我必须为分类数据分配标签。让我们考虑 iris 示例:
import pandas as pd
import numpy as np
from sklearn.datasets import load_iris
iris = load_iris()
print "targets: ", np.unique(iris.target)
print "targets: ", iris.target.shape
print "target_names: ", np.unique(iris.target_names)
print "target_names: ", iris.target_names.shape
它将被打印:
目标:[0 1 2] 目标:(150L,) target_names: ['setosa' 'versicolor' 'virginica'] target_names: (3L,)
为了生成所需的标签,我使用 pandas.Categorical.from_codes:
print pd.Categorical.from_codes(iris.target, iris.target_names)
[setosa, setosa, setosa, setosa, setosa, ..., virginica, virginica, virginica, virginica, virginica] 长度:150 类别(3,对象):[setosa, versicolor, virginica]
让我们尝试一个不同的例子:
# I define new targets
target = np.array([123,123,54,123,123,54,2,54,2])
target = np.array([1,1,3,1,1,3,2,3,2])
target_names = np.array(['paglia','gioele','papa'])
#---
print "targets: ", np.unique(target)
print "targets: ", target.shape
print "target_names: ", np.unique(target_names)
print "target_names: ", target_names.shape
如果我再次尝试转换标签中的分类值:
print pd.Categorical.from_codes(target, target_names)
我收到错误消息:
C:\Users\ianni\Anaconda2\lib\site-packages\pandas\core\categorical.pyc in from_codes(cls, codes, categories, ordered) 459 460 if len(codes) and (codes.max() >= len (categories) or codes.min() < -1): --> 461 raise ValueError("codes need to be between -1 and " 462 "len(categories)-1") 463
ValueError:代码需要介于 -1 和 len(categories)-1 之间
你知道为什么吗?