【问题标题】:One hot encoding a list of characters with unobserved levels一个热编码具有未观察级别的字符列表
【发布时间】:2019-10-14 15:04:54
【问题描述】:

我正在尝试创建一个允许未观察级别的字符列表的单一热编码 (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】:

    您可以使用查找字典:

    # 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)。您甚至可以通过以下方式保存 for 循环:

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

    【讨论】:

    • 很高兴我能帮上忙 :)
    猜你喜欢
    • 1970-01-01
    • 2020-08-12
    • 1970-01-01
    • 1970-01-01
    • 2018-02-14
    • 2017-09-22
    • 1970-01-01
    • 1970-01-01
    • 2018-11-04
    相关资源
    最近更新 更多