即使有很好的分类报告,模型也无法正确预测

问题描述 投票:0回答:1

我尝试从链接运行此模型:
https://www.kaggle.com/code/alexfordna/garbage-classification-mobilenetv2-92-accuracy/notebook

当我在 colab 上使用类似的数据集(但更小,2100 个图像到 6 个类)时,效果很好。但是当我添加此代码来预测输入图像时:

from google.colab import files
from PIL import Image


def process_uploaded_image(image_path, target_size=(224, 224)):
    img = Image.open(image_path)
    img = img.resize(target_size)  
    img_array = np.array(img) 

    if img_array.shape[-1] == 4:  
        img_array = img_array[..., :3]

    img_array = img_array / 255.0 
    img_array = np.expand_dims(img_array, axis=0)  
    img_array = mobilenetv2.preprocess_input(img_array) 

    return img_array

uploaded = files.upload()

for fn in uploaded.keys():  
    processed_image = process_uploaded_image(fn, target_size=IMAGE_SIZE)    
    preds = model.predict(processed_image)
    pred_class = np.argmax(preds, axis=1)
  
    plt.imshow(Image.open(fn))  # Display the uploaded image
    plt.title(f'Predicted class: {categories[pred_class[0]]}')
    plt.axis('off')
    plt.show()
    print(f'File {fn} is predicted as: {categories[pred_class[0]]}')

结果是错误的预测。例如,模型总是将我的输入预测为“垃圾”类。当我停止运行时它会更改为另一个类,但它仍然是错误的预测。
我还添加了此代码来检查预测概率:

preds = model.predict(processed_image)
pred_probs = preds[0]  # Get the prediction probabilities for the first (and only) batch
print("Prediction probabilities:", pred_probs)
pred_class = np.argmax(pred_probs)
print("Predicted class:", categories[pred_class])

输出:

**1/1** ━━━━━━━━━━━━━━━━━━━━ **0s** 24ms/step Prediction probabilities: \[0.31027108 0.12315894 0.47848797 0.00863316 0.07789086 0.00155797\]   
Predicted class: metal  

为什么会发生这种情况?我的模型如何正确预测结果?

tensorflow machine-learning deep-learning conv-neural-network google-colaboratory
1个回答
0
投票

有时会起作用,但大多数情况下不起作用

© www.soinside.com 2019 - 2024. All rights reserved.