gpt4 book ai didi

python - 仅当另一个 n*n 的值具有特定值时才显示 n*n 矩阵的值 (Python)

转载 作者:行者123 更新时间:2023-12-01 03:38:05 26 4
gpt4 key购买 nike

所以我目前正在尝试计算我拥有的一些数据的 Pearson R 和 p 值。这是通过以下代码完成的:

import numpy as np
from scipy.stats import pearsonr, betai
from pandas import DataFrame
import seaborn as sns
import matplotlib.pyplot as plt

def corrcoef(matrix): #function that calculates the Pearson's R and p-value
r = np.corrcoef(matrix)
rf = r[np.triu_indices(r.shape[0], 1)]
df = matrix.shape[1] - 2
ts = rf * rf * (df / (1 - rf * rf))
pf = betai(0.5 * df, 0.5, df / (df + ts))
p = np.zeros(shape=r.shape)
p[np.triu_indices(p.shape[0], 1)] = pf
p[np.tril_indices(p.shape[0], -1)] = pf
p[np.diag_indices(p.shape[0])] = np.ones(p.shape[0])
return r, p

data = np.loadtxt('corr-data.txt') #data matrix loaded

sig_lvl = 0.05 #significance level

r_mat, p_mat = corrcoef(data) #use function on data and put the answers in two different matrices

df_rmat = DataFrame(r_mat, columns=Index, index=Index) #make data readable for the seaborn package
df_pmat = DataFrame(p_mat, columns=Index, index=Index)

r_mat[abs(r_mat) <= .90] = np.nan #if the R-value matrix elements are under 0.90, don't show them - make them NaN.
p_mat[abs(p_mat) >= sig_lvl] = np.nan #this is probably the issue.

mask_pmat = np.zeros_like(p_mat)
mask_pmat[np.tril_indices_from(mask_pmat)] = True #only showing the upper triangle of the values since it's symmetrical in the diagonal

sns.plt.subplot(1,2,2)
ax_pmat = sns.heatmap(np.around(df_pmat, decimals=2), annot=True, mask = mask_pmat) #subplot sequence for the p-value matrix only

sns.plt.show()

它可能不是最优化的代码,但到目前为止它可以按预期工作。使用seaborn包,如果不同值足够高(> = 0.95)或具有正确的显着性水平,并且只有上三角形,我会得到不同值的热度/颜色图。然而,我实际上想做的是仅显示第一个图中表示的那些 R 值的 p 值。小于 0.95 的值仅替换为 NaN,并且在热图中没有颜色。因此,如果表示 R 值矩阵中的值,则只应表示 p 值矩阵中的值。

这可以做到吗,或者……?

如果有任何不清楚的地方,请告诉我。然后我会尝试进一步解释。

提前致谢

最佳答案

我想你的意思是这样的:

p_mat[r_mat < 0.95] = np.nan

这是有效的,因为pr是相同的形状。它将进入您的代码而不是:

if r_mat[abs(r_mat) <= .90] == np.nan:
p_mat = np.nan

请注意,如果将 NaN 与某个值进行比较,结果始终为 false。

关于python - 仅当另一个 n*n 的值具有特定值时才显示 n*n 矩阵的值 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40093475/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com