[英]Convert array of indices to 1-hot encoded numpy array
假設我有一個 1d numpy 數組
a = array([1,0,3])
您的數組a
定義了輸出數組中非零元素的列。 您還需要定義行,然后使用花式索引:
>>> 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.]])
>>> 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.]])
以下是我認為有用的內容:
def one_hot(a, num_classes):
return np.squeeze(np.eye(num_classes)[a.reshape(-1)])
這里num_classes
代表您擁有的類數。 因此,如果您有a
形狀為(10000,) a
向量,則此函數會將其轉換為(10000,C) 。 請注意, a
是零索引的,即one_hot(np.array([0, 1]), 2)
將給出[[1, 0], [0, 1]]
。
正是你想要的,我相信。
PS:來源是序列模型-deeplearning.ai
您還可以使用 numpy 的眼睛功能:
numpy.eye(number of classes)[vector containing the labels]
您可以使用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
的輸出是稀疏的。
您可以使用以下代碼轉換為 one-hot 向量:
讓 x 是具有單個列的普通類向量,其中類為 0 到某個數字:
import numpy as np
np.eye(x.max()+1)[x]
如果 0 不是一個類; 然后刪除+1。
這是一個將一維向量轉換為二維單熱數組的函數。
#!/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]])
我認為簡短的回答是否定的。 對於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
)和迭代版本的表現大致相同。
只是為了詳細說明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)
我最近遇到了同樣的問題,並找到了上述解決方案,結果證明只有當你的數字符合某種形式時才會令人滿意。 例如,如果您想對以下列表進行單熱編碼:
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)
我希望有人在上述解決方案上遇到相同的限制,這可能會派上用場
這種類型的編碼通常是 numpy 數組的一部分。 如果您使用的是這樣的 numpy 數組:
a = np.array([1,0,3])
那么有一種非常簡單的方法可以將其轉換為 1-hot 編碼
out = (np.arange(4) == a[:,None]).astype(np.float32)
就是這樣。
干凈簡單的解決方案:
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)
這是我根據上述答案和我自己的用例編寫的示例函數:
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)
我正在添加一個簡單的函數來完成,僅使用 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]]
這是一個與維度無關的獨立解決方案。
這會將任何非負整數的 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
使用以下代碼。 它效果最好。
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 你不需要進入鏈接。
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
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))
我發現最簡單的解決方案結合了
np.take<\/code>和
np.eye<\/code>
def one_hot(x, num_classes: int):
return np.take(np.eye(num_classes), x, axis=0)
如果使用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)>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.