[Python] Trying to create predicted curves of CO2 using observed data and using a non-linear...

Discussão em 'Python' iniciado por Stack, Fevereiro 18, 2025.

  1. Stack

    Stack Membro Participativo

    This is all being done in python. I have a data frame with CO2 data and the relevant columns are 'year' (year CE) and 'co2' (in ppm). The data ranges from 1959 to 2024 and this is my observed data. I split the data into two sections and I put the 1959 to 2004 data into a function called co2_model (has an equation to try to recreate the pattern of the observed data) to get parameters I can use to calculate predicted values of both periods I created previously. However, when I plot the predicted data against the observed data, I get straight lines for the predicted data when I was expecting sine curves (see pictures to see what I mean)

    This is my code

    # Build model based on equation
    def co2_model(x, a, b, A, phi, c):
    # Model containing linear, quadratic and sinusoidal component
    return (a*x) + (b*(x**2)) + (A*np.sin((2*np.pi*x)+ phi)) + c

    x = (co2['time']).values - co2['time'].values[0]
    y = co2['co2'].values

    # Split data into training and validation periods
    co2_train = co2[co2['year'] <= 2004]
    co2_val = co2[co2['year'] > 2004]

    # Rescaling time periods and specifying dependent variable
    x_train = co2_train['year'].values - co2_train['year'].values[0]
    y_train = co2_train['co2'].values

    x_val = co2_val['year'].values - co2_val['year'].values[0]
    y_val = co2_val['co2'].values

    # Fit the co2 model to the training data
    params_train, covar_train = curve_fit(co2_model, x_train, y_train)
    a, b, A, phi, c = params_train # Extract fitted parameters

    #Calculate predicted values for the training and validation data
    y_train_predict = co2_model(x_train, a, b, A, phi, c)
    y_val_predict = co2_model(x_val, a, b, A, phi, c)

    # Plot the original data with the predictions
    plt.figure(figsize=(15, 6))
    plt.scatter(x, y, color='grey', label='Observed temperature', alpha=0.5)

    # Plot the training period predictions
    plt.plot(x_train, y_train_predict, label='Training Period', color='blue', linestyle='--')

    # Plot the validation period predictions
    plt.plot(x_val, y_val_predict, label='Validation Period', color='red', linestyle='--')

    plt.xlabel('Year (CE)')
    plt.ylabel('CO$_2$ (ppm)')

    # Show the plot
    plt.show()


    This is what I get The graph I get

    But I was expecting something similar to this but one-half red and the other blue Different curve

    Please let me know if I am just making a silly mistake

    Continue reading...

Compartilhe esta Página