重写矩阵元素以反映Python中的列和行聚类

2024-06-06 23:27:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找一种方法来分别对矩阵行和列执行集群,重新排序矩阵中的数据以反映集群并将其组合在一起。聚类问题很容易解决,创建树状图也很容易(例如在this blog"Programming collective intelligence"中)。然而,如何对数据重新排序对我来说仍然不清楚。

最后,我正在寻找一种使用naive Python创建类似下图的图形的方法(使用任何“标准”库,如numpy、matplotlib等,但不使用using R或其他外部工具)。

dendogram
(来源:warwick.ac.uk

澄清

有人问我重新排序是什么意思。当您首先按矩阵行对矩阵中的数据进行聚类,然后按其列对数据进行聚类时,每个矩阵单元都可以通过在两个树状图中的位置进行标识。如果重新排列原始矩阵的行和列,使树状图中彼此接近的元素在矩阵中彼此接近,然后生成热图,则数据的群集可能对查看器变得明显(如上图所示)


Tags: 数据方法图形排序集群collective矩阵blog
3条回答

我知道这是很晚的游戏,但我做了一个绘图对象的基础上,从这一页的帖子代码。它是在pip上注册的,所以要安装你只需要调用

pip install pydendroheatmap

在这里查看项目的github页面:https://github.com/themantalope/pydendroheatmap

请参阅下面部分复制到this related question的myrecent answer

import scipy
import pylab
import scipy.cluster.hierarchy as sch

# Generate features and distance matrix.
x = scipy.rand(40)
D = scipy.zeros([40,40])
for i in range(40):
    for j in range(40):
        D[i,j] = abs(x[i] - x[j])

# Compute and plot dendrogram.
fig = pylab.figure()
axdendro = fig.add_axes([0.09,0.1,0.2,0.8])
Y = sch.linkage(D, method='centroid')
Z = sch.dendrogram(Y, orientation='right')
axdendro.set_xticks([])
axdendro.set_yticks([])

# Plot distance matrix.
axmatrix = fig.add_axes([0.3,0.1,0.6,0.8])
index = Z['leaves']
D = D[index,:]
D = D[:,index]
im = axmatrix.matshow(D, aspect='auto', origin='lower')
axmatrix.set_xticks([])
axmatrix.set_yticks([])

# Plot colorbar.
axcolor = fig.add_axes([0.91,0.1,0.02,0.8])
pylab.colorbar(im, cax=axcolor)

# Display and save figure.
fig.show()
fig.savefig('dendrogram.png')

Dendrogram and distance matrix
(来源:stevetjoa.com

我不完全明白,但你们似乎是在尝试基于各种树状图指标重新索引数组的每个轴。我想这是假设在每个分支的描述中都有一些比较逻辑。如果是这样的话,这样做行吗以下内容:

>>> x_idxs = [(0,1,0,0),(0,1,1,1),(0,1,1),(0,0,1),(1,1,1,1),(0,0,0,0)]
>>> y_idxs = [(1,1),(0,1),(1,0),(0,0)]
>>> a = np.random.random((len(x_idxs),len(y_idxs)))
>>> x_idxs2, xi = zip(*sorted(zip(x_idxs,range(len(x_idxs)))))
>>> y_idxs2, yi = zip(*sorted(zip(y_idxs,range(len(y_idxs)))))
>>> a2 = a[xi,:][:,yi]

x_idxsy_idxs是树状图的标记。a是未排序的矩阵。xiyi是新的行/列数组指示符。a2是分类矩阵,而x_idxs2y_idxs2是新的分类树状图指标。这假设在创建树状图时,0分支列/行总是相对大于/小于1分支。

如果您的yidx和xidx不是列表,而是numpy数组,那么您可以以类似的方式使用np.argsort

相关问题 更多 >