I have built and trained my CNN model and I want to test it. I am getting an error when I'm predicting on new data. Any help would be appreciated.
This code uses the model.predict() to give the prediction.
The error is:
ValueError: Input 0 of layer sequential is incompatible with the layer: expected axis -1 of input shape to have value 1 but received input with shape (1, 128, 128, 3)
The code is:
import tensorflow as tf
from tensorflow import keras
import numpy as np
import cv2
import os
model_location =r'new_elephant_detection.h5' l
model=load_model(model_location)
image_location=r''file_list=os.listdir(image_location)
for f in file_list:
f_path=os.path.join(image_location, f)
img=cv2.imread(f_path)
img=cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img=cv2.resize(img, (128,128))
img=img/127.5-1
img=np.expand_dims(img, axis=0)
prediction =model.predict (img, batch_size=1, verbose=0)
pred=np.argmax(prediction)
print ('for file ', f_path, ' the index of the predicted class is ',
pred, ' with a probability of ', prediction[0][pred] )
Here attached the model:
import cv2
import numpy as np
from tensorflow.keras.utils import to_categorical
from sklearn.preprocessing import LabelBinarizer
from sklearn.model_selection import train_test_split
from skimage import io
import matplotlib.pyplot as plt
from pylab import *
img_rows, img_cols = 112, 112
images = []
labels = []
for category in Data_Dir:
folder_path = os.path.join(Dataset, category)
for img in os.listdir(folder_path):
img_path = os.path.join(folder_path, img)
img=cv2.imread(img_path)
try:
grayscale_img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
resized_img=cv2.resize(grayscale_img,(img_rows,img_cols))
images.append(resized_img)
labels.append(category)
plt.subplot(121), imshow(img)
plt.title('RGB format')
plt.imshow(grayscale_img)
plt.title('grayscale format')
plt.show()
except Exception as e:
print('Exception:',e)
images=np.array(images)/255.0
images=np.reshape(images,(images.shape[0],img_rows,img_cols,1))
lb = LabelBinarizer()
labels = lb.fit_transform(labels)
labels = to_categorical(labels)
labels = np.array(labels)
(train_X, test_X, tarin_y, test_y) = train_test_split(images, labels, test_size=0.25,random_state=0)
from keras.models import Sequential
from keras.layers import Dense,Activation,Flatten,Dropout
from keras.layers import Conv2D,MaxPooling2D
num_classes = 2
batch_size = 32
model=Sequential()
model.add(Conv2D(64,(3,3),input_shape=(img_rows,img_cols,1)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Conv2D(128,(3,3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Flatten())
model.add(Dropout(0.5))
model.add(Dense(64,activation='relu'))
model.add(Dense(num_classes,activation='softmax'))
print(model.summary())