You need to enable JavaScript to run this app. Python Keras中如何正确预测类别并匹配输出对应标签
优惠活动
大模型
产品
解决方案
定价
更多

Python Keras中如何正确预测类别并匹配输出对应标签

项目基础背景
  • 模型架构:基于Keras搭建Sequential结构的LeNet网络
  • 训练数据:PlantVillage数据集
  • 任务目标:识别植物类型与对应病害
  • 训练效果:模型验证准确率val_acc达80%
当前遇到的问题
  • 两类模型预测接口的适用场景不清晰:
    • 调用model.predict(x)会返回由长小数组成的概率数组
    • 调用model.predict_classes(x)会返回类似[30]、[7]的列表包裹单数字结果
  • 输出的数字结果无法正确映射为对应的类别标签,自行匹配对应关系时出现大量逻辑矛盾
  • 无法定位预测不准的根本原因:不确定是数据预处理流程的问题,还是预测环节的标签映射逻辑存在偏差
  • 希望获得现有图像预处理流程的可落地优化建议
推理环节当前实现代码
import numpy as np
import tensorflow as tf
from tensorflow import keras
from keras.models import load_model, Sequential
from PIL import Image
import matplotlib.pyplot as plt
import cv2
import os

#  width is [0]
# height it [1]
x = 0
def prep_pic(img_path):
    img = Image.open(img_path)
    old_width  = img.size[0] 
    old_height = img.size[1]
    
    square_width = 150
    square_height = 150
    
    if old_height > old_width:
        square_width = old_width
        square_height = old_width
    
    if old_height <= old_width:
        square_width = old_height
        square_height = old_height
    
    left = (old_width - square_width)/2
    top = (old_height - square_height)/2
    right = (old_width + square_width)/2
    bottom = (old_height + square_height)/2

    img2 = img.crop((left, top, right, bottom))
    img2.resize = (-1, 150, 150, 3)
    img2.save("pic.png")
    
    img3 = plt.imread("pic.png")
    #os.remove("pic.png")
    img3 = cv2.resize(img3, (150, 150))
    print(img3.shape)
    return img3.reshape(-1, 150, 150, 3)  # 返回TensorFlow要求的输入格式
    
prep_pic('../input/project-plantus/applescab.jpg')
model = Sequential()
model = load_model('../input/project-plantus/plantus_model.h5')
print(model.predict_classes([prep_pic('../input/project-plantus/applescab.jpg')]))

注:作者自评当前推理预处理逻辑偏粗糙,暂能实现基本功能,欢迎提出优化方向

训练环节当前预处理实现代码
def train_data_gen(DIR, ID):
    for img in os.listdir(DIR)[:1000]:
        try:
            path = DIR + '/' + img
            img = plt.imread(path)
            img = cv2.resize(img, (150, 150))
            if img.shape == (150, 150, 3):
                x.append(img)
                y.append(ID)
        except:
            None

内容的提问来源于stack exchange,提问作者9_0_4

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.22 02:24:07