gpt4 book ai didi

python线性回归按日期预测

转载 作者:太空狗 更新时间:2023-10-30 01:45:48 26 4
gpt4 key购买 nike

我想用简单的线性回归预测 future 某个日期的值,但由于日期格式的原因我无法做到。

这是我的数据框:

data_df = 
date value
2016-01-15 1555
2016-01-16 1678
2016-01-17 1789
...

y = np.asarray(data_df['value'])
X = data_df[['date']]
X_train, X_test, y_train, y_test = train_test_split
(X,y,train_size=.7,random_state=42)

model = LinearRegression() #create linear regression object
model.fit(X_train, y_train) #train model on train data
model.score(X_train, y_train) #check score

print (‘Coefficient: \n’, model.coef_)
print (‘Intercept: \n’, model.intercept_)
coefs = zip(model.coef_, X.columns)
model.__dict__
print "sl = %.1f + " % model.intercept_ + \
" + ".join("%.1f %s" % coef for coef in coefs) #linear model

我尝试转换日期失败

data_df['conv_date'] = data_df.date.apply(lambda x: x.toordinal())

data_df['conv_date'] = pd.to_datetime(data_df.date, format="%Y-%M-%D")

最佳答案

线性回归不适用于日期数据。因此我们需要将它转换成数值。下面的代码将日期转换成数值:

import datetime as dt
data_df['Date'] = pd.to_datetime(data_df['Date'])
data_df['Date']=data_df['Date'].map(dt.datetime.toordinal)

关于python线性回归按日期预测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40217369/

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