【发布时间】:2020-08-11 02:38:24
【问题描述】:
我正在尝试在 Python 中执行真正的样本外预测。我已经研究了几天,但没有运气。
我遇到了下面显示的用于股票价格预测的示例代码,我试图对其进行修改以预测由热化学过程(时间序列问题)引起的温度变化。据我了解,示例代码将历史数据集(例如 100 个数据点)移动 'n' 天,然后将剩余的数据点分成两组进行训练(80%)和测试(20%)然后它继续预测/估计预定“n”天的股票价值。
是否可以修改此代码以预测历史数据集之外的真实样本外因变量?
感谢您的帮助。
from pandas_datareader import data
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
df = data.DataReader('FB', 'yahoo', start= '2015-01-01', end='2020-04-27')
df = df[['Close']]
print (df.tail())
# variable for predicting 'n' days out in the future
forecast = 1
# create another column called prediction that is shifted n days out
df['predicted'] = df[['Close']].shift(-forecast)
# Convert the dataframe to numpy array
X = np.array(df.drop(['predicted'],1))
# Remove the last n rows
X = X[:-forecast]
# Create the dependent dataset
y = np.array(df['predicted'])
# Get all the y values except the last n rows
y = y[:-forecast]
# Split data into %training and %testing
x_train, x_test, y_train, y_test = train_test_split(X, y, test_size = 0.2)
# Create and train the linear regression model
lr = LinearRegression()
lr.fit(x_train, y_train)
# Testing the model using score (returns the coefficient of determination R^2)
lr_score = lr.score(x_test, y_test)
# Create x_forecast equals to the last n rows of the original dataset from the close column
x_forecast = np.array(df.drop(['predicted'],1))[-forecast:]
lr_prediction = lr.predict(x_forecast)
print (lr_score)
print (lr_prediction)
【问题讨论】:
-
问题有点不清楚。第 101 个因变量是什么意思?
-
我刚刚修改了问题。我需要代码来预测历史数据集中最后一天后一天的因变量值。
标签: python