给定一个一维索引数组:
a = array([1, 0, 3])
我想将其作为一个二维数组进行one-hot编码:
b = array([[0,1,0,0], [1,0,0,0], [0,0,0,1]])
给定一个一维索引数组:
a = array([1, 0, 3])
我想将其作为一个二维数组进行one-hot编码:
b = array([[0,1,0,0], [1,0,0,0], [0,0,0,1]])
def one_hot_encode(x):
"""
argument
- x: a list of labels
return
- one hot encoding matrix (number of labels, number of class)
"""
encoded = np.zeros((len(x), 10))
for idx, val in enumerate(x):
encoded[idx][val] = 1
return encoded
在这里找到它 P.S 你不需要进入链接。
import numpy as np
a = np.array([1,0,3])
b = np.array([[0,1,0,0], [1,0,0,0], [0,0,0,1]])
from neuraxle.steps.numpy import OneHotEncoder
encoder = OneHotEncoder(nb_columns=4)
b_pred = encoder.transform(a)
assert b_pred == b
numpy.eye()
(但已经被另一个用户完成)。请务必仔细阅读问题和已发布的答案,以维护stackoverflow和社区的质量。 - Alexandre Huat