我训练了一个Keras模型来对两类图像进行分类:
_________________________________________________________________Layer (type) Output Shape Param # =================================================================conv2d_3 (Conv2D) (None, 150, 150, 16) 448 _________________________________________________________________max_pooling2d_3 (MaxPooling2 (None, 75, 75, 16) 0 _________________________________________________________________dropout (Dropout) (None, 75, 75, 16) 0 _________________________________________________________________conv2d_4 (Conv2D) (None, 75, 75, 32) 4640 _________________________________________________________________max_pooling2d_4 (MaxPooling2 (None, 37, 37, 32) 0 _________________________________________________________________conv2d_5 (Conv2D) (None, 37, 37, 64) 18496 _________________________________________________________________max_pooling2d_5 (MaxPooling2 (None, 18, 18, 64) 0 _________________________________________________________________dropout_1 (Dropout) (None, 18, 18, 64) 0 _________________________________________________________________flatten_1 (Flatten) (None, 20736) 0 _________________________________________________________________dense_2 (Dense) (None, 512) 10617344 _________________________________________________________________dense_3 (Dense) (None, 1) 513 =================================================================Total params: 10,641,441Trainable params: 10,641,441Non-trainable params: 0_________________________________________________________________
现在我想输入一个.jpg文件来获取预测结果。我尝试了以下方法:
img_path = pathlib.Path('/content/drive/My Drive/trainingset1/images/pbs/tpb2.jpg')from PIL import Imageimg = Image.open(img_path)array = tf.keras.preprocessing.image.img_to_array(img)testimg=array[:, :, 0]
testimg = (np.expand_dims(testimg,0))print(testimg.shape)
(1, 460, 350)
probability_model = tf.keras.Sequential([model_new, tf.keras.layers.Softmax()])predictions_single = probability_model.predict(testimg)print(predictions_single)
我得到了以下错误:
ValueError: Input 0 of layer sequential_4 is incompatible with the layer: expected ndim=4, found ndim=3. Full shape received: [None, 460, 350]
我不确定在处理图像时哪里出错了。我是否以错误的方式输入了模型?
更新:
现在我可以无错误地使用模型,但无论我输入什么图像,它总是打印:
[[1.]]
由于我训练了两个类别,它不应该生成两个值吗?
更新2:
这是我的模型代码:
model_new = Sequential([ Conv2D(16, 3, padding='same', activation='relu', input_shape=(150, 150, 3)), MaxPooling2D(), Dropout(0.2), Conv2D(32, 3, padding='same', activation='relu'), MaxPooling2D(), Conv2D(64, 3, padding='same', activation='relu'), MaxPooling2D(), Dropout(0.2), Flatten(), Dense(512, activation='relu'), Dense(1)])
model_new.compile(optimizer='adam', loss=tf.keras.losses.BinaryCrossentropy(from_logits=True), metrics=['accuracy'])
回答:
删除这一行 testimg=array[:, :, 0]
。
你的输入缺少通道。
Conv2D期望输入的形状为 (batch, height, width, channel)
另外,你可能需要根据模型输入形状调整图像大小。
img = Image.open(img_path).resize((h, w))
更新:
你的模型有很多不一致之处。
-
dense_3 (Dense) (None, 1) 513
– 你的最后一层表明这是一个二分类问题。在模型中使用sigmoid激活函数,而不是softmax。 -
发布你的完整模型代码。