gpt4 book ai didi

python - 使用 Python 编写具有 p 值的 Seaborn 相关矩阵

转载 作者:行者123 更新时间:2023-12-04 01:41:23 24 4
gpt4 key购买 nike

我有一个在 seaborn 中生成的对角线相关矩阵。我想屏蔽掉 p 值大于 0.05 的那些。

这是我所拥有的
https://imgur.com/ljwj0U2

sns.set(style="white")
corr = result.corr()
print corr

mask = np.zeros_like(corr, dtype=np.bool)
mask[np.triu_indices_from(mask)] = True
f, ax = plt.subplots(figsize=(11, 9))
sns_plot = sns.heatmap(result.corr(),mask=mask, annot=True, center=0, square=True, fmt=".1f", linewidths=.5, cmap="Greens")


将不胜感激任何帮助。
非常感谢

最佳答案

为了完整起见,这里有一个使用 scipy.stats.pearsonr 的解决方案。 ( docs ) 创建 p 值矩阵。在创建一个 bool 掩码以传递给 seaborn(或另外结合 numpy np.triu 以隐藏相关性的上三角)

def corr_sig(df=None):
p_matrix = np.zeros(shape=(df.shape[1],df.shape[1]))
for col in df.columns:
for col2 in df.drop(col,axis=1).columns:
_ , p = stats.pearsonr(df[col],df[col2])
p_matrix[df.columns.to_list().index(col),df.columns.to_list().index(col2)] = p
return p_matrix

p_values = corr_sig(df)
mask = np.invert(np.tril(p_values<0.05))
# note seaborn will hide correlation were the boolean value is True in the mask



带示例的完整流程

首先创建一些样本数据(3 个相关变量;3 个不相关变量):
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from scipy import stats

# Simulate 3 correlated variables
num_samples = 100
mu = np.array([5.0, 0.0, 10.0])
# The desired covariance matrix.
r = np.array([
[ 3.40, -2.75, -2.00],
[ -2.75, 5.50, 1.50],
[ -2.00, 1.50, 1.25]
])
y = np.random.multivariate_normal(mu, r, size=num_samples)
df = pd.DataFrame(y)
df.columns = ["Correlated1","Correlated2","Correlated3"]

# Create two random variables
for i in range(2):
df.loc[:,f"Uncorrelated{i}"] = np.random.randint(-2000,2000,len(df))

# To make sure that they are uncorrelated - add also a nearly invariant variables
df.loc[:,"Near Invariant"] = np.random.randint(-99,-95,num_samples)

方便的绘图功能主要用于热图的化妆品。
def plot_cor_matrix(corr, mask=None):
f, ax = plt.subplots(figsize=(11, 9))
sns.heatmap(corr, ax=ax,
mask=mask,
# cosmetics
annot=True, vmin=-1, vmax=1, center=0,
cmap='coolwarm', linewidths=2, linecolor='black', cbar_kws={'orientation': 'horizontal'})

Corr.-具有所有相关性的示例数据图 为了让您了解相关性在此示例性相关矩阵中的外观,而无需过滤显着相关性(p 值 < .05)。
# Plotting without significance filtering
corr = df.corr()
mask = np.triu(corr)
plot_cor_matrix(corr,mask)
plt.show()

enter image description here

仅具有 Sig 的示例数据的 Corr.Plot。相关性
最后只绘制显着的 p 值相关性 (alpha < .05)
# Plotting with significance filter
corr = df.corr() # get correlation
p_values = corr_sig(df) # get p-Value
mask = np.invert(np.tril(p_values<0.05)) # mask - only get significant corr
plot_cor_matrix(corr,mask)

enter image description here

结论

虽然在第一个相关矩阵中有一些相关系数 ( r ) > .05(按照 OP 的评论中建议的过滤),但这并不意味着 p 值是显着的。因此,区分 p 很重要。来自相关系数的值 r .

我希望这个答案将来对其他搜索一种绘制与 sns.heatmap 显着相关性的方法有所帮助。

关于python - 使用 Python 编写具有 p 值的 Seaborn 相关矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57226054/

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