gpt4 book ai didi

python - keras 中输入数据不兼容错误,维度不匹配 ValueError

转载 作者:行者123 更新时间:2023-11-30 09:41:46 26 4
gpt4 key购买 nike

我试图了解如何在 Keras 上编写 Conv1D 模型,但我不断遇到维度不匹配错误。现在 x_train = [1000,294] (1000 个项目和 294 个特征)和 y_train = [1000,9] (1000 个项目和 9 个标签)。我不断收到错误消息需要 3 个维度,但得到了 2 个维度。但我尝试修复它,它又出现了。 github 上的一些问题建议使用 Flatten() 但它已经存在并且没有运气。知道我缺少什么吗?谢谢

我得到的错误,

  1. ValueError:输入 0 与层 conv1d_1 不兼容:预期ndim=3,找到ndim=2

代码包含在下面

tb = [keras.callbacks.TensorBoard(log_dir='./dllogs')]

main_input = Input(shape=(294, ), dtype='float32')

x_train = np.array(x_train)
y_train = np.array(y_train)

x_dev = np.array(x_dev)
y_dev = np.array(y_dev)
x = Conv1D(128, 5, activation='relu')(main_input)
x = MaxPooling1D(5)(x)
x = Conv1D(128, 5, activation='relu')(x)
x = MaxPooling1D(5)(x)
x = Conv1D(128, 5, activation='relu')(x)
x = MaxPooling1D(35)(x)
x = Flatten()(x)
x = Dropout(0.25)(x)
x = Dense(128, activation='relu')(x)

preds = Dense(pred_dim, activation='softmax')(x)
model = Model(inputs=main_input, outputs=preds)
model.compile(optimizer='adam', loss='kullback_leibler_divergence', metrics=['accuracy'])
print(model.summary())
history_NN = model.fit(x_train, y_train, batch_size=BATCHSIZE, epochs=EPOCHS, callbacks=tb, validation_data=(x_dev, y_dev))

回答

  1. 尺寸是一个引起麻烦的问题,Today 的评论解决了这个问题。
  2. 接下来是池化尺寸,这是池化后尺寸的减少,所以在整个过程之后,当我更改它时,最终池化时没有 35 张幻灯片。固定的。

结果代码,

tb = [keras.callbacks.TensorBoard(log_dir='./dllogs')]
main_input = Input(shape=(294, 1))#changed

x_train = np.array(x_train)
y_train = np.array(y_train)

x_dev = np.array(x_dev)
y_dev = np.array(y_dev)
x_train = np.expand_dims(x_train, axis=-1) #changed
x_dev = np.expand_dims(x_dev, axis=-1) #changed
x = Conv1D(128, 5, activation='relu')(main_input)
x = MaxPooling1D(5)(x)
x = Conv1D(128, 5, activation='relu')(x)
x = MaxPooling1D(5)(x)
x = Conv1D(128, 5, activation='relu')(x)
x = MaxPooling1D(11)(x)
x = Flatten()(x)
x = Dropout(0.25)(x)
x = Dense(128, activation='relu')(x)

preds = Dense(pred_dim, activation='softmax')(x)
model = Model(inputs=main_input, outputs=preds)
model.compile(optimizer='adam', loss='kullback_leibler_divergence', metrics=['accuracy'])
print(model.summary())
history_NN = model.fit(x_train, y_train, batch_size=BATCHSIZE, epochs=EPOCHS, callbacks=tb, validation_data=(x_dev, y_dev))

最佳答案

Conv1D 层需要形状为 (sequence_length, num_features)序列输入。看起来你有长度为 294 的序列,具有 一个 特征;因此,每个输入样本需要具有 (294,1) 的形状(而不是 (294,))。要修复此问题,您可以使用 np.expand_dims 将大小为 1 的第三个维度添加到输入数据中:

x_train = np.expand_dims(x_train, axis=-1)
x_dev = np.expand_dims(x_dev, axis=-1)

main_input = Input(shape=(294, 1)) # fix the input shape here as well

关于python - keras 中输入数据不兼容错误,维度不匹配 ValueError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57714476/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com