【问题标题】:Keras model.predict() throwing ValueErrorKeras model.predict() 抛出 ValueError
【发布时间】:2020-05-16 00:26:33
【问题描述】:

X 和 Y 的形状分别为 (89362, 5) 和 (89362,)。

x_train, x_test, y_train, y_test = train_test_split(X, Y,
                                                    test_size = 0.3, 
                                                    random_state = 1)


x_train.shape, y_train.shape = ((62553, 5), (62553,))
x_test.shape, y_test.shape = ((26809, 5), (26809,))

将向量重新整形为:

torch.Size([1, 62553, 5]), torch.Size([1, 62553])
torch.Size([1, 26809, 5]), torch.Size([1, 26809])

模型定义为

n_steps = 62553
n_features = 5


model = Sequential()
model.add(Conv1D(filters=64, kernel_size=2, activation='relu', input_shape=(n_steps, n_features)))
model.add(MaxPooling1D(pool_size=2))
model.add(Flatten())
model.add(Dense(50, activation='relu'))
model.add(Dense(62553))
model.compile(optimizer='adam', loss='mse')
model.fit(x_train, y_train, epochs=10, verbose=0)

使用 x_test 进行预测时,会抛出值错误

yhat = model.predict(x_test, verbose=0)
print(yhat)

ValueError: Error when checking input: expected conv1d_4_input to have shape (62553, 5) but got array with shape torch.Size([26809, 5])

【问题讨论】:

  • 我认为你不需要这一行:model.add(Dense(62553))。
  • 是我的想法,还是您在 Keras 中使用 Pytorch 张量?
  • @desertnaut 你是对的,那是错误的。我正在尝试 Pytorch 和 Keras,但代码混淆了。

标签: machine-learning keras tf.keras conv-neural-network


【解决方案1】:

发生这种情况是因为您在此处指定了固定大小:

model.add(Conv1D(filters=64, kernel_size=2, activation='relu', input_shape=(n_steps, n_features)))

一旦您将其他内容传递给模型,模型仍会期望具有固定尺寸的尺寸:

n_steps = 62553
n_features = 5

删除 input_shape 参数应该可以解决这个问题:

model.add(Conv1D(filters=64, kernel_size=2, activation='relu'))

希望对你有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-05
    • 1970-01-01
    • 2020-04-29
    • 1970-01-01
    • 1970-01-01
    • 2018-02-04
    • 1970-01-01
    相关资源
    最近更新 更多