首页 > 解决方案 > 一个热编码具有未观察到的级别的字符列表

问题描述

我正在尝试为允许未观察到的级别的字符列表创建一个热编码(ohe)。使用将索引数组转换为 1-hot 编码的 numpy 数组的答案并在 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。谢谢。

标签: pythonone-hot-encoding

解决方案


您可以使用查找字典:

# 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

.indexis的复杂性O(n)与查找字典的复杂性是O(1). 您甚至可以通过执行以下操作来保存 for 循环:

indices = [lookup[vi] for vi in v]
ohe = np.zeros((len(v), len(av)))
ohe[np.arange(len(v)), indices] = 1

推荐阅读