[英]Reshape dictionary values from 1D to 2D array
I want to calculate cosine similarity for words in two dictionaries. 我想计算两个字典中单词的余弦相似度。 The words are keys, arrays are values.
单词是键,数组是值。 In order to do this, I need to convert them to 2D array first, I did some research and found
x = x.reshape(1,-1)
I successfully converted it with a single value in dictionary, however, I don't know how to convert the whole dictionary's values by using for loops. 为此,我需要先将它们转换为2D数组,我进行了一些研究,发现
x = x.reshape(1,-1)
我成功地用字典中的单个值将其转换了,但是,我没有知道如何使用for循环转换整个字典的值。
The data 数据
D
{'A': array([ 4.80625004e-01, -1.40245005e-01, -9.99999046e-03]),
'B': array([-0.46553 , -0.1519755 , 0.41836]),
'C': array([0.0090175 , 0.05817001, -0.09712502])}
D2 (same format as D)
{'D': ([8.11059952e-01, 6.84859991e-01, 1.01619996e-01]),
'E':([-0.82868 , 0.49513 , 0.67581]),
'F':([-0.17093 , 0.88746 , 0.0931135])}
I tried 我试过了
for i in D2.items():
D2[i] = D2[i].reshape(1, -1) #Error on this line
but received error: TypeError: unhashable type: 'numpy.ndarray' 但收到错误: TypeError:无法散列的类型:'numpy.ndarray'
Some advice please? 请问一些建议吗? thank you in advanced!
在此先感谢您!
Dict.items() returns tuples of the key, value pairs. Dict.items()返回键值对的元组。 Therefore in your case
i
is a tuple of the key and the value. 因此,在您的情况下,
i
是键和值的元组。 Try: 尝试:
for i, value in D2.items():
D2[i] = value.reshape(1, -1)
try this 尝试这个
from numpy import array
d = dict({'A': array([ 4.80625004e-01, -1.40245005e-01, -9.99999046e-03]),
'B': array([-0.46553 , -0.1519755 , 0.41836]),
'C': array([0.0090175 , 0.05817001, -0.09712502])})
reshaped_arrays = dict()
for x, j in d.items():
dd[x]=j.reshape(1,-1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.