层顺序的输入0与该层不兼容:

时间:2020-09-19 07:11:33

标签: python tensorflow prediction

我正在尝试预测基本的股价模型。这是我的代码

data = pd.read_csv("total_cases.csv")
x = data["date"]
world_cases = data["Turkey"].fillna(0)
time = np.arange(len(world_cases), dtype="float32")

split_time = 200
x_train = time[:split_time]
x_valid = time[split_time:]

y_train = world_cases[:split_time]
y_valid = world_cases[split_time:]
window_size = 20
batch_size = 32
shuffle_buffer_size=1000
train_data = tf.data.Dataset.from_tensor_slices((x_train, y_train))
valid_data = tf.data.Dataset.from_tensor_slices((x_valid, y_valid))
model = Sequential()
model.add(LSTM(16, return_sequences=True))

model.add(LSTM(16))

model.add(Dense(16, activation='relu'))
model.compile(optimizer='adam', loss='mae', metrics=['mae'])

r = model.fit(train_data, validation_data=valid_data, epochs=100)

运行模型时,引发了错误

ValueError: Input 0 of layer sequential is incompatible with the layer: expected ndim=3, found ndim=0. Full shape received: []

编辑 这是csv文件的一部分,world_cases-土耳其-列

0           0.0
1           0.0
2           0.0
3           0.0
4           0.0
         ...
258    291162.0
259    292878.0
260    294620.0
261    296391.0
262    298039.0

1 个答案:

答案 0 :(得分:0)

我重现了您的问题。

import tensorflow as tf
inputs = tf.random.normal([])
lstm = tf.keras.layers.LSTM(4)
output = lstm(inputs)
print(output.shape)

输出

ValueError: Input 0 of layer lstm_1 is incompatible with the layer: expected ndim=3, found ndim=0. Full shape received: ()

问题在于输入数据形状

由于 Tensorflow.Keras LSTM 需要形状 3D 的输入。按此修改您的输入

inputs: A 3D tensor with shape [batch, timesteps, feature] 
model.add(LSTM(16,return_sequences=False)).

工作示例代码

import tensorflow as tf
inputs = tf.random.normal([32, 10, 8])
lstm = tf.keras.layers.LSTM(4)
output = lstm(inputs)
print(output.shape)

输出

(32, 4)