我的資料集具有以下形狀:
y_train.shape,y_val.shape
((265, 2), (10, 2))
x_train.shape, x_val.shape
((265, 4), (10, 4))
我正在嘗試使用一個簡單的 RNN 模型
model=models.Sequential([layers.SimpleRNN(20,input_shape=(None,4),return_sequences=True),
layers.SimpleRNN(20,return_sequences=True),
layers.SimpleRNN(2),
])
model.compile(optimizer="Adam",
loss=tf.keras.losses.MeanSquaredError(),
metrics=["accuracy"])

當我將模型擬合到資料時,問題就出現了:
history=model.fit(x_train,y_train,
epochs=20,
validation_data=(x_val,y_val),
verbose=2)
我收到以下錯誤:
ValueError: Input 0 of layer sequential_12 is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: (None, 4)
我認為這與輸入有關......但我不明白是什么。
uj5u.com熱心網友回復:
第一件事輸入應該是 3D 形狀[batch, timesteps, feature]。
x_train并且x_val不遵循此規則。您可以通過以下方式輕松擴展其暗淡:
x_train = np.expand_dims(x_train, axis = -1) # (265, 4, 1)
x_val= np.expand_dims(x_val, axis = -1) # (10, 4, 1)
另一個問題是input_shape。它需要input_shape=(4,1)根據新的形狀x_train和x_val。所以正確的定義應該是:
model=models.Sequential([layers.SimpleRNN(20,input_shape=(4,1),return_sequences=True),
layers.SimpleRNN(20,return_sequences=True),
layers.SimpleRNN(2),
])
如果你想包含None在,input_shape那么你應該通過batch_input_shape.
model= tf.keras.Sequential([tf.keras.layers.SimpleRNN(20,batch_input_shape=(None, 4,1),
return_sequences=True),
tf.keras.layers.SimpleRNN(20,return_sequences=True),
tf.keras.layers.SimpleRNN(2),
])
這表明模型接受任何批量大小。
注意:如果您指定batch_input_shape, like, batch_input_shape=(32, 4,1),那么如果剩余批次的大小小于 ,則會拋出錯誤32。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/381040.html
上一篇:Tensorflow-FailedPreconditionError:找不到變數dense_24/bias。這可能意味著該變數已被洗掉
