Python中将X(假设X的大小为1*m,类别为k类)转换为one-hot矩阵
准备一个eye(k)矩阵,然后根据X将对应的列取出来。(或者把行取出来再转置)
def conv_to_one_hot(X,n):
X = np.array(X)
refer = np.eye(n)
X_one_hot = refer[X]
return X_one_hot.T
X=[3,5,4,7]
print(conv_to_one_hot(X,8))
结果为:
[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]
[1. 0. 0. 0.]
[0. 0. 1. 0.]
[0. 1. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 1.]]
本文介绍了一种在Python中实现one-hot编码的方法,通过使用numpy和eye函数创建单位矩阵,并根据输入向量X(大小为1*m,类别为k类)选取对应列,最终返回转换后的one-hot矩阵。
1280

被折叠的 条评论
为什么被折叠?



