python - 预期密集输入具有形状 (7,),但得到形状为 (1,) 的数组

标签 python tensorflow keras

我正在尝试根据从一些图像中提取的特征来训练模型,模型训练得很好,但是当我尝试 model.predict 时,它给了我这个错误。 “预计dense_input的形状为(7,),但得到的数组的形状为(1,)” 我了解输入的形状,但错误很奇怪。现在对我来说没有任何意义,我试图打印我给 model.predict 的输入的形状,它很好。

import numpy as np

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation

trainX = np.array(train_set)

trainY = np.array(train_labels)

model = Sequential()

model.add(Dense(8, input_dim=7, activation='relu'))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(trainX, trainY, nb_epoch=1200, batch_size=2, verbose=2)
model.save('my_model.h5') 

for i in np.array(test_set):
    print(i.shape)
    dataPrediction = model.predict(i)
    print (dataPrediction, '<--- Predicted number')
    print (test_labels[i],' <-- Correct answer \n')

print(i.shape) 给我 (7,) 但它给了我错误 检查输入时出错:期望dense_input具有形状(7,),但得到形状为(1,)的数组

最佳答案

这是因为您的模型需要一组样本,但您一次只给它一个样本。

因此,它将样本中的每个特征视为形状 (1,) 的单个样本,这对它来说没有意义,因为您大概有 7 个特征,因此它期望样本为形状(7,)

您可以执行model.predict(np.array(test_set))

关于python - 预期密集输入具有形状 (7,),但得到形状为 (1,) 的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55844330/

相关文章:

python - 如何使用大量 bool 属性创建高效的 Google-App-Engine 架构

python - 从 requirements.txt 安装 PyTorch

python - 设置 celery 周期性任务

python - 决定是否根据特征条件更新权重

python - 如何拥有一个没有距离较近的元素对的数组

neural-network - Keras 的 fit_generator 中 nb_epoch 的目的是什么?

python - 如何让 OpenERP 中的字段仅在特定的工作流程状态下需要?

python - tensorflow 2.0 : Add image preprocessing step in a saved model

python - tf.keras.models.save_model 和优化器警告

python - 为什么从 Keras 1.2.2 更改为 Keras 2.0.5 时 keras 代码会收到错误消息