如何使用Numpy对字符串数组进行onehot编码?

2024-06-16 12:29:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道有次优的解决方案,但我正在努力优化我的代码。到目前为止,我找到的最短路径是:

import numpy as np
from sklearn.preprocessing import OrdinalEncoder

target = np.array(['dog', 'dog', 'cat', 'cat', 'cat', 'dog', 'dog', 'cat', 'cat'])

oe = OrdinalEncoder()
target = oe.fit_transform(target.reshape(-1, 1)).ravel()
target = np.eye(np.unique(target).shape[0])[np.array(target, dtype=np.int32)]
print(target)

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

这是很难看的代码,而且很长。去掉它的任何部分,它都不会起作用。我正在寻找一种更简单的方法,不需要调用来自两个不同库的超过六个函数。你知道吗


Tags: 代码fromimport路径numpytargetasnp
3条回答

明白了。这将适用于任何数量的唯一值数组。你知道吗

import numpy as np

target = np.array(['dog', 'dog', 'cat', 'cat', 'cat', 'dog', 'dog', 
    'cat', 'cat', 'hamster', 'hamster'])

def one_hot(array):
    unique, inverse = np.unique(array, return_inverse=True)
    onehot = np.eye(unique.shape[0])[inverse]
    return onehot

print(one_hot(target))

Out[9]:
[[0., 1., 0.],
[0., 1., 0.],
[1., 0., 0.],
[1., 0., 0.],
[1., 0., 0.],
[0., 1., 0.],
[0., 1., 0.],
[1., 0., 0.],
[1., 0., 0.],
[0., 0., 1.],
[0., 0., 1.]])

你可以使用keras和LabelEncoder

import numpy as np
from keras.utils import to_categorical
from sklearn.preprocessing import LabelEncoder

# define example
data = np.array(['dog', 'dog', 'cat', 'cat', 'cat', 'dog', 'dog', 'cat', 'cat'])

label_encoder = LabelEncoder()
data = label_encoder.fit_transform(data)
# one hot encode
encoded = to_categorical(data)

为什么不使用OneHotEncoder?你知道吗

>>> from sklearn.preprocessing import OneHotEncoder
>>> ohe = OneHotEncoder(categories='auto', sparse=False)
>>> arr = ohe.fit_transform(target[:, np.newaxis])
>>> arr
array([[0., 1.],
       [0., 1.],
       [1., 0.],
       [1., 0.],
       [1., 0.],
       [0., 1.],
       [0., 1.],
       [1., 0.],
       [1., 0.]])

它存储了有关转换的良好元数据:

>>> ohe.categories_
[array(['cat', 'dog'], dtype='<U3')]

此外,您还可以轻松转换回:

>>> ohe.inverse_transform(arr).ravel()
array(['dog', 'dog', 'cat', 'cat', 'cat', 'dog', 'dog', 'cat', 'cat'],
      dtype='<U3')

相关问题 更多 >