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

Python 如何使用Numpy对字符串数组进行热编码?,python,numpy,Python,Numpy,我知道存在次优的解决方案,但我正在尝试优化我的代码。到目前为止,我找到的最短路径是: 将numpy导入为np 从sklearn.preprocessing导入序号编码器 target=np.数组(['dog','dog','cat','cat','cat','dog','dog','cat','cat'])) oe=普通编码器() target=oe.fit_变换(target.reforme(-1,1)).ravel() target=np.eye(np.unique(target.shape

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

将numpy导入为np
从sklearn.preprocessing导入序号编码器
target=np.数组(['dog','dog','cat','cat','cat','dog','dog','cat','cat']))
oe=普通编码器()
target=oe.fit_变换(target.reforme(-1,1)).ravel()
target=np.eye(np.unique(target.shape[0])[np.array(target,dtype=np.int32)]
打印(目标)
[[0.1.]
[0.1.]
[1.0.]
[1.0.]


这是一段难看的代码,而且很长。删除其中的任何部分都不会起作用。我正在寻找一种更简单的方法,不需要从两个不同的库调用超过六个函数。

明白了。这将适用于任意数量的唯一值数组

将numpy导入为np
target=np.数组(['dog','dog','cat','cat','cat','dog','dog','dog',',
“猫”、“猫”、“仓鼠”、“仓鼠”])
def 1_热(阵列):
unique,inverse=np.unique(数组,返回值\u inverse=True)
onehot=np.eye(唯一的.shape[0])[逆]
返回onehot
打印(1_热(目标))
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.]]


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

将numpy导入为np
target=np.数组(['dog','dog','cat','cat','cat','dog','dog','dog',',
“猫”、“猫”、“仓鼠”、“仓鼠”])
def 1_热(阵列):
unique,inverse=np.unique(数组,返回值\u inverse=True)
onehot=np.eye(唯一的.shape[0])[逆]
返回onehot
打印(1_热(目标))
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.]]

为什么不使用

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

>>> ohe.categories_
[array(['cat', 'dog'], dtype='<U3')]
>>ohe.categories_
[数组(['cat','dog',dtype='为什么不使用

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

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

[array(['cat','dog',dtype='您可以使用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)

您可以使用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)

oe
生成的
目标是什么
oe
预处理生成的
目标是什么
预处理生成的
目标是什么。OneHotEncoder
也会这样做,尽管您的速度更快。您没有使用
参数返回到
numpy.unique
,而不是
numpy.searchsorted
另外,您正在调用
numpy.array
中已经是
np.array(array)中的数组的内容
。另外,使用
return\u counts=True
是不必要的。您只使用结果的长度,但该长度与
字的长度相同
预处理。OneHotEncoder
也可以这样做,尽管您的速度更快。您是否有任何特殊原因没有使用
return\u inverse
参数来
numpy.unique
,而不是
numpy.searchsorted
?另外,您正在调用
numpy.array
,该对象已经是
np.array(array)中的数组
。此外,不需要使用
return\u counts=True
。您只使用结果的长度,但该长度与
单词的长度相同。这不是NumPy这不是NumPy