I'm writing a simple CNN model to Classification Cat and Dog picture from a local directory named train
.
Below are the codes that I have written so far:
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 i000 == 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))
Now after running following code to build model :
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()
I got this error :
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)
I searched a lot to solving the problem and try and test different shapes but can not find the solution
can any body help me?
CodePudding user response:
The Conv2D layer should be used on a 2-dimensional image with eventually some color channels. To make it work please try the following:
To keep 2d image structure, remove:
image = image.flatten()
Change input shape for the first Conv2D layer to:
layers.Conv2D(32, ... input_shape = (50,50,3)