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

我的Sequential图像分类模型准确率卡在0.2155,请问是什么原因?

图像分类器训练准确率停滞问题求助

我是机器学习领域新手,知识储备不足请多包涵。我正在使用Sequential模型搭建图像分类器,用于识别10类物品,已为每个类别准备了数据集,每张图片尺寸为(200,200),总图片数量约1200张。
目前遇到的问题是,模型训练时准确率始终卡在0.2155,完全不清楚哪里出了问题,希望大家可以帮助我指出错误所在,以下是完整代码:

import numpy as np
import keras
import matplotlib.pyplot as plt
import random
import os
import cv2

X_train=[]
y_train=[]
size= 200

#preprocessing 
imagedir= "preprocessed"
pathdir= os.path.join("Images",imagedir)
for image_name in os.listdir("preprocessed/"):

    image_path= os.path.join("preprocessed",image_name)
    image= cv2.imread(image_path)
    X_train.append(image)
    if image_name.startswith("pen"):
        y_train.append(0)
    elif image_name.startswith("spoon"):
        y_train.append(1)
    elif image_name.startswith("ceiling_fan"):
        y_train.append(2)
    elif image_name.startswith("clock"):
        y_train.append(3)
    elif image_name.startswith("paper_airplane"):
        y_train.append(4)
    elif image_name.startswith("tomato"):
        y_train.append(5)
    elif image_name.startswith("banana"):
        y_train.append(6)
    elif image_name.startswith("leaf"):
        y_train.append(7)
    elif image_name.startswith("coin"):
        y_train.append(8)
    elif image_name.startswith("phone"):
        y_train.append(9)

    
X_train= np.array(X_train)
y_train= np.array(y_train)

X_train= X_train/255

test_size= 30
X_train= X_train[0:-test_size]
y_train= y_train[0:-test_size]
X_test= X_train[-test_size:-1]
y_test= y_train[-test_size:-1]

print(X_train.shape, X_test.shape)
print(y_train.shape, y_test.shape)

X_train_array= X_train.reshape(len(X_train), (size**2)*3)
X_test_array= X_test.reshape(len(X_test), (size**2)*3)

print(X_train_array.shape)

model = keras.Sequential([keras.layers.Dense(10, input_shape=((size**2)*3,), activation='sigmoid')])

model.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['accuracy'])

model.fit(X_train_array, y_train, epochs=100)

y_predict_test=model.predict(X_test_array)
y_predict_test_labels=[]
for i in y_predict_test:
    y_predict_test_labels.append(np.argmax(i))

model.save("Model.h5")

问题修正点

  • 数据集划分错误:代码先将总数据去掉最后30张赋值给X_train,再从修改后的X_train中截取末尾数据作为测试集,导致测试集属于训练集的一部分,同时总数据的最后30张被直接丢弃,完全没有参与训练或测试。正确做法是加载完全部数据后,用train_test_split工具打乱数据后再划分训练集和测试集。
  • 输出层激活函数错误:10分类任务的输出层应使用softmax激活函数,保证所有类别的输出概率和为1,sigmoid仅适用于二分类或多标签分类任务,和你使用的sparse_categorical_crossentropy损失函数不匹配。
  • 模型结构不合理:200*200的彩色图像直接拉平为12万维的向量,仅接一层10神经元的全连接层,没有任何特征提取能力,自然无法学习到图像的有效特征。图像分类任务应使用卷积神经网络结构,加入Conv2D、MaxPooling2D等层提取图像特征后再接入全连接层分类。
  • 数据集未打乱:按文件夹遍历顺序加载样本,若同类样本连续排列,会导致训练集和测试集的类别分布不均匀,影响模型学习效果,加载数据后需要先打乱样本顺序再划分数据集。
  • 小问题:cv2.imread读取的图像为BGR通道顺序,和常规的RGB顺序不同,可增加转换代码统一通道顺序。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 13:15:04