具有时间序列日期的线性回归训练

时间:2019-06-06 13:06:05

标签: python numpy multidimensional-array linear-regression sklearn-pandas

我是sklearn的新手。我有一项工作要做线性回归,逻辑回归等。我正在尝试创建数据以比较结果。我的数据如下:

Closing_Price   Daily_Returns   Daily_Returns_1 Daily_Returns_2 Daily_Returns_3 Daily_Returns_4 Daily_Returns_5
Date                            
1980-12-22  0.53    0.058269    0.040822    0.042560    0.021979    -0.085158   -0.040005
1980-12-23  0.55    0.037041    0.058269    0.040822    0.042560    0.021979    -0.085158
1980-12-24  0.58    0.053110    0.037041    0.058269    0.040822    0.042560    0.021979
1980-12-26  0.63    0.082692    0.053110    0.037041    0.058269    0.040822    0.042560
1980-12-29  0.64    0.015748    0.082692    0.053110    0.037041    0.058269    0.040822

我想做的是使用sklearn线性回归来开始计算和绘制结果以及每日收益。这就是我正在做的:

from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression as lr
from sklearn.linear_model import LogisticRegression as lor
X = apple['Closing_Price'].values.reshape(-1,1)
y = apple['Daily_Returns'].values.reshape(-1,1)
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size = 0.2)
LinReg = lr()
LinReg.fit(X_train,y_train)
LinRegPred = LinReg.predict(X_test)

我的问题:是否可以创建一个2D数组,其中第1列是原始数据集数据帧的索引值,第2列是预测的线性回归结果?

apple.index处:

DatetimeIndex(['1980-12-22', '1980-12-23', '1980-12-24', '1980-12-26',
               '1980-12-29', '1980-12-30', '1980-12-31', '1981-01-02',
               '1981-01-05', '1981-01-06',
               ...
               '2019-05-22', '2019-05-23', '2019-05-24', '2019-05-28',
               '2019-05-29', '2019-05-30', '2019-05-31', '2019-06-03',
               '2019-06-04', '2019-06-05'],
              dtype='datetime64[ns]', name='Date', length=9695, freq=None)

1 个答案:

答案 0 :(得分:0)

您可以将train_test_split改成数据框

from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression as lr
from sklearn.linear_model import LogisticRegression as lor
import numpy as np

data_train, data_test,  = train_test_split(apple,test_size = 0.2)
X_train = data_train['Closing_Price'].values.reshape(-1,1)
y_train = data_train['Daily_Returns'].values.reshape(-1,1)
X_test = data_test['Closing_Price'].values.reshape(-1,1)
y_test = data_test['Daily_Returns'].values.reshape(-1,1)
LinReg = lr()
LinReg.fit(X_train,y_train)
LinRegPred = LinReg.predict(X_test)

然后您就可以访问索引并创建2D数组,如下所示:

from datetime import datetime
predictedWithIndexes = [list(index.astype(str)), list(LinRegPred)]
pdi = pd.DataFrame(predictedWithIndexes)
pdi = pdi.T
pdi.columns = ['Date','Predicted_Linear_Regression']
pdi['Predicted_Linear_Regression'] = pdi['Predicted_Linear_Regression'].astype(float)
pdi['Date'] = pd.to_datetime(pdi['Date'].str[0])

我希望我已经回答了您的问题