Reputation: 2701
I have a problem about solving dimension in prediction method of CNN. Before defining train and test data based on image , I posed a CNN model. After the process has been done, I fitted the model. When I predict the value by using model, It throws an error here.
How can I fix it ?
Here are my code blocks shown below.
My Keras Libraries
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
from keras.preprocessing.image import ImageDataGenerator
Here is my CNN Model
classifier = Sequential()
classifier.add(Convolution2D(filters = 32,
kernel_size=(3,3),
data_format= "channels_last",
input_shape=(64, 64, 3),
activation="relu")
)
classifier.add(MaxPooling2D(pool_size = (2,2)))
classifier.add(Convolution2D(32, (3, 3), activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2, 2)))
classifier.add(Convolution2D(32, (3, 3), activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2, 2)))
classifier.add(Flatten())
classifier.add(Dense(units = 128, activation = 'relu'))
classifier.add(Dense(units = 1, activation = 'sigmoid'))
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
Fitting CNN to Images
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(train_path,
target_size=(64, 64),
batch_size=32,
class_mode='binary')
test_set = test_datagen.flow_from_directory(
test_path,
target_size=(64, 64),
batch_size=32,
class_mode='binary')
Fit Model
classifier.fit_generator(
training_set,
steps_per_epoch=50,
epochs=30,
validation_data=test_set,
validation_steps=200)
Prediction
S = 64
directory = os.listdir(test_forged_path)
print(directory[3])
print("Path : ", test_forged_path + "/" + directory[3])
imgForged = cv2.imread(test_forged_path + "/" + directory[3])
plt.imshow(imgForged)
pred = classifier.predict(imgForged) # ERROR
print("Probability of Forged Signature : ", "%.2f".format(pred))
The Error :
ValueError: Error when checking input: expected conv2d_19_input to have 4 dimensions, but got array with shape (270, 660, 3)
Upvotes: 1
Views: 78
Reputation: 745
The predict
method is missing the batch dimension from your input. Modify your prediction like so:
import numpy as np <--- import numpy
S = 64
directory = os.listdir(test_forged_path)
print(directory[3])
print("Path : ", test_forged_path + "/" + directory[3])
imgForged = cv2.imread(test_forged_path + "/" + directory[3])
plt.imshow(imgForged)
pred = classifier.predict(np.expand_dims(imgForged,0)) # <-- add new axis to the front, shape will be (1, 270, 660, 3)
print("Probability of Forged Signature : ", "%.2f".format(pred))
Upvotes: 2