添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
浏览 408

LSTM模型预测出错

LSTM多变量时间序列代码
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM
from tensorflow.keras.layers import Dense, Dropout
import pandas as pd
from matplotlib import pyplot as plt
from sklearn.preprocessing import MinMaxScaler
import seaborn as sns

df=pd.read_csv("train.csv",parse_dates=["Date"],index_col=[0])
df.shape
df.head()
df.tail()
test_split=round(len(df)*0.20)
test_split
df_for_training=df[:-1041]
df_for_testing=df[-1041:]
scaler = MinMaxScaler(feature_range=(0,1))
df_for_training_scaled = scaler.fit_transform(df_for_training)
#scaler = MinMaxScaler(feature_range=(0,1))
df_for_testing_scaled=scaler.transform(df_for_testing)

def createXY(dataset,n_past):
dataX = []
dataY = []
for i in range(n_past, len(dataset)):
dataX.append(dataset[i - n_past:i, 0:dataset.shape[1]])
dataY.append(dataset[i,0])
return np.array(dataX),np.array(dataY)
trainX,trainY=createXY(df_for_training_scaled,30)
testX,testY=createXY(df_for_testing_scaled,30)

from tensorflow.keras.wrappers.scikit_learn import KerasRegressor
from sklearn.model_selection import GridSearchCV

def build_model(optimizer):
grid_model = Sequential()
grid_model.add(LSTM(50,return_sequences=True,input_shape=(30,5)))
grid_model.add(LSTM(50))
grid_model.add(Dropout(0.2))
grid_model.add(Dense(1))

grid_model.compile(loss = 'mse',optimizer = optimizer)
return grid_model

grid_model = KerasRegressor(build_fn=build_model,verbose=1,validation_data=(testX,testY))

parameters = {'batch_size' : [16,20],
'epochs' : [8,10],
'optimizer' : ['adam','Adadelta'] }

grid_search = GridSearchCV(estimator = grid_model,
param_grid = parameters,
cv = 2)

#grid_search = grid_search.fit(trainX,trainY)
grid_search = grid_search.fit(trainX,trainY)
#grid_search.best_params
my_model=grid_search.best_estimator_.model
prediction=my_model.predict(testX)
print("prediction\n", prediction)
print("\nPrediction Shape-",prediction.shape)

scaler.inverse_transform(prediction)
prediction_copies_array = np.repeat(prediction,5, axis=-1)
pred=scaler.inverse_transform(np.reshape(prediction_copies_array,(len(prediction),5)))[:,0]

original_copies_array = np.repeat(testY,5, axis=-1)

original_copies_array.shape

original=scaler.inverse_transform(np.reshape(original_copies_array,(len(testY),5)))[:,0]

import matplotlib.pyplot as plt
plt.plot(original, color = 'red', label = 'Real Stock Price')
plt.plot(pred, color = 'blue', label = 'Predicted Stock Price')
plt.title(' Stock Price Prediction')
plt.xlabel('Time')
plt.ylabel(' Stock Price')
plt.legend()
plt.show()

df_30_days_past=df.iloc[-30:,:]
df_30_days_future=pd.read_csv("test.csv",parse_dates=["Date"],index_col=[0])
df_30_days_future["Open"]=0
df_30_days_future=df_30_days_future[["Open","High","Low","Close","Adj Close"]]
old_scaled_array=scaler.transform(df_30_days_past)
new_scaled_array=scaler.transform(df_30_days_future)
new_scaled_df=pd.DataFrame(new_scaled_array)
new_scaled_df.iloc[:,0]=np.nan
full_df=pd.concat([pd.DataFrame(old_scaled_array),new_scaled_df]).reset_index().drop(["index"],axis=1)
full_df_scaled_array=full_df.values
(60, 5)
all_data=[]
time_step=30
for i in range(time_step,len(full_df_scaled_array)):
data_x=[]
data_x.append(full_df_scaled_array[i-time_step:i,0:full_df_scaled_array.shape[1]])
data_x=np.array(data_x)
prediction=my_model.predict(data_x)
all_data.append(prediction)
full_df.iloc[i,0]=prediction

new_array=np.array(all_data)
new_array=new_array.reshape(-1,1)
prediction_copies_array = np.repeat(new_array,5, axis=-1)
y_pred_future_30_days = scaler.inverse_transform(np.reshape(prediction_copies_array,(len(new_array),5)))[:,0]

from tensorflow.keras.models import Model
from tensorflow.keras.models import load_model

my_model.save('Model_future_value.h5')
print('Model Saved!')
scaler
import pickle
scalerfile = 'scaler_model_future_value.pkl'
pickle.dump(scaler, open(scalerfile, 'wb'))

错误提示LFile "G:/时间序列/Multivariate-time-series-forecasting-using-LSTM-main/forecast.py", line 57, in
grid_search = grid_search.fit(trainX,trainY)
File "C:\Users\dell\AppData\Local\Programs\Python\Python37\lib\site-packages\sklearn\model_selection_search.py", line 805, in fit
base_estimator = clone(self.estimator)
File "C:\Users\dell\AppData\Local\Programs\Python\Python37\lib\site-packages\sklearn\base.py", line 92, in clone
"either does not set or modifies parameter %s" % (estimator, name)
RuntimeError: Cannot clone object <tensorflow.python.keras.wrappers.scikit_learn.KerasRegressor object at 0x0000017C9E8D5828>, as the constructor either does not set or modifies parameter validation_data

0

  • 编辑 收藏 删除 结题
  • 追加酬金 (90%的用户在追加酬金后获得了解决方案)

    当前问题酬金

    ¥ 0 (可追加 ¥500)

    支付方式

    扫码支付

    加载中...

    提供问题酬金的用户不参与问题酬金结算和分配

    支付即为同意 《付费问题酬金结算规则》

    6 条回答 默认 最新

    查看更多回答(-1条)

    报告相同问题?

    问题事件

    • 创建了问题 3月8日

    悬赏问题

    • ¥15 java中ftp上传文件到服务端上传30M文件成功,但得不到响应 调用gitlab api问题 stm32加ax58100开发ethercat从站 如何使用 vue-plugin-hiprint 打印 并排标签 问问字符串的排序(选择排序法)最后交换的时候为什么不能用strcpy,而必须交换指针的指向呢 安卓系统原代码和root jSignature签名组件后退失效(html5) vscode连接远程后如何把本地文件夹连上服务器