一种热编码未观察到的字符列表

问题描述 投票:0回答:1

我正在尝试为字符列表创建一个热编码(ohe),以允许未观察到的等级。使用Convert array of indices to 1-hot encoded numpy arrayFinding the index of an item given a list containing it in Python的答案,以下确实是我想要的:

# example data
# this is the full list including unobserved levels
av = list(map(chr, range(ord('a'), ord('z')+1))) 
# this is the vector to apply ohe
v = ['a', 'f', 'u'] 

# apply one hot encoding
ohe = np.zeros((len(v), len(av)))
for i in range(len(v)): ohe[i, av.index(v[i])] = 1
ohe

是否有更标准/更快的方法来执行此操作,请注意,上面的第二个链接提到了.index()的瓶颈。

((我的问题的规模:完整向量(av)具有〜1000个水平,并且ohe(v)的值的长度为0.5M。谢谢。

python one-hot-encoding
1个回答
0
投票

您可以使用查找字典:

# example data
# this is the full list including unobserved levels
av = list(map(chr, range(ord('a'), ord('z')+1)))
lookup = { v : i for i, v in enumerate(av)}

# this is the vector to apply ohe
v = ['a', 'f', 'u']

# apply one hot encoding
ohe = np.zeros((len(v), len(av)))
for i in range(len(v)):
    ohe[i, lookup[v[i]]] = 1

.index的复杂度是O(n)相对于在O(1)的字典中查找。

© www.soinside.com 2019 - 2024. All rights reserved.