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

Python机器学习数据集类名存储位置及自定义数据集类名处理

关于sklearn中iris数据集类名存储与自定义数据集处理的解惑

嘿,我来帮你把这个问题理清楚~

一、iris数据集的类名存储位置与模型逻辑

首先,sklearn通过load_iris()加载的数据集是一个Bunch对象——这是sklearn自定义的一种类似字典的结构,它把数据集的所有相关信息都打包成了这个对象的属性。

  • 类名target_names就是这个Bunch对象的直接属性,和data(特征数据)、target(数值化的类别标签)是平级的。你可以通过dir(iris)查看这个对象的所有属性,就能看到target_names在里面。
  • 模型调用的逻辑是这样的:sklearn的所有分类模型(比如LogisticRegression、RandomForestClassifier)只接受数值型的目标变量,也就是iris.target里的0、1、2。target_names的作用只是做“数值→类别名称”的映射,方便你把模型输出的数值结果转换成人类能看懂的字符串,模型训练过程中根本不会用到它。

举个简单的例子,当你训练完模型得到预测结果后,可以这样把数值转成类名:

from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier

iris = load_iris()
model = RandomForestClassifier()
model.fit(iris.data, iris.target)
prediction = model.predict([[5.1, 3.5, 1.4, 0.2]])
# 把预测的数值转成类名
print(iris.target_names[prediction[0]])  # 输出 'setosa'

二、自定义宝可梦数据集的处理方式

针对你说的含ice、fire、water、flying四类的宝可梦数据集,处理方式如下:

1. 类名的存储位置

你可以自己维护一个类名列表或者字典,只要保证它和你数值化后的标签一一对应就行。比如:

  • 直接存一个列表:pokemon_class_names = ['ice', 'fire', 'water', 'flying']
  • 或者用字典做双向映射:label_to_name = {0:'ice', 1:'fire', 2:'water', 3:'flying'},name_to_label = {v:k for k,v in label_to_name.items()}

2. 必须将类名转为数值形式

是的,sklearn的监督学习模型不接受字符串类型的目标变量,必须把类别名称转换成0、1、2、3这类整数。这里有两种常用方法:

方法一:手动映射(灵活可控)

如果你想自己指定每个类别对应的数值(比如让0对应ice,1对应fire),可以用字典手动转换:

# 假设你的原始类别是字符串列表,比如每个样本的类别存在pokemon_labels里
pokemon_labels = ['fire', 'ice', 'water', 'flying', ...]  # 你的样本类别列表
name_to_label = {'ice':0, 'fire':1, 'water':2, 'flying':3}
pokemon_target = [name_to_label[label] for label in pokemon_labels]
# 此时pokemon_target就是数值化的标签数组,形状和iris.target一样是(n_samples,)

方法二:用LabelEncoder自动转换

sklearn提供了LabelEncoder工具可以自动完成字符串到数值的转换,它会按照类别名称的字典序来分配数值:

from sklearn.preprocessing import LabelEncoder

pokemon_labels = ['fire', 'ice', 'water', 'flying', ...]
le = LabelEncoder()
pokemon_target = le.fit_transform(pokemon_labels)
# 查看对应的类名,le.classes_就相当于iris.target_names
print(le.classes_)  # 输出 ['fire', 'ice', 'flying', 'water'](按字典序排序)
# 如果要把预测的数值转回类名,可以用le.inverse_transform()
predicted_num = 0
print(le.inverse_transform([predicted_num]))  # 输出 ['fire']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:58:07