gpt4 book ai didi

python - 使用 pandas 和 statsmodels 预测 future

转载 作者:行者123 更新时间:2023-11-30 22:24:51 24 4
gpt4 key购买 nike

我需要做的是根据这些“要求”绘制 future 温度:“假设温度大致是二氧化碳排放量的线性函数,从最近的数据点估计线性函数的系数(使用过去 2 个就可以了,如果你想更彻底的话,使用过去 10 个左右也可以)。此外,假设二氧化碳排放量的增长率为与今天相同(即,如果 2016 年二氧化碳排放量比2015 年,2017 年二氧化碳排放量将比 2016 年多 X 吨)”。

我有 2 个数据集,一个包含每年每个月的温度,另一个包含每年的碳水平。

(发布合并和缩短的一个,因为它不是那么大,但如果看到它们未经修改更有帮助,那么我也可以发布它,你可以在我发布代码的地方看到它是如何完成的)

Year    Carbon    June

2000 6727 20.386
2001 6886 20.445
2002 6946 20.662
2003 7367 20.343
2004 7735 20.242
2005 8025 20.720
2006 8307 20.994
2007 8488 20.661
2008 8738 20.657
2009 8641 20.548
2010 9137 21.027
2011 9508 20.915
2012 9671 21.172

到目前为止,我所做的是将两个数据集合并在一起,然后尝试预测 future 几年一个月的温度,我将其限制为 2000-2012 年,只是为了使其更简单,并确保两个表都有长度相同,一张 table 比另一张 table 长。我对 python 和编码非常陌生,我不知道如何做到这一点,下面你可以看到我到目前为止所做的尝试:

data1 = pd.read_csv("co2.csv", sep=',')
data2 = pd.read_csv("temperature.csv", sep=',')

data1 = data1.set_index('Year')
data2 = data2.set_index('Year')

data3 = data1.loc["2000":"2012"]

data4 = data2.loc["2000":"2012"]

data4 = data4.loc[:, "June":"June"]

data5 = pd.merge(data3,data4, how= 'left', left_index =True , right_index=True)

x = data5["Carbon"]

y = data5["June"]

model = sm.OLS(y,x).fit()

prediction = model.predict(x)

prediction.plot()


plt.show()

最佳答案

方法OLS.predict不要将 x 作为参数,而应将模型参数(以及最终的外生数据)作为参数。此外,你必须给X添加一个常数,否则它会迫使线性回归通过原点。这是一个例子:

import pandas as pd
import statsmodels.api as sm
import matplotlib.pyplot as plt
from StringIO import StringIO

data = StringIO("""
Year Carbon June
2000 6727 20.386
2001 6886 20.445
2002 6946 20.662
2003 7367 20.343
2004 7735 20.242
2005 8025 20.720
2006 8307 20.994
2007 8488 20.661
2008 8738 20.657
2009 8641 20.548
2010 9137 21.027
2011 9508 20.915
2012 9671 21.172
""")

# Model training
df = pd.read_table(data, index_col=0, sep='\s+')
Y_train = df['June']
X_train = df['Carbon']
X_train = sm.add_constant(X_train) # add this to your code
model = sm.OLS(Y_train, X_train)
results = model.fit()

# Prediction of future values
future_carbon = range(9700, 10000, 50)
X_pred = pd.DataFrame(data=future_carbon, columns=['Carbon'])
X_pred = sm.add_constant(X_pred)
prediction = model.predict(results.params, X_pred)

# Plot
plt.figure()
plt.plot(X_train['Carbon'], model.predict(results.params), '-r', label='Linear model')
plt.plot(X_pred['Carbon'], prediction, '--r', label='Linear prediction')
plt.scatter(df['Carbon'], df['June'], label='data')
plt.xlabel('Carbon')
plt.ylabel('June temperature')
plt.legend()
plt.show()

enter image description here

关于python - 使用 pandas 和 statsmodels 预测 future ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47714805/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com