dok*_*ndr 5 python scikit-learn one-hot-encoding
我需要将 one-hot 编码转换为由唯一整数表示的类别。因此,使用以下代码创建了 one-hot 编码:
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.]]
Run Code Online (Sandbox Code Playgroud)
可以转换回一组唯一的整数,例如:
[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)
Run Code Online (Sandbox Code Playgroud)
不是我需要的
您可以使用np.where以下方法来做到这一点:
import numpy as np
a=np.array([[ 0., 1., 0.],
[ 1., 0., 0.],
[ 0., 0., 1.]])
np.where(a==1)[1]
Run Code Online (Sandbox Code Playgroud)
这打印array([1, 0, 2], dtype=int64). 这是有效的,因为np.where(a==1)[1]返回 的列索引1,这正是标签。
另外,由于a是0,1-matrix,因此也可以替换np.where(a==1)[1]为 just 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]
Run Code Online (Sandbox Code Playgroud)
这打印
array([0, 2, 1, 4, 4, 5, 6], dtype=int64)
Run Code Online (Sandbox Code Playgroud)
或者,您可以将原始解决方案与@ml4294 的评论一起使用。
| 归档时间: |
|
| 查看次数: |
11681 次 |
| 最近记录: |