Python中三角形距离矩阵的距离CSV

Python中三角形距离矩阵的距离CSV,python,matrix,bigdata,hierarchical-clustering,Python,Matrix,Bigdata,Hierarchical Clustering,我在关键字之间有大量相似之处,我想将其转换为三角形距离矩阵(因为它非常大,稀疏性更好),以便使用scipy执行分层聚类。我当前的csv数据如下所示: a, b, 1 b, a, 1 c, a, 2 a, c, 2 我不知道如何做到这一点,也找不到任何简单的python集群教程 谢谢你的帮助 这个问题有两个部分: 如何将这种格式的CSV中的距离加载到(可能是稀疏的)三角形距离矩阵中 给定一个三角形距离矩阵,如何使用scipy进行分层聚类 如何加载数据:我认为稀疏数据不起作用,所以让我

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

a,  b, 1
b,  a, 1
c,  a, 2
a,  c, 2
我不知道如何做到这一点,也找不到任何简单的python集群教程


谢谢你的帮助

这个问题有两个部分:

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

  • 给定一个三角形距离矩阵,如何使用scipy进行分层聚类

如何加载数据:我认为稀疏数据不起作用,所以让我们进行密集加载。我还将把它转换成完整的正方形矩阵,然后取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)]

谢谢我的数据非常大(大约50000个关键字/对象)因此,出于记忆原因,我希望制作一个下三角矩阵。现在我想知道,在压缩距离的情况下,如何从ward clustering中获得集群分配。你认为我可以将稀疏距离矩阵转换为压缩距离矩阵吗?我已经发布了一个相关问题,如果你认为它相关,我会有兴趣听听您的意见:我有大约120000个对象,我想知道是否有可能在python中创建一个距离对象来集群。
id_to_name = dict((id, name) for name, id in name_to_id.iteritems())