keras Cat Dog Classification CNN模型中存在不兼容的输入图层大小错误

5cnsuln7  于 2023-01-21  发布在  其他
关注(0)|答案(1)|浏览(154)

我正在从本地目录train中编写一个简单的CNN模型来分类猫和狗图片。
下面是我到目前为止编写的代码:

import numpy as np
import cv2 as cv
import tensorflow.keras as keras
import os
from sklearn.preprocessing import LabelEncoder
from tensorflow.keras.utils import to_categorical
from tensorflow.keras import layers , models
from sklearn.model_selection import train_test_split

images_vector =[]
images_label =[]

fileNames = os.listdir('train')

for i , f_name in enumerate(fileNames) :

image = cv.imread('train/' + f_name)
    
image = cv.resize(image , (50,50))
image = image/255.0
image = image.flatten()

images_vector.append(image)
images_label.append(f_name.split('.')[0]) 

if i%10000 == 0 : 
    print(f" [INFO ] : {i} images are processed...")

labelEncoder  = LabelEncoder()
images_label = labelEncoder.fit_transform(images_label)

images_label = to_categorical(images_label)
images_label

X_train , X_test , y_train , y_test = 
train_test_split(images_vector ,images_label  , random_state=40 , train_size=0.8)

print('X_train: ' + str(X_train.shape))
print('Y_train: ' + str(y_train.shape))
print('X_test:  '  + str(X_test.shape))
print('Y_test:  '  + str(y_test.shape))

现在运行以下代码构建模型后:

net = models.Sequential([
    layers.Conv2D(32 , (3,3) , activation='relu' , input_shape = (1,7500)) ,
    layers.MaxPooling2D(2,2),
    layers.Conv2D(64 , (3,3) , activation='relu'),
    layers.Flatten(),
    layers.Dense(2 , activation='softmax')
])

net.summary()

我得到这个错误:

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

我搜索了很多来解决这个问题,并尝试和测试不同的形状,但找不到解决方案
有人能帮我吗?

qeeaahzv

qeeaahzv1#

Conv2D图层应该用在最终带有一些颜色通道的二维图像上。要使其工作,请尝试以下操作:
1.要保留2D图像结构,请删除:

image = image.flatten()

1.将第一个Conv2D层的输入形状更改为:

layers.Conv2D(32, ... input_shape = (50,50,3)

相关问题