scipy 绘制Spearmanr相关性树状图时出现错误

flseospp  于 2022-11-10  发布在  其他
关注(0)|答案(2)|浏览(190)

在绘制spearmanr相关性的树状图时出错。下面是我使用的代码

corr = np.round(scipy.stats.spearmanr(full_data[list_of_continous]).correlation, 4)
corr_condensed = hc.distance.squareform(1-corr)
z = hc.linkage(corr_condensed, method='average')
fig = plt.figure(figsize=(20,20))
dendrogram = hc.dendrogram(z, labels=full_data[list_of_continous].columns, orientation='left', leaf_font_size=30)
plt.show()

下面是我得到的错误:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-10-9873c0be8dc7> in <module>()
      1 corr = np.round(scipy.stats.spearmanr(full_data[list_of_continous]).correlation, 4)
----> 2 corr_condensed = hc.distance.squareform(1-corr)
      3 z = hc.linkage(corr_condensed, method='average')
      4 fig = plt.figure(figsize=(20,20))
      5 dendrogram = hc.dendrogram(z, labels=full_data[list_of_continous].columns, orientation='left', leaf_font_size=30)

/usr/local/anaconda/lib/python3.6/site-packages/scipy/spatial/distance.py in squareform(X, force, checks)
   1844             raise ValueError('The matrix argument must be square.')
   1845         if checks:
-> 1846             is_valid_dm(X, throw=True, name='X')
   1847 
   1848         # One-side of the dimensions is set here.

/usr/local/anaconda/lib/python3.6/site-packages/scipy/spatial/distance.py in is_valid_dm(D, tol, throw, name, warning)
   1920                 if name:
   1921                     raise ValueError(('Distance matrix \'%s\' must be '
-> 1922                                      'symmetric.') % name)
   1923                 else:
   1924                     raise ValueError('Distance matrix must be symmetric.')

ValueError: Distance matrix 'X' must be symmetric.
s2j5cfk0

s2j5cfk01#

变量corr可能有nan个值,这些值可能会使其变形。
请尝试:

corr = np.nan_to_num(corr)

更新:
跳跃

corr_condensed = hc.distance.squareform(1-corr)

对我来说没有任何错误。
所以

corr = np.round(scipy.stats.spearmanr(full_data[list_of_continous]).correlation, 4)
z = hc.linkage(corr, method='average')
fig = plt.figure(figsize=(20,20))
dendrogram = hc.dendrogram(z, labels=full_data[list_of_continous].columns, orientation='left', leaf_font_size=30)
plt.show()

对你也一样。

s4chpxco

s4chpxco2#

如果您确定矩阵是对称的,请设置checks=False
corr_condensed = hc.distance.squareform(1-corr, checks=False)

相关问题