检查输入时出错:预期conv2d\u 3\u input具有形状(64,64,3),但获得了具有形状(64,64,1)的数组

2024-04-19 15:24:24 发布

您现在位置:Python中文网/ 问答频道 /正文

基本上,我是按照udemy的机器学习A-Z教程学习的,在那里我学会了训练自己的卷积神经网络模型,但是没有教我如何使用训练过的模型-如何输入和输出。我在youtube上查看了一些教程,通过Keras的cnn传递了一张图片,并附带了this教程。当我运行代码时,我得到了一个错误

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

现在我完全不知道如何处理这个问题。如果有人能告诉我在我训练了人际网络之后该怎么做,以及如何解决这个问题,我会非常感激我尝试过改变img_array = cv2.imread(filepath, cv2.IMREAD_GRAYSCALE) 但我觉得这跟这没关系

我用来训练卷积网络的代码:

import keras
from keras.models import Sequential
from keras.layers import Convolution2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense

初始化cnnclassifier = Sequential()

步骤1-应用卷积

classifier.add(Convolution2D(32,3,3, border_mode = 'same', input_shape=(64,64,3), activation = 'relu'))

应用最大池

classifier.add(MaxPooling2D(pool_size=(2,2)))

添加另一个卷积层以提高精度

classifier.add(Convolution2D(32,3,3, border_mode = 'same', activation = 'relu'))
classifier.add(MaxPooling2D(pool_size=(2,2)))

应用展平

classifier.add(Flatten())

步骤4-完全连接

classifier.add(Dense(output_dim = 128, activation = 'relu'))
#input
classifier.add(Dense(output_dim = 1, activation = 'sigmoid'))
#output

全部编译

classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
#fitting the cnn to the images
from keras.preprocessing.image import ImageDataGenerator
#pixels take values between 0 & 255
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('dataset/training_set', target_size=(64, 64), batch_size=32, class_mode='binary')       
test_set = test_datagen.flow_from_directory('dataset/test_set',
                                         target_size=(64, 64),
                                         batch_size=32,
                                         class_mode='binary')

classifier.fit_generator(training_set,
                     samples_per_epoch = 8000,
                     nb_epoch = 25,
                     verbose = 1,
                     validation_data = test_set,
                     nb_val_samples = 2000)

classifier.save('my_model.h5')

我在一个新文件中使用的代码来尝试我的训练网络
import cv2
import tensorflow as tf
import keras
from keras.models import Sequential

Categories = ["Dogs","cats"]

def prepare(filepath):
    img_size = 64
    img_array = cv2.imread(filepath, cv2.IMREAD_GRAYSCALE)
    new_array = cv2.resize(img_array, (img_size,img_size))
    return new_array.reshape(-1,img_size,img_size, 1)
    classifier = keras.models.load_model('my_model.h5')

prediction = classifier.predict([prepare('/Users/m.zain/Documents/machine learning-2019 dps/Machine Learning A-Z Template Folder/Part 8 - Deep Learning/Section 40 - Convolutional Neural Networks (CNN)/dog.jpg')])
print(prediction)

prediction = classifier.predict([prepare('/Users/m.zain/Documents/machine learning-2019 dps/Machine Learning A-Z Template Folder/Part 8 - Deep Learning/Section 40 - Convolutional Neural Networks (CNN)/dog.jpg')])
 print(Categories[int(prediction[0][0])])

prediction = classifier.predict([prepare('/Users/m.zain/Documents/machine learning-2019 dps/Machine Learning A-Z Template Folder/Part 8 - Deep Learning/Section 40 - Convolutional Neural Networks (CNN)/cat.jpg')])
 print(Categories[int(prediction[0][0])])

我希望在执行代码时得到“dog”作为输出:

prediction = classifier.predict([prepare('/Users/m.zain/Documents/machine learning-2019 dps/Machine Learning A-Z Template Folder/Part 8 - Deep Learning/Section 40 - Convolutional Neural Networks (CNN)/dog.jpg')])
print(Categories[int(prediction[0][0])])

当我运行这个时,cat作为一个输出:

prediction = classifier.predict([prepare('/Users/m.zain/Documents/machine learning-2019 dps/Machine Learning A-Z Template Folder/Part 8 - Deep Learning/Section 40 - Convolutional Neural Networks (CNN)/cat.jpg')])
print(Categories[int(prediction[0][0])])

Tags: fromtestimportaddimgsizepreparearray