【发布时间】:2020-06-16 00:45:17
【问题描述】:
我试图在 Keras 中重新创建 this Flower Recognition CNN。该模型似乎有效,至少在笔记本中(同时获得验证集的预测),但我需要在其他地方使用该模型。照片是 150x150,这就是我构建 CNN 的方式:
model = Sequential()
model.add(Conv2D(filters=32, kernel_size=(5,5), padding='Same', activation='relu', input_shape=(150, 150, 3)))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Conv2D(filters=64, kernel_size=(3,3), padding='Same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2)))
model.add(Conv2D(filters=96, kernel_size=(3,3), padding='Same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2)))
model.add(Conv2D(filters=96, kernel_size=(3,3), padding='Same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2)))
model.add(Flatten())
model.add(Dense(512))
model.add(Activation('relu'))
model.add(Dense(5, activation="softmax"))
不过,当我尝试使用加载的示例照片和模型在本地预测结果时:
model = model_from_json(open("model.json", "r").read())
model.load_weights('model.h5')
img = cv2.imread('/path/to/the/dir/testimage.jpg')
img = cv2.resize(img, (150, 150))
data = np.array(img)
model.summary()
result = model.predict(data)
我收到此错误:
ValueError: Input 0 of layer sequential_1 is incompatible with the layer: expected ndim=4, found ndim=3. Full shape received: [None, 150, 3]
模型汇总的输出为:
Model: "sequential_1"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
conv2d_1 (Conv2D) (None, 150, 150, 32) 2432
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 75, 75, 32) 0
_________________________________________________________________
conv2d_2 (Conv2D) (None, 75, 75, 64) 18496
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 37, 37, 64) 0
_________________________________________________________________
conv2d_3 (Conv2D) (None, 37, 37, 96) 55392
_________________________________________________________________
max_pooling2d_3 (MaxPooling2 (None, 18, 18, 96) 0
_________________________________________________________________
conv2d_4 (Conv2D) (None, 18, 18, 96) 83040
_________________________________________________________________
max_pooling2d_4 (MaxPooling2 (None, 9, 9, 96) 0
_________________________________________________________________
flatten_1 (Flatten) (None, 7776) 0
_________________________________________________________________
dense_1 (Dense) (None, 512) 3981824
_________________________________________________________________
activation_1 (Activation) (None, 512) 0
_________________________________________________________________
dense_2 (Dense) (None, 5) 2565
=================================================================
Total params: 4,143,749
Trainable params: 4,143,749
Non-trainable params: 0
我不明白为什么它会有不同的形状。我已经读过 Reshape 可能会做这件事,但我正在使用 fit_generator 来适应训练集,我不确定这是否可行。
【问题讨论】:
标签: python tensorflow keras