Skip to main content
 首页 » 编程设计

python之科学数据包 : Convert one-hot encoding to encoding with integers

2024年10月01日11开发

我需要将单热编码转换为由唯一整数表示的类别。因此,使用以下代码创建了单热编码:

from sklearn.preprocessing import OneHotEncoder 
enc = OneHotEncoder() 
labels = [[1],[2],[3]] 
enc.fit(labels)   
for x in [1,2,3]: 
    print(enc.transform([[x]]).toarray()) 
 
Out: 
[[ 1.  0.  0.]] 
[[ 0.  1.  0.]] 
[[ 0.  0.  1.]] 

可以转换回一组唯一的整数,例如:

[1,2,3] 或 [11,37, 45] 或任何其他整数,其中每个整数唯一地代表一个类。

是否可以使用 scikit-learn 或任何其他 python 库?

* 更新 *

试图:

labels = [[1],[2],[3], [4], [5],[6],[7]] 
enc.fit(labels)  
 
lst = [] 
for x in [1,2,3,4,5,6,7]: 
    lst.append(enc.transform([[x]]).toarray()) 
lst 
Out: 
[array([[ 1.,  0.,  0.,  0.,  0.,  0.,  0.]]), 
 array([[ 0.,  1.,  0.,  0.,  0.,  0.,  0.]]), 
 array([[ 0.,  0.,  1.,  0.,  0.,  0.,  0.]]), 
 array([[ 0.,  0.,  0.,  1.,  0.,  0.,  0.]]), 
 array([[ 0.,  0.,  0.,  0.,  1.,  0.,  0.]]), 
 array([[ 0.,  0.,  0.,  0.,  0.,  1.,  0.]]), 
 array([[ 0.,  0.,  0.,  0.,  0.,  0.,  1.]])] 
 
 
a = np.array(lst) 
np.where(a==1)[1] 
Out: 
array([0, 0, 0, 0, 0, 0, 0], dtype=int64) 

不是我需要的

请您参考如下方法:

您可以使用 np.where 执行此操作,如下所示:

import numpy as np 
a=np.array([[ 0.,  1.,  0.], 
            [ 1.,  0.,  0.], 
            [ 0.,  0.,  1.]]) 
np.where(a==1)[1] 

这会打印 array([1, 0, 2], dtype=int64)。这是有效的,因为 np.where(a==1)[1] 返回 1 的列索引,这正是标签。

此外,由于a是一个0,1矩阵,你也可以替换np.where(a==1)[1] 仅包含 np.where(a)[1]。

更新:以下解决方案应该适用于您的格式:

l=[np.array([[ 1.,  0.,  0.,  0.,  0.,  0.,  0.]]), 
 np.array([[ 0.,  0.,  1.,  0.,  0.,  0.,  0.]]), 
 np.array([[ 0.,  1.,  0.,  0.,  0.,  0.,  0.]]), 
 np.array([[ 0.,  0.,  0.,  0.,  1.,  0.,  0.]]), 
 np.array([[ 0.,  0.,  0.,  0.,  1.,  0.,  0.]]), 
 np.array([[ 0.,  0.,  0.,  0.,  0.,  1.,  0.]]), 
 np.array([[ 0.,  0.,  0.,  0.,  0.,  0.,  1.]])] 
a=np.array(l) 
 
np.where(a)[2] 

这打印

array([0, 2, 1, 4, 4, 5, 6], dtype=int64) 

或者,您可以将原始解决方案与@ml4294 的评论一起使用。