案例:鸢尾花数据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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值