检查输入时出错:预期density_input的形状为(21,),但数组的形状为(1,)

时间:2018-09-06 18:50:09

标签: python tensorflow machine-learning neural-network keras

如何固定输入数组以满足输入形状?

我试图按here所述转置输入数组,但是错误是相同的。

ValueError:检查输入时出错:预期density_input具有形状(21,)但具有形状(1,)的数组

import tensorflow as tf
import numpy as np

model = tf.keras.models.Sequential([
  tf.keras.layers.Dense(40, input_shape=(21,), activation=tf.nn.relu),
  tf.keras.layers.Dropout(0.2),
  tf.keras.layers.Dense(1, activation=tf.nn.softmax)
])
model.compile(optimizer='adam',
              loss='categorical_crossentropy',
              metrics=['accuracy'])

arrTest1 = np.array([0.1,0.1,0.1,0.1,0.1,0.5,0.1,0.0,0.1,0.6,0.1,0.1,0.0,0.0,0.0,0.1,0.0,0.0,0.1,0.0,0.0])
scores = model.predict(arrTest1)
print(scores)

1 个答案:

答案 0 :(得分:3)

您的测试数组arrTest1是21的一维向量:

>>> arrTest1.ndim
1

您要提供给模型的是一排21个功能。您只需要再加上一组括号即可:

arrTest1 = np.array([[0.1, 0.1, 0.1, 0.1, 0.1, 0.5, 0.1, 0., 0.1, 0.6, 0.1, 0.1, 0., 0., 0., 0.1, 0., 0., 0.1, 0., 0.]])

现在您有一个包含21个值的行:

>>> arrTest1.shape
(1, 21)