python - ValueError : Error when checking input: expected conv2d_3_input to have shape (100, 100, 1) 但得到形状为 (100, 100, 3) 的数组

标签 python python-3.x keras neural-network image-recognition

当我尝试编写用于图像识别的神经网络时,出现错误:

ValueError: Error when checking input: expected conv2d_3_input to have shape (100, 100, 1) but got array with shape (100, 100, 3).

我的所有图像都是灰度,尺寸为100x100像素。 代码如下:

# Importing the Keras libraries and packages
import tensorflow as tf
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
# Initialising the CNN
classifier = Sequential()
# Step 1 - Convolution
classifier.add(Conv2D(32, (3, 3), input_shape = (100, 100, 1), activation = 'relu'))
# Step 2 - Pooling
classifier.add(MaxPooling2D(pool_size = (2, 2)))
# Adding a second convolutional layer
classifier.add(Conv2D(32, (3, 3), activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2, 2)))
# Step 3 - Flattening
classifier.add(Flatten())
# Step 4 - Full connection
classifier.add(Dense(units = 128, activation = 'relu'))
classifier.add(Dense(units = 1, activation = 'sigmoid'))
# Compiling the CNN
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
# Part 2 - Fitting the CNN to the images
from keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(rescale = 1./255,
shear_range = 0.2,
zoom_range = 0.2,
horizontal_flip = True)
test_datagen = ImageDataGenerator(rescale = 1./255)
training_set = train_datagen.flow_from_directory('E:/exercise/dataset/train',
target_size = (100, 100),
batch_size = 32,
color_mode = "grayscale",
class_mode = 'binary')
test_set = test_datagen.flow_from_directory('E:/exercise/dataset/test',
target_size = (100, 100),
color_mode = "grayscale",
batch_size = 32,
class_mode = 'binary')
classifier.fit_generator(training_set,
steps_per_epoch = 40,
epochs = 10,                                                                                   
validation_data = test_set,
validation_steps = 8)

import numpy as np
from keras.preprocessing import image                           
test_image = image.load_img('E:/exercise/predict_2.jpg', target_size = (100, 100))
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis = 0)
result = classifier.predict(test_image)
training_set.class_indices                                   
if result[0][0] >= 0.5: prediction = 'happy'
else: prediction = 'sad'
print(prediction)  

任何人都可以告诉我如何解决这个问题。谢谢大家!

最佳答案

尝试将参数 preprocessing_function=gray_to_rgb 添加到 train_datagentest_datagenImageDataGenerator 中,如下所示:

def rgb_to_gray(rgb):     # Using the luminosity formula: grayscale =  0.21 R + 0.72 G + 0.07 B
    return np.dot(rgb[...,:3], [0.299, 0.587, 0.114])

train_datagen = ImageDataGenerator(rescale = 1./255,
shear_range = 0.2,
zoom_range = 0.2,
horizontal_flip = True,
preprocessing_function=rgb_to_gray)
test_datagen = ImageDataGenerator(rescale = 1./255, preprocessing_function=rgb_to_gray)

关于python - ValueError : Error when checking input: expected conv2d_3_input to have shape (100, 100, 1) 但得到形状为 (100, 100, 3) 的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59696497/

相关文章:

python - 在 __exit__ 中由 __enter__ 返回

python - 删除 pandas 数据框中具有多个关联的条目?

python - 检查数据框组是否包含列表中的值

python - 使用 get() 从字典中提取键

python - Keras LSTM 输入维度设置

python - 如何在 virtualenv 中配置 pip 以将软件包安装到当前目录根目录?

python - 读取为 NoneType 的 txt 行

python - 如何在 Python 中检查代码是在本地运行还是在集群上运行

python-3.x - 预测单个/多个时间步长的多行 lstm

image-processing - 在具有不同基本事实和输出 channel 的多类分割问题中,如何计算损失? (UNET,骰子损失)