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.]]