gpt4 book ai didi

python - 从字典计算欧氏距离(sklearn)

转载 作者:行者123 更新时间:2023-11-28 20:04:00 25 4
gpt4 key购买 nike

我的代码中已经计算了两个字典,如下所示:

X = {'a': 10, 'b': 3, 'c': 5, ...}
Y = {'a': 8, 'c': 3, 'e': 8, ...}

实际上它们包含来自 wiki 文本的单词,但这应该可以说明我的意思。它们不一定包含相同的 key 。

最初我想像这样使用 sklearn 的成对度量:

from sklearn.metrics.pairwise import pairwise_distances

obama = wiki[wiki['name'] == 'Barack Obama']['tf_idf'][0]
biden = wiki[wiki['name'] == 'Joe Biden']['tf_idf'][0]

obama_biden_distance = pairwise_distances(obama, biden, metric='euclidean', n_jobs=2)[0][0]

然而,这给出了一个错误:

--------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-124-7ff03bd40683> in <module>()
6 biden = wiki[wiki['name'] == 'Joe Biden']['tf_idf'][0]
7
----> 8 obama_biden_distance = pairwise_distances(obama, biden, metric='euclidean', n_jobs=2)[0][0]

/home/xiaolong/development/anaconda3/envs/coursera_ml_clustering_and_retrieval/lib/python3.4/site-packages/sklearn/metrics/pairwise.py in pairwise_distances(X, Y, metric, n_jobs, **kwds)
1205 func = partial(distance.cdist, metric=metric, **kwds)
1206
-> 1207 return _parallel_pairwise(X, Y, func, n_jobs, **kwds)
1208
1209

/home/xiaolong/development/anaconda3/envs/coursera_ml_clustering_and_retrieval/lib/python3.4/site-packages/sklearn/metrics/pairwise.py in _parallel_pairwise(X, Y, func, n_jobs, **kwds)
1058 ret = Parallel(n_jobs=n_jobs, verbose=0)(
1059 fd(X, Y[s], **kwds)
-> 1060 for s in gen_even_slices(Y.shape[0], n_jobs))
1061
1062 return np.hstack(ret)

AttributeError: 'dict' object has no attribute 'shape'

对我来说,这听起来像是在尝试访问 shape 属性,而 dict 没有。我猜它需要 numpy 数组。我如何转换字典,以便 sklearn 函数计算正确的距离,假设 0 值,如果字典没有某个键,另一个字典有吗?

最佳答案

你为什么不直接从你的稀疏表示来做呢?

In [1]: import math

In [2]: Y = {'a': 8, 'c':3,'e':8}

In [3]: X = {'a':10, 'b':3, 'c':5}

In [4]: math.sqrt(sum((X.get(d,0) - Y.get(d,0))**2 for d in set(X) | set(Y)))
Out[4]: 9.0

关于python - 从字典计算欧氏距离(sklearn),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38369742/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com