Error when checking input: expected dense_input to have shape (21,) but got array with shape (1,)

走远了吗. 提交于 2019-12-22 18:48:10

问题


How to fix the input array to meet the input shape?

I tried to transpose the input array, as described here, but an error is the same.

ValueError: Error when checking input: expected dense_input to have shape (21,) but got array with shape (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:


Your test array, arrTest1, is a 1d vector of 21:

>>> arrTest1.ndim
1

What you are trying to feed your model is a row of 21 features. You simply need one more set of brackets:

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

And now you have a row with 21 values:

>>> arrTest1.shape
(1, 21)


来源:https://stackoverflow.com/questions/52210472/error-when-checking-input-expected-dense-input-to-have-shape-21-but-got-arra

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!