在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)
答案 0 :(得分:2)
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))