ValueError: 层顺序的输入 0 与层不兼容::预期 min_ndim=4,发现 ndim=3。收到的完整形状:[无、32、32]

时间:2021-03-29 21:50:06

标签: python tensorflow machine-learning keras deep-learning

import imageio
import glob
import numpy as np
import tensorflow as tf
from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt

trainImages = []
for imagePath in glob.glob('C:/Users/razva/*.png'):
     image = imageio.imread(imagePath)
     trainImages.append(image)
trainImages = np.array(trainImages)

f = open('C:/Users/razva/train.txt')
trainLabels = f.readlines()
for i in range(len(trainLabels)):
     trainLabels[i] = int(trainLabels[i][11])
trainLabels = np.array(trainLabels)

validationImages = []
for imagePath in glob.glob('C:/Users/razva/*.png'):
     image = imageio.imread(imagePath)
     validationImages.append(image)
validationImages = np.array(validationImages)
f = open('C:/Users/razva/validation.txt')
validationLabels = f.readlines()
for i in range(len(validationLabels)):
     validationLabels[i] = int(validationLabels[i][11])
validationLabels = np.array(validationLabels)

mean_image = np.mean(trainImages, axis = 0)
sd = np.std(trainImages)
trainImages = (trainImages - mean_image) / sd

mean_image1 = np.mean(validationImages, axis = 0)
sd1 = np.std(validationImages)
validationImages = (validationImages - mean_image1) / sd1

model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))

model.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(10))

model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy'])

history = model.fit(trainImages, trainLabels, epochs=10, validation_data=(validationImages, validationLabels))

我有这个用于图像分类的 cnn,trainImages 和 trainLabel(从 0 到 8)是训练数据,validationImages 和 validationLabels 用于测试。图片是 32 * 32。我不能让这个算法工作,如果你发现更多错误,请告诉我。

1 个答案:

答案 0 :(得分:1)

我无法确切地说出问题出在哪里,因为我无法访问加载的图像,但问题是您提供的样本没有“通道”轴,在指定的 input_shape=(32, 32, 3) 中表示为大小为 3。每个样本(图像)必须有 3 个维度(宽度、高度、通道),但相反,您传递的样本只有 2 个维度(宽度和高度)。

这很可能是因为您可能仅使用一个通道加载灰度图像,而 numpy 并未明确指定轴。如果是这种情况,请确保 trainImagesvalidationImages 都具有形状 (32, 32, 1),否则只需使用 np.expand_dims(_trainImages_, axis=-1) (验证集相同),然后再将它们提供给模型。相应地,将第一个 Conv2D 层中的 input_shape 调整为 (32, 32, 1)。

希望它有帮助,否则让我了解更多细节。