为什么我不能以批次的方式输入我的Keras模型?

我试图以批次的方式输入一个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)

enter image description here


回答:

我不太确定你想做什么,但这是一个可行的示例:

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)

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注