【发布时间】:2022-01-12 15:03:29
【问题描述】:
我创建了数据的稀疏表示,并希望将其转换为 Numpy 数组。
假设我有以下数据(实际上data 包含更多列表,每个列表更长):
data = [['this','is','my','first','dataset','here'],['but','here', 'is', 'another','one'],['and','yet', 'another', 'one']]
我有两个 dict 项目将每个单词映射到一个唯一的整数值,反之亦然:
w2i = {'this':0, 'is':1, 'my':2, 'first':3, 'dataset':4, 'here':5, 'but':6, 'another':7, 'one':8, 'and':9, 'yet':10}
此外,我有一个 dict 可以获取每个单词组合的计数:
comb_dict = dict()
for text in data:
sorted_set_text = sorted(list(set(text)))
for i in range(len(sorted_set_text)-1):
for j in range(i+1, len(sorted_set_text)):
if (sorted_set_text[i],sorted_set_text[j]) in comb_dict:
comb_dict[(sorted_set_text[i],sorted_set_text[j])] += 1
else:
comb_dict[(sorted_set_text[i],sorted_set_text[j])] = 1
从这个字典中,我创建了一个稀疏表示,如下所示:
sparse = [(w2i[k[0]],w2i[k[1]],v) for k,v in comb_dict.items()]
此列表由元组组成,其中第一个值表示 x 轴的位置,第二个值表示 y 轴的位置,第三个值表示同时出现的次数:
[(4, 3, 1),
(4, 5, 1),
(4, 1, 1),
(4, 2, 1),
(4, 0, 1),
(3, 5, 1),
(3, 1, 1),
(3, 2, 1),
(3, 0, 1),
(5, 1, 2),
(5, 2, 1),
(5, 0, 1),
(1, 2, 1),
(1, 0, 1),
(2, 0, 1),
(7, 6, 1),
(7, 5, 1),
(7, 1, 1),
(7, 8, 2),
(6, 5, 1),
(6, 1, 1),
(6, 8, 1),
(5, 8, 1),
(1, 8, 1),
(9, 7, 1),
(9, 8, 1),
(9, 10, 1),
(7, 10, 1),
(8, 10, 1)]
现在,我想得到一个Numpy array (11 x 11),其中 i 行和 j 列的每一行代表一个单词,单元格表示单词 i 和 j 共同出现的频率。因此,开始将是
cooc = np.zeros((len(w2i),len(w2i)), dtype=np.int16)
然后,我想更新cooc,以便为与sparse 中的单词组合相关联的行/列索引分配相关值。我该怎么做?
编辑:我知道我可以遍历cooc 并一个一个地分配每个单元格。但是,我的数据集很大,这将非常耗时。相反,我想将 cooc 转换为 Scipy 稀疏矩阵并使用 toarray() 方法。我该怎么做?
【问题讨论】:
标签: python arrays numpy sparse-matrix