Skip to main content
 首页 » 编程设计

python之从字典值生成一个热编码

2025年05月04日11xing901022

我试图根据我的字典字符制作一个单热数组:首先,我创建了一个具有行 X 列 (3x7) 的 numpy zeros,然后我搜索每个字符的 ID 并将“1”分配给每个字符numpy 数组的行。

我的目标是为每个角色分配一个热数组。 “1”表示“存在”,“0”表示“不存在”。这里我们有 3 个字符,所以我们应该有 3 行,而 7 列作为字典中存在的字符。

但是,我收到一条错误消息,指出“类型错误:只能将整数标量数组转换为标量索引”。谁能帮我解决这个问题?谢谢

为了不让大家误解我的字典:

这是我创建 dic 的方法:

sent = ["a", "b", "c", "d", "e", "f", "g"] 
aaa = len(sent) 
aa = {x:i for i,x in enumerate(sent)} 

我的代码:

import numpy as np 
sentences = ["b", "c", "e"] 
a = {} 
for xx in sentences: 
   a[xx] = aa[xx] 
a = {"b":1, "c":2, "e":4} 
aa =len(a) 
 
for x,y in a.items(): 
    aa = np.zeros((aa,aaa)) 
    aa[y] = 1 
 
print(aa) 

当前错误:

TypeError: only integer scalar arrays can be converted to a scalar index 

我的预期输出:

[[0. 1. 0. 0. 0. 0. 0.] 
 [0. 0. 1. 0. 0. 0. 0.] 
 [0. 0. 0. 0. 1. 0. 0.]] 

------> 因为它是字典,所以索引排列应该不同,数组中的“1”是一个虚拟的,这样我就可以显示我的预期输出。

请您参考如下方法:

设置索引

(内联评论。)

# Sort and extract the indices. 
idx = sorted(a.values()) 
# Initialise a matrix of zeros. 
aa = np.zeros((len(idx), max(idx) + 1)) 
# Assign 1 to appropriate indices. 
aa[np.arange(len(aa)), idx] = 1 

print (aa) 
array([[0., 1., 0., 0., 0.], 
       [0., 0., 1., 0., 0.], 
       [0., 0., 0., 0., 1.]]) 

numpy.eye

idx = sorted(a.values()) 
eye = np.eye(max(idx) + 1)     
aa = eye[idx] 

print (aa) 
array([[0., 1., 0., 0., 0.], 
       [0., 0., 1., 0., 0.], 
       [0., 0., 0., 0., 1.]])