首页 > 解决方案 > Keras model.predict() 抛出 ValueError

问题描述

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])

标签: machine-learningkerastf.kerasconv-neural-network

解决方案


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

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'))

我希望这对你有帮助。


推荐阅读