python - 一个热编码具有未观察到的级别的字符列表
问题描述
我正在尝试为允许未观察到的级别的字符列表创建一个热编码(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。谢谢。
解决方案
您可以使用查找字典:
# 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
is的复杂性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
推荐阅读
- math - 像马赛克一样分割一个矩形
- php - PHP 致命错误:调用未定义的方法 mysqli_stmt::get_result()
- c - stm32多个ADC redings错误
- javascript - React Native - 在 Redux 不工作的情况下从 api 按 ID 导航
- python - Python 编码 '\xdf' / '\xc3\x9f' 到 'ß'
- sql - 我未能将身份放在表格的现有列上
- unity3d - 如何在一段时间内将物体沿圆周移动一定角度
- jquery - 获取formData中的值
- angular - 从外部到特定路线 angular2 应用程序的深层链接
- javascript - Nightmare.js FOR 循环