成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

在Python中創建相關系數矩陣的六種方法

大數據 數據分析
相關系數矩陣(Correlation matrix)是數據分析的基本工具。它們讓我們了解不同的變量是如何相互關聯的。在Python中,有很多個方法可以計算相關系數矩陣,今天我們來對這些方法進行一個總結

相關系數矩陣(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(cnotallow=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), 
    diagnotallow='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_notallow=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_notallow=numeric_only)
     
    # Calculate the p-values using scipy's pearsonr
    pvalue_matrix = df.corr(
        numeric_notallow=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值和觀察計數作為參考是非常有幫助的。


責任編輯:華軒 來源: DeepHub IMBA
相關推薦

2023-04-26 08:41:16

Git撤消更改

2010-10-08 11:13:22

MySQL修改密碼

2011-02-24 10:56:34

人才

2023-06-01 16:45:11

React開發JavaScript

2025-01-03 08:48:20

列表推導式Python編程

2023-08-15 15:44:55

React開發

2023-04-03 20:29:00

Linux環境變量

2023-09-06 08:00:00

ChatGPT數據分析

2025-01-02 08:21:32

2023-07-29 00:08:32

2024-11-05 08:28:50

2023-12-08 08:53:37

數據中心人工智能自動化

2021-12-06 06:58:50

List重復數據

2022-06-09 08:46:58

ITCIO職業

2022-06-10 10:25:07

CIOIT領導者職業生涯

2015-07-09 10:13:05

IT基礎設施支出數據中心

2023-05-15 18:32:20

2016-10-25 10:12:13

2010-04-02 15:36:37

Oracle約束

2022-02-21 22:47:36

首席信息官IT技術
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 午夜影院污| 国产精品视频一 | 亚洲 日本 欧美 中文幕 | 久久久性色精品国产免费观看 | 亚洲精品www久久久久久广东 | 日韩中文一区 | 亚洲视频一区 | 成人一级视频在线观看 | 五月综合久久 | 九九久久久久久 | 国产精品一区二区精品 | 成人不卡 | 久久综合狠狠综合久久综合88 | 91精品国产92 | 国产精品视频www | 欧美国产精品久久久 | 无码一区二区三区视频 | 欧美高清视频一区 | 久久国产激情视频 | 精品亚洲一区二区 | 99国产精品视频免费观看一公开 | 色婷婷综合久久久中字幕精品久久 | 久久精品久久精品久久精品 | 欧州一区二区 | 韩国精品一区二区三区 | 国产精品久久国产精品99 gif | 97伦理影院| 国精产品一区二区三区 | 国产成年人小视频 | 欧美国产视频 | 亚洲精品一区中文字幕乱码 | 欧美一区二区在线 | 中文字幕在线观看一区 | heyzo在线 | 国产视频欧美 | 久久专区 | 国产一区二区在线免费观看 | 久久久久国产一级毛片高清网站 | 天天久久 | 瑟瑟视频在线看 | 国产9久|