Python学习onehot编码分类的,有时重复的值

2024-09-30 22:20:56 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我对sklearn的onehotcoder的问题。 对于数组a = [1,2,3,4,5,6,7,8,9,22],即a.shape=[10,1](在reshape(-1,1)之后)的所有唯一值,返回onehotcoded值的[10,10]矩阵。你知道吗

array([[ 0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.],
   [ 0.,  0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.],
   [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.,  0.],
   [ 0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
   [ 1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
   [ 0.,  0.,  0.,  0.,  0.,  0.,  1.,  0.,  0.,  0.],
   [ 0.,  0.,  0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.],
   [ 0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
   [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.],
   [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.,  0.,  0.]])

但是对于类似a = [1,2,2,4,4,6,7,8,9,22]的数组,即a.shape=[10,1](在reshape(-1,1)之后)的非唯一数组,返回onehotcoded值的[10,8]矩阵。你知道吗

array([[ 1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
   [ 0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.],
   [ 0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.],
   [ 0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.],
   [ 0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.],
   [ 0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.],
   [ 0.,  0.,  0.,  0.,  1.,  0.,  0.,  0.],
   [ 0.,  0.,  0.,  0.,  0.,  1.,  0.,  0.],
   [ 0.,  0.,  0.,  0.,  0.,  0.,  1.,  0.],
   [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.]])

但我不能用它作为输入占位符,它需要一个[10,10]矩阵作为输入。有人能帮我处理sklearn的onehotcoder中的非唯一值吗?你知道吗

p.S添加参数n\u values=10会产生一个错误ValueError: Feature out of bounds for n_values=10


Tags: of参数错误矩阵数组sklearnoutarray
1条回答
网友
1楼 · 发布于 2024-09-30 22:20:56

你知道你的分类特征可以接受的所有值吗?如果是这样,你可以这样做:

enc = OneHotEncoder()   
enc.fit(np.asarray([1,2,3,4,5,6,7,8,9,22]).reshape(-1, 1)) #fit your encoder to the values
data_for_encoding =  np.asarray([1,2,2,4,4,6,7,8,9,22]).reshape(-1, 1) #your data
sparse_matrix = enc.transform(data_for_encoding) #encoded data

相关问题 更多 >