栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

案例:鸢尾花数据SVM分类——数据文本标签数据编码

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

案例:鸢尾花数据SVM分类——数据文本标签数据编码

实现:对文本数据的类别标签编码并根据预测的数组返回文本类别
//鸢尾花数据文件:
...
5.3,3.7,1.5,0.2,Iris-setosa
5.0,3.3,1.4,0.2,Iris-setosa
...
7.0,3.2,4.7,1.4,Iris-versicolor
6.4,3.2,4.5,1.5,Iris-versicolor
...
6.5,3.0,5.2,2.0,Iris-virginica
6.2,3.4,5.4,2.3,Iris-virginica
5.9,3.0,5.1,1.8,Iris-virginica

//下面把文本数据进行编码,比如a b c编码为 0 1 2; 
// 下面把文本数据进行编码,比如a b c编码为 0 1 2; 
path = './datas/iris.data'  # 数据文件路径
data = pd.read_csv(path, header=None)
x, y = data[list(range(4))], data[4]
查看类别有哪些
pd.unique(y)
array(['Iris-setosa', 'Iris-versicolor', 'Iris-virginica'], dtype=object)
请使用pandas.unique(),它比numpy.unique()方法快得多, 并且还包含空值。 解释:

np.unique() is treating the data as an array, so it goes through every value individually then identifies the unique fields.
whereas, pandas has pre-built metadata which contains this information and pd.unique() is simply calling on the metadata which contains ‘unique’ info, so it doesn’t have to calculate it again.

编码
// 创建编码对象,并设置编码顺序 0,1,2...对应的实际类别['Iris-setosa', 'Iris-versicolor', 'Iris-virginica']
y_category = pd.Categorical(y,ordered=True,categories=['Iris-setosa', 'Iris-versicolor', 'Iris-virginica'])

// 编码
y = y_category.codes

经过sklearn.svm.SVC训练后,预测训练集结果:

y_hat = clf.predict(x_train)
array([2, 1, 0, 1, 2, 1, 0, 1, 1, 1, 2, 0, 2, 0, 0, 1, 2, 2, 1, 2, 1, 2,
       2, 1, 2, 2, 1, 2, 2, 2, 1, 0, 1, 1, 1, 1, 1, 2, 0, 0, 2, 1, 0, 0,
       2, 0, 1, 1, 0, 1, 2, 1, 0, 2, 2, 2, 2, 0, 0, 2, 2, 0, 2, 0, 1, 2,
       0, 0, 2, 0, 0, 0, 1, 2, 2, 0, 0, 0, 1, 2, 0, 0, 2, 0, 2, 1, 2, 2,
       0, 1, 0, 2, 0, 0, 2, 0, 2, 1, 1, 1, 2, 2, 2, 2, 0, 1, 2, 1, 0, 2,
       1, 1, 2, 0, 0, 0, 2, 1, 2, 0], dtype=int8)
如何根据 y_hat 获取对应的原文本类别数据呢? 方法1: 使用编码对象的属性categories,利用y_hat索引
y_category.categories[y_hat]
Index(['Iris-virginica', 'Iris-versicolor', 'Iris-setosa', 'Iris-versicolor',
       'Iris-virginica', 'Iris-versicolor', 'Iris-setosa', 'Iris-versicolor',
       'Iris-versicolor', 'Iris-versicolor',
       ...
       'Iris-versicolor', 'Iris-versicolor', 'Iris-virginica', 'Iris-setosa',
       'Iris-setosa', 'Iris-setosa', 'Iris-virginica', 'Iris-versicolor',
       'Iris-virginica', 'Iris-setosa'],
      dtype='object', length=120)

返回的类型:pandas.core.indexes.base.Index

方法2: 使用pd.Categorical Method —— .from_codes(codes,categories=)
pd.Categorical.from_codes(clf.predict(x_train),['Iris-setosa', 'Iris-versicolor', 'Iris-virginica'])

返回的类型:pandas.core.arrays.categorical.Categorical

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1019388.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号