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

你可能感兴趣的:(机器学习,支持向量机,分类,机器学习)