在 NumPy 中将索引数组转换为独热编码数组
- 2025-01-13 08:53:00
- admin 原创
- 138
问题描述:
给定一维索引数组:
a = array([1, 0, 3])
我想将其独热编码为二维数组:
b = array([[0,1,0,0], [1,0,0,0], [0,0,0,1]])
解决方案 1:
创建一个b
具有足够列的零数组,即a.max() + 1
。
然后,对于每一行i
,将a[i]
第 列设置为1
。
>>> a = np.array([1, 0, 3])
>>> b = np.zeros((a.size, a.max() + 1))
>>> b[np.arange(a.size), a] = 1
>>> b
array([[ 0., 1., 0., 0.],
[ 1., 0., 0., 0.],
[ 0., 0., 0., 1.]])
解决方案 2:
>>> values = [1, 0, 3]
>>> n_values = np.max(values) + 1
>>> np.eye(n_values)[values]
array([[ 0., 1., 0., 0.],
[ 1., 0., 0., 0.],
[ 0., 0., 0., 1.]])
解决方案 3:
如果你正在使用 keras,那么有一个内置实用程序:
from keras.utils.np_utils import to_categorical
categorical_labels = to_categorical(int_labels, num_classes=3)
它的作用与@YXD 的答案几乎相同(参见源代码)。
解决方案 4:
以下是我认为有用的东西:
def one_hot(a, num_classes):
return np.squeeze(np.eye(num_classes)[a.reshape(-1)])
这里num_classes
代表您拥有的类数。因此,如果您有a
一个形状为(10000,)的向量,此函数会将其转换为(10000,C)。请注意,a
是从零开始索引的,即one_hot(np.array([0, 1]), 2)
会给出[[1, 0], [0, 1]]
。
我相信这正是您想要的。
PS:来源是Sequence models - deeplearning.ai
解决方案 5:
您还可以使用numpy的eye函数:
numpy.eye(number of classes)[vector containing the labels]
解决方案 6:
您可以使用 sklearn.preprocessing.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.preprocessing.LabelBinarizer()
以使输出transform
稀疏。
解决方案 7:
对于 1-hot 编码
one_hot_encode=pandas.get_dummies(array)
例如
享受编码
解决方案 8:
这是一个将一维向量转换为二维独热数组的函数。
#!/usr/bin/env python
import numpy as np
def convertToOneHot(vector, num_classes=None):
"""
Converts an input 1-D vector of integers into an output
2-D array of one-hot vectors, where an i'th input value
of j will set a '1' in the i'th row, j'th column of the
output array.
Example:
v = np.array((1, 0, 4))
one_hot_v = convertToOneHot(v)
print one_hot_v
[[0 1 0 0 0]
[1 0 0 0 0]
[0 0 0 0 1]]
"""
assert isinstance(vector, np.ndarray)
assert len(vector) > 0
if num_classes is None:
num_classes = np.max(vector)+1
else:
assert num_classes > 0
assert num_classes >= np.max(vector)
result = np.zeros(shape=(len(vector), num_classes))
result[np.arange(len(vector)), vector] = 1
return result.astype(int)
以下是一些用法示例:
>>> a = np.array([1, 0, 3])
>>> convertToOneHot(a)
array([[0, 1, 0, 0],
[1, 0, 0, 0],
[0, 0, 0, 1]])
>>> convertToOneHot(a, num_classes=10)
array([[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0]])
解决方案 9:
您可以使用以下代码将其转换为独热向量:
令 x 为普通类向量,具有一列,其类数为 0 到某个数字:
import numpy as np
np.eye(x.max()+1)[x]
如果 0 不是一个类;则删除 +1。
解决方案 10:
我发现最简单的解决方案np.take
是np.eye
def one_hot(x, depth: int):
return np.take(np.eye(depth), x, axis=0)
适用于x
任何形状。
解决方案 11:
我认为答案是否定的。对于n
尺寸方面更通用的情况,我想出了以下方法:
# For 2-dimensional data, 4 values
a = np.array([[0, 1, 2], [3, 2, 1]])
z = np.zeros(list(a.shape) + [4])
z[list(np.indices(z.shape[:-1])) + [a]] = 1
我想知道是否有更好的解决方案——我不喜欢在最后两行创建这些列表。无论如何,我做了一些测量timeit
,似乎numpy
基于(indices
/ arange
)和迭代版本的性能大致相同。
解决方案 12:
为了详细说明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 ndarrays):
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)
解决方案 13:
p 将是一个二维 ndarray。
我们想知道一行中哪个值最高,将那里放 1,其他地方放 0。
干净简单的解决方案:
max_elements_i = np.expand_dims(np.argmax(p, axis=1), axis=1)
one_hot = np.zeros(p.shape)
np.put_along_axis(one_hot, max_elements_i, 1, axis=1)
解决方案 14:
如果使用tensorflow
,则有one_hot()
:
import tensorflow as tf
import numpy as np
a = np.array([1, 0, 3])
depth = 4
b = tf.one_hot(a, depth)
# <tf.Tensor: shape=(3, 3), dtype=float32, numpy=
# array([[0., 1., 0.],
# [1., 0., 0.],
# [0., 0., 0.]], dtype=float32)>
解决方案 15:
def one_hot(n, class_num, col_wise=True):
a = np.eye(class_num)[n.reshape(-1)]
return a.T if col_wise else a
# Column for different hot
print(one_hot(np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9, 9, 9, 8, 7]), 10))
# Row for different hot
print(one_hot(np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9, 9, 9, 8, 7]), 10, col_wise=False))
解决方案 16:
我最近遇到了一个类似的问题,发现上述解决方案只有在数字符合特定格式时才令人满意。例如,如果你想对以下列表进行独热编码:
all_good_list = [0,1,2,3,4]
继续吧,上面已经提到了发布的解决方案。但如果考虑以下数据,情况会怎样:
problematic_list = [0,23,12,89,10]
如果您使用上述方法,您很可能最终会得到 90 个 one-hot 列。这是因为所有答案都包含类似 的内容n = np.max(a)+1
。我找到了一个更通用的解决方案,它对我有用,想与您分享:
import numpy as np
import sklearn
sklb = sklearn.preprocessing.LabelBinarizer()
a = np.asarray([1,2,44,3,2])
n = np.unique(a)
sklb.fit(n)
b = sklb.transform(a)
我希望有人遇到上述解决方案的相同限制,并且这可能会派上用场
解决方案 17:
这是一个与维度无关的独立解决方案。
这会将任何 N 维arr
非负整数数组转换为独热 N+1 维数组one_hot
,其中one_hot[i_1,...,i_N,c] = 1
意味着arr[i_1,...,i_N] = c
。您可以通过以下方式恢复输入np.argmax(one_hot, -1)
def expand_integer_grid(arr, n_classes):
"""
:param arr: N dim array of size i_1, ..., i_N
:param n_classes: C
:returns: one-hot N+1 dim array of size i_1, ..., i_N, C
:rtype: ndarray
"""
one_hot = np.zeros(arr.shape + (n_classes,))
axes_ranges = [range(arr.shape[i]) for i in range(arr.ndim)]
flat_grids = [_.ravel() for _ in np.meshgrid(*axes_ranges, indexing='ij')]
one_hot[flat_grids + [arr.ravel()]] = 1
assert((one_hot.sum(-1) == 1).all())
assert(np.allclose(np.argmax(one_hot, -1), arr))
return one_hot
解决方案 18:
这种类型的编码通常是 numpy 数组的一部分。如果你使用这样的 numpy 数组:
a = np.array([1,0,3])
然后有一个非常简单的方法可以将其转换为 1-hot 编码
out = (np.arange(4) == a[:,None]).astype(np.float32)
就是这样。
解决方案 19:
下面是我根据上述答案和我自己的用例编写的一个示例函数:
def label_vector_to_one_hot_vector(vector, one_hot_size=10):
"""
Use to convert a column vector to a 'one-hot' matrix
Example:
vector: [[2], [0], [1]]
one_hot_size: 3
returns:
[[ 0., 0., 1.],
[ 1., 0., 0.],
[ 0., 1., 0.]]
Parameters:
vector (np.array): of size (n, 1) to be converted
one_hot_size (int) optional: size of 'one-hot' row vector
Returns:
np.array size (vector.size, one_hot_size): converted to a 'one-hot' matrix
"""
squeezed_vector = np.squeeze(vector, axis=-1)
one_hot = np.zeros((squeezed_vector.size, one_hot_size))
one_hot[np.arange(squeezed_vector.size), squeezed_vector] = 1
return one_hot
label_vector_to_one_hot_vector(vector=[[2], [0], [1]], one_hot_size=3)
解决方案 20:
我正在添加一个简单的函数来完成,仅使用 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 1 0 0]...[0 0 0 1]]
解决方案 21:
对于拥有 ndarray 的更一般情况,您可以使用 numpy 广播:
a = array([[[[1, 0, 3]]]]) # (1, 1, 1, 3)
b = (a[..., np.newaxis] == np.arange(np.max(a) + 1)).astype(np.int32)
这将给你:
array([[[[[0, 1, 0, 0],
[1, 0, 0, 0],
[0, 0, 0, 1]]]]], dtype=int32)
结果形状为 (1, 1, 1, 3, 4)。
解决方案 22:
简单示例使用np.put_along_axis
:
x = rng.integers(0, 10, 20)
t = np.zeros([20, 10])
np.put_along_axis(t, indices=np.expand_dims(x, 1), values=1, axis=1)
print(x)
print(t)
[8 6 5 2 3 0 0 0 1 8 6 9 5 6 9 7 6 5 5 9]
[[0. 0. 0. 0. 0. 0. 0. 0. 1. 0.]
[0. 0. 0. 0. 0. 0. 1. 0. 0. 0.]
[0. 0. 0. 0. 0. 1. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 1. 0. 0. 0. 0. 0. 0.]
[1. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[1. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[1. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 1. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 1. 0.]
[0. 0. 0. 0. 0. 0. 1. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
[0. 0. 0. 0. 0. 1. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 1. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
[0. 0. 0. 0. 0. 0. 0. 1. 0. 0.]
[0. 0. 0. 0. 0. 0. 1. 0. 0. 0.]
[0. 0. 0. 0. 0. 1. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 1. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]]
解决方案 23:
使用以下代码。效果最好。
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
在这里找到了PS 您不需要进入链接。
解决方案 24:
使用Neuraxle管道步骤:
设置您的示例
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
文档链接:neuraxle.steps.numpy.OneHotEncoder
扫码咨询,免费领取项目管理大礼包!