我在CNN的预测方法中遇到了一个关于求解维度的问题。在根据图像定义训练和测试数据之前,我提出了一个CNN模型。流程完成后,我安装了模型。当我使用模型预测值时,它在这里抛出了一个错误。
我该怎么修?
下面是我的代码块。
我的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
from keras.preprocessing.image import ImageDataGenerator
这是我的CNN模型
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'])
将CNN与图像拟合
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')
拟合模型
classifier.fit_generator(
training_set,
steps_per_epoch=50,
epochs=30,
validation_data=test_set,
validation_steps=200)
预测
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))
错误:
ValueError: Error when checking input: expected conv2d_19_input to have 4 dimensions, but got array with shape (270, 660, 3)
predict
方法在您的输入中缺少批次维度。这样修改你的预测:
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))