//鸢尾花数据文件:
...
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)
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_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
pd.Categorical.from_codes(clf.predict(x_train),['Iris-setosa', 'Iris-versicolor', 'Iris-virginica'])
返回的类型:pandas.core.arrays.categorical.Categorical