检查输入时出错:预期dense_input 具有形状(21,) 但得到形状为(1,) 的数组

Den*_* P. 7 python machine-learning neural-network keras tensorflow

如何修复输入数组以满足输入形状?

我试图转输入数组,如所描述这里,但误差是相同的。

ValueError:检查输入时出错:预期dense_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)
Run Code Online (Sandbox Code Playgroud)

Tgs*_*591 8

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

>>> arrTest1.ndim
1
Run Code Online (Sandbox Code Playgroud)

您尝试提供给模型的是一行 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.]])
Run Code Online (Sandbox Code Playgroud)

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

>>> arrTest1.shape
(1, 21)
Run Code Online (Sandbox Code Playgroud)