我试图以批次的方式输入一个Sequential模型。为了重现我的示例,假设我的数据是:
X = np.random.rand(432,24,1)Y = np.random.rand(432,24,1)
我的目标是以批次的方式输入模型,每次24个点(24 x 1向量),重复432次。
我构建的模型如下:
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.3, random_state=12)model = keras.Sequential([ #keras.layers.Flatten(batch_input_shape=(None, 432, 2)), keras.layers.Dense(64, activation=tf.nn.relu), keras.layers.Dense(2, activation=tf.nn.sigmoid),])model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])history = model.fit(X_train, y_train, epochs=200, batch_size=32, validation_split=0.3)test_loss, test_acc = model.evaluate(X_test, y_test)print('Model loss:', test_loss, 'Model accuracy: ', test_acc)
然而,我得到了以下错误:
ValueError: Input 0 of layer dense_25 is incompatible with the layer: expected axis -1 of input shape to have value 864 but receivedinput with shape (None, 432)
回答:
我不太确定你想做什么,但这是一个可行的示例:
import tensorflow as tffrom sklearn.model_selection import train_test_splitX = np.random.rand(432, 24)Y = np.random.randint(2, size=(432, 2))X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.3, random_state=12)model = tf.keras.Sequential([ tf.keras.layers.Dense(64, activation=tf.nn.relu), tf.keras.layers.Dense(2, activation=tf.nn.sigmoid),])model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])history = model.fit(X_train, y_train, epochs=200, batch_size=32, validation_split=0.3)test_loss, test_acc = model.evaluate(X_test, y_test)print('Model loss:', test_loss, 'Model accuracy: ', test_acc)
请注意,你的数据X
的形状是(432, 24)
,你的标签Y
的形状是(432, 2)
。我移除了你的Flatten
层,因为如果你的数据形状是(432, 24)
,这个层没有太大意义。你可以在训练模型后像这样进行预测:
X_new = np.random.rand(1, 24)Y_new = model.predict(X_new)print(Y_new)