给定一个一维下标数组:
a = array([1, 0, 3])
我想把它编码成一个2D数组:
b = array([[0,1,0,0], [1,0,0,0], [0,0,0,1]])
给定一个一维下标数组:
a = array([1, 0, 3])
我想把它编码成一个2D数组:
b = array([[0,1,0,0], [1,0,0,0], [0,0,0,1]])
当前回答
以下是我认为有用的方法:
def one_hot(a, num_classes):
return np.squeeze(np.eye(num_classes)[a.reshape(-1)])
这里num_classes表示您拥有的类的数量。如果你有一个形状为(10000,)的向量,这个函数将它转换为(10000,C)注意,a是零索引,即one_hot(np。数组([0,1]),2)将给出[[1,0],[0,1]]。
我相信这正是你想要的。
PS:源代码是Sequence models - deeplearning.ai
其他回答
为了详细说明K3—rnc的优秀答案,这里有一个更通用的版本:
def onehottify(x, n=None, dtype=float):
"""1-hot encode x with the max value n (computed from data if n is None)."""
x = np.asarray(x)
n = np.max(x) + 1 if n is None else n
return np.eye(n, dtype=dtype)[x]
此外,这里是这个方法的快速和粗略的基准测试,以及YXD目前接受的答案(略有更改,以便他们提供相同的API,除了后者只适用于1D ndarray):
def onehottify_only_1d(x, n=None, dtype=float):
x = np.asarray(x)
n = np.max(x) + 1 if n is None else n
b = np.zeros((len(x), n), dtype=dtype)
b[np.arange(len(x)), x] = 1
return b
后一种方法快35% (MacBook Pro 13 2015),但前一种更通用:
>>> import numpy as np
>>> np.random.seed(42)
>>> a = np.random.randint(0, 9, size=(10_000,))
>>> a
array([6, 3, 7, ..., 5, 8, 6])
>>> %timeit onehottify(a, 10)
188 µs ± 5.03 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
>>> %timeit onehottify_only_1d(a, 10)
139 µs ± 2.78 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
以下是我认为有用的方法:
def one_hot(a, num_classes):
return np.squeeze(np.eye(num_classes)[a.reshape(-1)])
这里num_classes表示您拥有的类的数量。如果你有一个形状为(10000,)的向量,这个函数将它转换为(10000,C)注意,a是零索引,即one_hot(np。数组([0,1]),2)将给出[[1,0],[0,1]]。
我相信这正是你想要的。
PS:源代码是Sequence models - deeplearning.ai
我添加了一个简单的补全函数,只使用numpy操作符:
def probs_to_onehot(output_probabilities):
argmax_indices_array = np.argmax(output_probabilities, axis=1)
onehot_output_array = np.eye(np.unique(argmax_indices_array).shape[0])[argmax_indices_array.reshape(-1)]
return onehot_output_array
它以一个概率矩阵作为输入:例如:
[[0.03038822 0.65810204 0.16549407 0.3797123] . [0.02771272 0.2760752 0.3280924 0.33458805]
它会返回
[[0 0 0 0]... [0 0 0 1]
你可以使用sklearn.预处理。labelbinarizer:
例子:
import sklearn.preprocessing
a = [1,0,3]
label_binarizer = sklearn.preprocessing.LabelBinarizer()
label_binarizer.fit(range(max(a)+1))
b = label_binarizer.transform(a)
print('{0}'.format(b))
输出:
[[0 1 0 0]
[1 0 0 0]
[0 0 0 1]]
除此之外,你可以初始化sklearn.pre - processing. labelbinarizer(),这样transform的输出是稀疏的。
使用下面的代码。这样效果最好。
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.你不需要进入链接。