gpt4 book ai didi

python - Python 中三角距离矩阵的距离 CSV

转载 作者:太空宇宙 更新时间:2023-11-04 01:33:01 25 4
gpt4 key购买 nike

我在关键字之间有一个很大的相似性 csv,我想将它转换为三角距离矩阵(因为它非常大并且稀疏会更好)以使用 scipy 执行层次聚类。我当前的数据 csv 如下所示:

a,  b, 1
b, a, 1
c, a, 2
a, c, 2

我不知道该怎么做,而且我找不到任何关于在 python 中进行集群的简单教程。

感谢您的帮助!

最佳答案

这个问题有两个部分:

  • 如何将这种格式的 CSV 中的距离加载到(可能是稀疏的)三角距离矩阵中?

  • 给定一个三角距离矩阵,如何用scipy做层次聚类?

如何加载数据:我不认为scipy.cluster.hierarchy使用稀疏数据,所以让我们把它做密集。我也打算把它做成完整的方阵,然后出于懒惰而采用 ​​scipy 想要的上三角形;如果你更聪明的话,你可以直接索引压缩版本。

from collections import defaultdict
import csv
import functools
import itertools
import numpy as np

# name_to_id associates a name with an integer 0, 1, ...
name_to_id = defaultdict(functools.partial(next, itertools.count()))

with open('file.csv') as f:
reader = csv.reader(f)

# do one pass over the file to get all the IDs so we know how
# large to make the matrix, then another to fill in the data.
# this takes more time but uses less memory than loading everything
# in in one pass, because we don't know how large the matrix is; you
# can skip this if you do know the number of elements from elsewhere.
for name_a, name_b, dist in reader:
idx_a = name_to_id[name_a]
idx_b = name_to_id[name_b]

# make the (square) distances matrix
# this should really be triangular, but the formula for
# indexing into that is escaping me at the moment
n_elem = len(name_to_id)
dists = np.zeros((n_elem, n_elem))

# go back to the start of the file and read in the actual data
f.seek(0)
for name_a, name_b, dist in reader:
idx_a = name_to_id[name_a]
idx_b = name_to_id[name_b]
dists[(idx_a, idx_b) if idx_a < idx_b else (idx_b, idx_a)] = dist

condensed = dists[np.triu_indices(n_elem, 1)]

然后调用例如scipy.cluster.hierarchy.linkage带有condensed。要从索引映射回名称,您可以使用类似

id_to_name = dict((id, name) for name, id in name_to_id.iteritems())

关于python - Python 中三角距离矩阵的距离 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12398685/

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