Python 调用LSTM模型的预测函数时,获取有关输入形状的错误

Python 调用LSTM模型的预测函数时,获取有关输入形状的错误,python,keras,deep-learning,lstm,Python,Keras,Deep Learning,Lstm,我安装了一个lstm模型。每个x和y变量有100个观测值。我使用80个值来训练模型,20个值来评估模型 import numpy as np import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers from tensorflow.keras import Sequential from tensorflow.keras.layers import Dense, LSTM, D

我安装了一个lstm模型。每个x和y变量有100个观测值。我使用80个值来训练模型,20个值来评估模型

import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense, LSTM, Dropout

input_features=1
time_stamp=100
out_features=1
x_input=np.random.random((time_stamp,input_features))
y_input=np.random.random((time_stamp,out_features))

train_x=x_input[0:80,:]
test_x=x_input[80:,:]

train_y=y_input[0:80,:]
test_y=y_input[80:,:]
然后,在将数据输入LSTM函数之前,我根据需要对数据进行了重塑。(例如:对于训练x:(样本、时间步、特征)=(1,80,1))

然后,我能够使用以下代码行成功地拟合模型:

model = Sequential()
model.add(LSTM(20,activation = 'relu', return_sequences = True,input_shape=(dataXtrain.shape[1], 
dataXtrain.shape[2])))
model.add(Dense(1))
model.compile(loss='mean_absolute_error', optimizer='adam')
model.fit(dataXtrain, dataYtrain, epochs=100, batch_size=10, verbose=1)
但是当我预测测试数据的模型时,我得到了这个错误

y_pred = model.predict(dataXtest)
Error when checking input: expected lstm_input to have shape (80, 1) but got array with shape (20, 1)
有人能帮我找出这里的问题吗


谢谢

看来问题在于数据准备。我认为你应该划分你的样本(而不是时间步长)来训练和测试数据,训练和测试样本的形状应该相同,就像
(无,时间步长,特征)

由于只有一个样本包含100个观测值(时间步长),因此可以将数据划分为包含小规模时间步长序列的样本。例如:

n_samples = 20
input_features = 1
time_stamp = 100
out_features = 1
x_input = np.random.random((1, time_stamp, input_features))
y_input = np.random.random((1, time_stamp, out_features))

new_time_stamp = time_stamp//n_samples
x_input = x_input.reshape(n_samples, new_time_stamp, input_features)
y_input = y_input.reshape(n_samples, new_time_stamp, out_features)

dataXtrain = x_input[:16,...]
dataXtest = x_input[16:,...]

dataYtrain = y_input[:16,...]
dataYtest = y_input[16:,...]
或者,您可以收集更多的数据样本,每个样本包含100个时间步(这取决于您的应用程序和现有数据)

此外,您还可以在Keras中全面查看和解释使用LSTM

n_samples = 20
input_features = 1
time_stamp = 100
out_features = 1
x_input = np.random.random((1, time_stamp, input_features))
y_input = np.random.random((1, time_stamp, out_features))

new_time_stamp = time_stamp//n_samples
x_input = x_input.reshape(n_samples, new_time_stamp, input_features)
y_input = y_input.reshape(n_samples, new_time_stamp, out_features)

dataXtrain = x_input[:16,...]
dataXtest = x_input[16:,...]

dataYtrain = y_input[:16,...]
dataYtest = y_input[16:,...]