层顺序的输入 0 与层不兼容:预期 min_ndim=4,发现 ndim=2。收到完整形状:(无,1)

时间:2021-04-03 10:01:04

标签: python tensorflow keras

我正在尝试对我的模型进行预测

prediction = model.predict(validation_names)
print(prediction)

但我收到以下错误:

ValueError: Input 0 of layer sequential is incompatible with the layer: : expected min_ndim=4, found ndim=2. Full shape received: (None, 1)

我理解这是因为模型接受维度 4 的数据

型号:

model = tf.keras.models.Sequential([

          tf.keras.layers.Conv2D(16, (3,3), activation = 'relu', 
                                        input_shape = (300, 300, 3)),
          tf.keras.layers.MaxPooling2D(2,2),

          tf.keras.layers.Conv2D(32, (3,3), activation = 'relu'),
          tf.keras.layers.MaxPooling2D(2,2),

          tf.keras.layers.Conv2D(64, (3,3), activation = 'relu'),
          tf.keras.layers.MaxPooling2D(2,2),

          tf.keras.layers.Conv2D(64, (3,3), activation = 'relu'),
          tf.keras.layers.MaxPooling2D(2,2),

          tf.keras.layers.Flatten(),
          tf.keras.layers.Dense(512, activation = 'relu'),

          tf.keras.layers.Dense(3, activation = 'softmax')
])

如何处理预测数据来解决这个问题?

1 个答案:

答案 0 :(得分:0)

Conv2D 期望 4+D tensor with shape: batch_shape + (channels, rows, cols) if data_format='channels_first' or 4+D tensor with shape: batch_shape + (rows, cols, channels) if data_format='channels_last'

工作示例代码:

# The inputs are 28x28 RGB images with `channels_last` and the batch
# size is 4.
import tensorflow as tf
input_shape = (4, 28, 28, 3)
x = tf.random.normal(input_shape)
y = tf.keras.layers.Conv2D(2, 3, activation='relu', input_shape=input_shape[1:])(x)