python数组索引为

编程入门 行业动态 更新时间:2024-10-14 20:19:40

python<a href=https://www.elefans.com/category/jswz/34/1771288.html style=数组索引为"/>

python数组索引为

python - 将索引数组转换为1-hot编码的numpy数组

假设我有一个ndy阵列

a = array([1,0,3])

我想将其编码为2d 1-hot阵列

b = array([[0,1,0,0], [1,0,0,0], [0,0,0,1]])

有快速的方法吗? 比仅仅循环a更快,设置元素b,即。

15个解决方案

251 votes

数组a定义输出数组中非零元素的列。 您还需要定义行,然后使用花式索引:

>>> a = np.array([1, 0, 3])

>>> b = np.zeros((3, 4))

>>> b[np.arange(3), a] = 1

>>> b

array([[ 0., 1., 0., 0.],

[ 1., 0., 0., 0.],

[ 0., 0., 0., 1.]])

YXD answered 2019-05-29T14:10:39Z

107 votes

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

K3---rnc answered 2019-05-29T14:10:58Z

24 votes

你可以使用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的输出是稀疏的。

Franck Dernoncourt answered 2019-05-29T14:11:39Z

19 votes

这是我觉得有用的东西:

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:来源是序列模型 - deeplearning.ai

D.Samchuk answered 2019-05-29T14:12:33Z

15 votes

如果您使用keras,则有一个内置实用程序:

from keras.utils.np_utils import to_categorical

categorical_labels = to_categorical(int_labels, num_classes=3)

它与@ YXD的答案几乎相同(参见源代码)。

Jodo answered 2019-05-29T14:13:11Z

3 votes

这是一个将1-D向量转换为2-D单热阵列的函数。

#!/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]])

stackoverflowuser2010 answered 2019-05-29T14:13:53Z

3 votes

numpy.eye(类的大小)[要转换的向量]

Karma answered 2019-05-29T14:14:25Z

2 votes

我认为简短的回答是否定的。 对于timeit维度的更通用案例,我想出了这个:

# 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)和迭代版本执行大致相同。

David Nemeskey answered 2019-05-29T14:15:06Z

1 votes

只是为了详细说明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)

Emil Melnikov answered 2019-05-29T14:15:53Z

1 votes

我最近遇到了同样的问题,并且发现所说的解决方案只有在某个形式内有数字时才会令人满意。 例如,如果您想要以下列表进行单热编码:

all_good_list = [0,1,2,3,4]

继续,上面已经提到了已发布的解决方案。 但是如果考虑这些数据呢:

problematic_list = [0,23,12,89,10]

如果您使用上述方法执行此操作,您最终可能会得到90个单热列。 这是因为所有的答案都包括像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)

我希望有人在上述解决方案中遇到相同的限制,这可能会派上用场

Hans T answered 2019-05-29T14:16:47Z

0 votes

这是我根据上面的答案和我自己的用例编写的一个示例函数:

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)

Aaron Lelevier answered 2019-05-29T14:17:19Z

0 votes

我正在添加完成一个简单的函数,只使用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]]

Jordy Van Landeghem answered 2019-05-29T14:18:24Z

0 votes

这是一个独立于维度的独立解决方案。

这将非负整数的任何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

eqzx answered 2019-05-29T14:19:09Z

0 votes

这种类型的编码通常是numpy数组的一部分。 如果你使用这样的numpy数组:

a = np.array([1,0,3])

然后有一种非常简单的方法将其转换为1-hot编码

out = (np.arange(4) == a[:,None]).astype(np.float32)

而已。

Sudeep K Rana answered 2019-05-29T14:19:54Z

0 votes

p将是一个2d数组。

我们想要知道哪一个值是连续的最高值,将其放在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)

MiFi answered 2019-05-29T14:20:43Z

更多推荐

python数组索引为

本文发布于:2024-02-07 00:52:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1751636.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   索引   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!