我在关键字之间有一个很大的相似性,我希望将它转换为三角形距离矩阵(因为它非常大且稀疏甚至更好)使用scipy执行层次聚类。我当前的数据csv看起来像:
a, b, 1
b, a, 1
c, a, 2
a, c, 2
我不知道如何做到这一点,我在python中找不到任何简单的聚类教程。
感谢您的帮助!
答案 0 :(得分:3)
这个问题分为两部分:
如何将这种格式的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())