我已经训练了一个简单的CNN用于二进制图像分类。然后我尝试进行预测。我使用ImageDataGenerator创建了一个预测迭代器(predict_it)。然后我使用
probabilities = model.predict(predict_it)
得到了如下结果:
print(probabilities)
[[9.0815449e-01]
[1.9250402e-02]
[9.8504424e-01]
...
[4.3504283e-06]
[3.5914429e-06]
[7.5442227e-07]]
因此,模型本身似乎工作正常。然而,这种预测方法处理的是一个充满图像的整个子目录。因此,我尝试处理一个图像。但当我执行下面的代码时,总是得到相同的值(对8个不同的图像执行多次):
probabilitiy = model.predict(single_image)
结果:
1/1 [==============================] - 0s 82ms/step
probability: [[0.5078959]]
1/1 [==============================] - 0s 33ms/step
probability: [[0.5078958]]
1/1 [==============================] - 0s 32ms/step
probability: [[0.5078958]]
1/1 [==============================] - 0s 42ms/step
probability: [[0.5078958]]
1/1 [==============================] - 0s 45ms/step
probability: [[0.50789577]]
1/1 [==============================] - 0s 39ms/step
probability: [[0.5078958]]
1/1 [==============================] - 0s 32ms/step
probability: [[0.5078957]]
1/1 [==============================] - 0s 33ms/step
probability: [[0.5078958]]
有人知道这是怎么发生的吗?
先谢谢你。
我尝试以不同的形式保存模型:(.keras和.h5)-但这并没有改变上面提到的结果。
我用来预处理单个图像的代码:
# a function to load and prepare each image
def load_image(filename):
# load the image
img = load_img(filename, grayscale=False, target_size=(256, 256))
# convert to array
img = img_to_array(img)
# reshape into a single sample with 1 channel
img = img.reshape(1, 256, 256, 3)
# prepare pixel data
img = img.astype("float32")
img = img / 255.0
return img
# run through all files in a specified folder
for filename in files:
# load a single image
img = load_image(filename)
# predict the probability
probability = model.predict(img)
# display the result
print(f"probability: {probability}")
1条答案
按热度按时间omqzjyyz1#
实际上,我在Keras文档中找到了有关重新缩放层的解决方案:“在训练和推理过程中都应用重标度.”
因为我的模型有一个缩放层,所以我必须将一个尚未缩放的图像传递给模型(在进行单幅图像预测时),否则缩放将被应用两次!
因此,用于预处理单个图像以进行预测的正确代码是: