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

使用Sklearn示例代码读取图片数字时遇AttributeError报错求助

问题原因

你用plt.imread()读取的是单张本地图片,返回的是numpy数组,而不是sklearn自带digits数据集那种包含.images和.target属性的Bunch对象,所以触发了AttributeError。

解决方案

根据你的需求分两种场景处理:

场景1:用sklearn自带数据集训练模型,再识别自己的单张数字图片

需要先训练模型,再把自定义图片转换成模型要求的格式:

import matplotlib.pyplot as plt
from sklearn import datasets, svm, metrics
from sklearn.model_selection import train_test_split
import numpy as np

# 1. 加载sklearn自带的digits数据集并训练模型
digits = datasets.load_digits()
# 将图片展平为一维数组,适配模型输入
X_train, X_test, y_train, y_test = train_test_split(
    digits.images.reshape((len(digits.images), -1)), 
    digits.target, 
    test_size=0.5, 
    shuffle=False
)
# 训练SVM分类器
clf = svm.SVC(gamma=0.001)
clf.fit(X_train, y_train)

# 2. 处理自定义图片
custom_image = plt.imread('/Users/aarik/Downloads/number.png')
# 彩色图转灰度图
if custom_image.ndim == 3:
    custom_image = np.mean(custom_image, axis=2)
# 调整为digits数据集的8x8尺寸
custom_image = plt.imresize(custom_image, (8, 8))
# 反转颜色(匹配digits白底黑字的格式)
custom_image = 1 - custom_image
# 归一化到0-16的像素范围(和数据集一致)
custom_image = (custom_image * 16).astype(int)

# 3. 预测并输出结果
predicted = clf.predict(custom_image.reshape(1, -1))
print(f"识别结果:{predicted[0]}")

# 展示处理后的图片
plt.imshow(custom_image, cmap=plt.cm.gray_r, interpolation="nearest")
plt.title(f"Predicted: {predicted[0]}")
plt.axis('off')
plt.show()

场景2:仅展示自己的单张图片(无需训练模型)

如果只是想显示图片,直接操作numpy数组即可,不需要.images和.target属性:

import matplotlib.pyplot as plt

custom_image = plt.imread('/Users/aarik/Downloads/number.png')

plt.imshow(custom_image, cmap=plt.cm.gray_r, interpolation="nearest")
plt.axis('off')
# 手动设置图片标题(替换X为实际数字)
plt.title("Custom Image: X")
plt.show()
关键提示
  • datasets.load_digits()返回的是封装好的Bunch对象,自带.images和.target属性;而plt.imread()仅返回单张图片的像素数组,没有这些附加属性。
  • 用模型识别自定义图片时,必须保证图片的尺寸、灰度模式、像素值范围和训练数据集一致,否则预测结果会失真。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 02:55:16