You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Teachable Machine模型网页准确率100%,Python部署后准确率骤降排查

问题分析与解决方案

准确率骤降的核心原因

  1. 预处理流程不匹配:Teachable Machine网页端的图像预处理逻辑是「保持比例缩放到短边224像素 → 中心裁剪至224×224」,而你当前代码是直接强制缩放图像到目标尺寸,会导致图像拉伸变形,模型训练时学习的特征位置偏移,自然识别错误。
  2. 色彩空间不一致:OpenCV的cv2.imread()默认读取BGR色彩格式,但Teachable Machine训练时用的是RGB格式,通道顺序完全相反,这会让模型接收到的色彩特征完全错误,是准确率暴跌的关键因素之一。
  3. 路径潜在问题:代码中image_path = "\testing\"存在转义问题,Windows系统下应改为"testing/"或"\\testing\\",否则可能无法正确读取图像文件。

实现Teachable Machine风格的图像预处理

要完全对齐网页端的处理逻辑,需按以下步骤处理图像:

  1. 将图像转为RGB格式
  2. 保持原图像比例,将短边缩放到224像素
  3. 对长边进行中心裁剪,得到224×224的正方形图像
  4. 执行与训练一致的归一化操作:(像素值 / 127.5) - 1

修改后的Python代码

from keras.models import load_model
import numpy as np
import os
from PIL import Image

np.set_printoptions(suppress=True)
model = load_model("350EpochCarInteriorModel.h5", compile=False)
class_names = open("labels.txt", "r").readlines()
# 修正路径格式,避免转义问题
image_path = "testing/"

def preprocess_image(image_path):
    # 用PIL读取图像,默认是RGB格式
    img = Image.open(image_path).convert("RGB")
    width, height = img.size
    
    # 保持比例缩放短边到224
    if width < height:
        new_width = 224
        new_height = int((height / width) * 224)
    else:
        new_height = 224
        new_width = int((width / height) * 224)
    img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
    
    # 中心裁剪到224×224
    left = (new_width - 224) // 2
    top = (new_height - 224) // 2
    right = left + 224
    bottom = top + 224
    img = img.crop((left, top, right, bottom))
    
    # 转为数组并归一化
    img_array = np.asarray(img, dtype=np.float32).reshape(1, 224, 224, 3)
    img_array = (img_array / 127.5) - 1
    return img_array

for image_name in os.listdir(image_path):
    full_path = os.path.join(image_path, image_name)
    # 跳过非图像文件
    if not full_path.lower().endswith(('.png', '.jpg', '.jpeg')):
        continue
    processed_img = preprocess_image(full_path)
    prediction = model.predict(processed_img)
    index = np.argmax(prediction)
    class_name = class_names[index][2:].strip()  # 去除换行符
    confidence_score = prediction[0][index]
    car_brand, car_model = class_name.split("^")
    print(f"Car: {class_name}, Confidence: {confidence_score:.4f}, Name: {car_brand} {car_model}")

额外验证建议

  • 取一张网页端测试通过的图片,用修改后的代码处理后,输出预处理后的图像,对比网页端预览的裁剪结果,确认两者一致。
  • 检查labels.txt的格式是否与模型输出对应,确保索引没有错位。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 20:32:35