关于人工智能:在Python中创建相关系数矩阵的6种方法

6次阅读

共计 3663 个字符,预计需要花费 10 分钟才能阅读完成。

相关系数矩阵(Correlation matrix)是数据分析的根本工具。它们让咱们理解不同的变量是如何互相关联的。在 Python 中,有很多个办法能够计算相关系数矩阵,明天咱们来对这些办法进行一个总结

Pandas

Pandas 的 DataFrame 对象能够应用 corr 办法间接创立相关矩阵。因为数据迷信畛域的大多数人都在应用 Pandas 来获取数据,因而这通常是检查数据相关性的最快、最简略的办法之一。

 import pandas as pd
 import seaborn as sns
 
 data = sns.load_dataset('mpg')
 correlation_matrix = data.corr(numeric_only=True)
 correlation_matrix

如果你是统计和剖析相干工作的,你可能会问 ” p 值在哪里?”,在最初咱们会有介绍

Numpy

Numpy 也蕴含了相关系数矩阵的计算函数,咱们能够间接调用,然而因为返回的是 ndarray,所以看起来没有 pandas 那么清晰。

 import numpy as np
 from sklearn.datasets import load_iris
 
 iris = load_iris()
 np.corrcoef(iris["data"])

为了更好的可视化,咱们能够间接将其传递给 sns.heatmap()函数。

 import seaborn as sns
 
 data = sns.load_dataset('mpg')
 correlation_matrix = data.corr()
 
 sns.heatmap(data.corr(), 
             annot=True, 
             cmap='coolwarm')

annot=True 这个参数能够输入一些额定的有用信息。一个常见 hack 是应用 sns.set_context(‘talk’)来取得额定的可读输入。

这个设置是为了生成幻灯片演示的图像,它能帮忙咱们更好地浏览(更大的字体)。

Statsmodels

Statsmodels 这个统计分析库也是必定能够的

 import statsmodels.api as sm
 
 correlation_matrix = sm.graphics.plot_corr(data.corr(), 
     xnames=data.columns.tolist())

plotly

默认状况下 plotly 这个后果是如何从左下到右上运行对角线 1.0 的。这种行为与大多数其余工具相同,所以如果你应用 plotly 须要特地留神

 import plotly.offline as pyo
 pyo.init_notebook_mode(connected=True)
 
 import plotly.figure_factory as ff
 
 correlation_matrix = data.corr()
 
 fig = ff.create_annotated_heatmap(
     z=correlation_matrix.values, 
     x=list(correlation_matrix.columns), 
     y=list(correlation_matrix.index), 
     colorscale='Blues')
 
 fig.show()

Pandas + Matplotlib 更好的可视化

这个后果也能够间接应用用 sns.pairplot(data),两种办法产生的图差不多,然而 seaborn 只须要一句话

 sns.pairplot(df[['mpg','weight','horsepower','acceleration']])

所以咱们这里介绍如何应用 Matplotlib 来实现

 import matplotlib.pyplot as plt
 
 pd.plotting.scatter_matrix(
     data, alpha=0.2, 
     figsize=(6, 6), 
     diagonal='hist')
 
 plt.show()

相关性的 p 值

如果你正在寻找一个简略的矩阵 (带有 p 值),这是许多其余工具(SPSS, Stata, R, SAS 等) 默认做的,那如何在 Python 中取得呢?

这里就要借助科学计算的 scipy 库了,以下是实现的函数

 from scipy.stats import pearsonr
 import pandas as pd
 import seaborn as sns
 
 def corr_full(df, numeric_only=True, rows=['corr', 'p-value', 'obs']):
     """
     Generates a correlation matrix with correlation coefficients, 
     p-values, and observation count.
     
     Args:
     - df:                  Input dataframe
     - numeric_only (bool): Whether to consider only numeric columns for 
                            correlation. Default is True.
     - rows:                Determines the information to show. 
                            Default is ['corr', 'p-value', 'obs'].
     
     Returns:
     - formatted_table: The correlation matrix with the specified rows.
     """
     
     # Calculate Pearson correlation coefficients
     corr_matrix = df.corr(numeric_only=numeric_only)
     
     # Calculate the p-values using scipy's pearsonr
     pvalue_matrix = df.corr(
         numeric_only=numeric_only, 
         method=lambda x, y: pearsonr(x, y)[1])
     
     # Calculate the non-null observation count for each column
     obs_count = df.apply(lambda x: x.notnull().sum())
     
     # Calculate observation count for each pair of columns
     obs_matrix = pd.DataFrame(index=corr_matrix.columns, columns=corr_matrix.columns)
     for col1 in obs_count.index:
         for col2 in obs_count.index:
             obs_matrix.loc[col1, col2] = min(obs_count[col1], obs_count[col2])
         
     # Create a multi-index dataframe to store the formatted correlations
     formatted_table = pd.DataFrame(index=pd.MultiIndex.from_product([corr_matrix.columns, rows]), 
         columns=corr_matrix.columns
     )
     
     # Assign values to the appropriate cells in the formatted table
     for col1 in corr_matrix.columns:
         for col2 in corr_matrix.columns:
             if 'corr' in rows:
                 formatted_table.loc[(col1, 'corr'), col2] = corr_matrix.loc[col1, col2]
             
             if 'p-value' in rows:
                 # Avoid p-values for diagonal they correlate perfectly
                 if col1 != col2:
                     formatted_table.loc[(col1, 'p-value'), col2] = f"({pvalue_matrix.loc[col1, col2]:.4f})"
             if 'obs' in rows:
                 formatted_table.loc[(col1, 'obs'), col2] = obs_matrix.loc[col1, col2]
     
     return(formatted_table.fillna('')
            .style.set_properties(**{'text-align': 'center'}))

间接调用这个函数,咱们返回的后果如下:

 df = sns.load_dataset('mpg')
 result = corr_full(df, rows=['corr', 'p-value'])
 result

总结

咱们介绍了 Python 创立相关系数矩阵的各种办法,这些办法能够随便抉择(那个不便用哪个)。Python 中大多数工具的规范默认输入将不包含 p 值或察看计数,所以如果你须要这方面的统计,能够应用咱们子厚提供的函数,因为要进行全面和残缺的相关性剖析,有 p 值和察看计数作为参考是十分有帮忙的。

https://avoid.overfit.cn/post/836b5590a96045faae2774bb3f23c9ef

正文完
 0