Sin*_*iny 5 python cluster-analysis scipy linkage correlation
我有一个相关系数矩阵(n * n)。如何使用相关系数矩阵进行聚类?
我可以在SciPy中使用链接和群集功能吗?
链接函数需要n * m
矩阵(根据教程),但是我想使用n * n矩阵。
我的代码是
corre = mp_N.corr() # mp_N is raw data (m*n matrix)
Z = linkage(corre, method='average') # 'corre' is correlation coefficient matrix
fcluster(Z,2,'distance')
Run Code Online (Sandbox Code Playgroud)
这个代码正确吗?如果此代码错误,如何使用相关系数矩阵进行聚类?
小智 5
使用相关矩阵对数据进行聚类是一个合理的想法,但是必须先对相关进行预处理。首先,由所返回的相关矩阵numpy.corrcoef
受到机器算术误差的影响:
可以通过对转置取平均值,并用1填充对角线来固定它们:
import numpy as np
data = np.random.randint(0, 10, size=(20, 10)) # 20 variables with 10 observations each
corr = np.corrcoef(data) # 20 by 20 correlation matrix
corr = (corr + corr.T)/2 # made symmetric
np.fill_diagonal(corr, 1) # put 1 on the diagonal
Run Code Online (Sandbox Code Playgroud)
其次,任何聚类方法(例如)的输入都linkage
需要测量对象的不相似性。相关性度量相似性。因此,需要以一种方式进行转换,以便将0个相关性映射到一个大数,而将1个相关性映射到0个。
这篇博客文章讨论了这种数据转换的几种方法,并提出了建议dissimilarity = 1 - abs(correlation)
。这个想法是,强烈的负相关性也表明对象是相关的,就像正相关性一样。这是示例的继续:
from scipy.cluster.hierarchy import linkage, fcluster
from scipy.spatial.distance import squareform
dissimilarity = 1 - np.abs(corr)
hierarchy = linkage(squareform(dissimilarity), method='average')
labels = fcluster(hierarchy, 0.5, criterion='distance')
Run Code Online (Sandbox Code Playgroud)
请注意,我们没有将完整的距离矩阵输入linkage
,需要先对其进行压缩squareform
。
使用哪种确切的聚类方法以及什么阈值取决于问题的背景,没有通用的规则。通常,0.5是用于关联的合理阈值,因此我做到了。使用20组随机数,我得到了7个簇:编码labels
为
[7, 7, 7, 1, 4, 4, 2, 7, 5, 7, 2, 5, 6, 3, 6, 1, 5, 1, 4, 2]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3067 次 |
最近记录: |