欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解Python進(jìn)行數(shù)據(jù)相關(guān)性分析的三種方式

 更新時間:2022年04月15日 11:19:04   作者:Mr數(shù)據(jù)楊  
相關(guān)系數(shù)量化數(shù)據(jù)集的變量或特征之間的關(guān)聯(lián)。這些統(tǒng)計數(shù)據(jù)對科學(xué)和技術(shù)非常重要,Python?有很好的工具可以用來計算它們。SciPy、NumPy?和Pandas相關(guān)方法以及數(shù)據(jù)可視化功能,感興趣的可以了解一下

相關(guān)性實現(xiàn)

統(tǒng)計和數(shù)據(jù)科學(xué)通常關(guān)注數(shù)據(jù)集的兩個或多個變量(或特征)之間的關(guān)系。數(shù)據(jù)集中的每個數(shù)據(jù)點都是一個觀察值,特征是這些觀察值的屬性或?qū)傩浴?/p>

這里主要介紹下面3種相關(guān)性的計算方式:

  • Pearson’s r
  • Spearman’s rho
  • Kendall’s tau

NumPy 相關(guān)性計算

np.corrcoef() 返回 Pearson 相關(guān)系數(shù)矩陣。

import numpy as np
x = np.arange(10, 20)
x
array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19])

y = np.array([2, 1, 4, 5, 8, 12, 18, 25, 96, 48])
y
array([ 2,  1,  4,  5,  8, 12, 18, 25, 96, 48])

r = np.corrcoef(x, y)
r
array([[1.        , 0.75864029],
       [0.75864029, 1.        ]])

SciPy 相關(guān)性計算

import numpy as np
import scipy.stats
x = np.arange(10, 20)
y = np.array([2, 1, 4, 5, 8, 12, 18, 25, 96, 48])

scipy.stats.pearsonr(x, y)    # Pearson's r
(0.7586402890911869, 0.010964341301680832)

scipy.stats.spearmanr(x, y)   # Spearman's rho
SpearmanrResult(correlation=0.9757575757575757, pvalue=1.4675461874042197e-06)

scipy.stats.kendalltau(x, y)  # Kendall's tau
KendalltauResult(correlation=0.911111111111111, pvalue=2.9761904761904762e-05)

在檢驗假設(shè)時,您可以在統(tǒng)計方法中使用p 值。p 值是一項重要的衡量標(biāo)準(zhǔn),需要深入了解概率和統(tǒng)計數(shù)據(jù)才能進(jìn)行解釋。

scipy.stats.pearsonr(x, y)[0]    # Pearson's r
0.7586402890911869
scipy.stats.spearmanr(x, y)[0]   # Spearman's rho
0.9757575757575757
scipy.stats.kendalltau(x, y)[0]  # Kendall's tau
0.911111111111111

Pandas 相關(guān)性計算

相對于來說計算比較簡單。

import pandas as pd
x = pd.Series(range(10, 20))
y = pd.Series([2, 1, 4, 5, 8, 12, 18, 25, 96, 48])

x.corr(y)                     # Pearson's r
0.7586402890911867
y.corr(x)
0.7586402890911869
x.corr(y, method='spearman')  # Spearman's rho
0.9757575757575757
x.corr(y, method='kendall')   # Kendall's tau
0.911111111111111

線性相關(guān)實現(xiàn)

線性相關(guān)性測量變量或數(shù)據(jù)集特征之間的數(shù)學(xué)關(guān)系與線性函數(shù)的接近程度。如果兩個特征之間的關(guān)系更接近某個線性函數(shù),那么它們的線性相關(guān)性更強(qiáng),相關(guān)系數(shù)的絕對值也更高。

線性回歸:SciPy 實現(xiàn)

線性回歸是尋找盡可能接近特征之間實際關(guān)系的線性函數(shù)的過程。換句話說,您確定最能描述特征之間關(guān)聯(lián)的線性函數(shù),這種線性函數(shù)也稱為回歸線。

import pandas as pd
x = pd.Series(range(10, 20))
y = pd.Series([2, 1, 4, 5, 8, 12, 18, 25, 96, 48])

使用scipy.stats.linregress()對兩個長度相同的數(shù)組執(zhí)行線性回歸。

result = scipy.stats.linregress(x, y)
scipy.stats.linregress(xy)
LinregressResult(slope=7.4363636363636365, intercept=-85.92727272727274, rvalue=0.7586402890911869, pvalue=0.010964341301680825, stderr=2.257878767543913)

result.slope # 回歸線的斜率
7.4363636363636365

result.intercept # 回歸線的截距
-85.92727272727274

result.rvalue # 相關(guān)系數(shù)
0.7586402890911869

result.pvalue #  p值
0.010964341301680825

result.stderr # 估計梯度的標(biāo)準(zhǔn)誤差
2.257878767543913

未來更多內(nèi)容參考機(jī)器學(xué)習(xí)專欄中的線性回歸內(nèi)容。

等級相關(guān)

比較與兩個變量或數(shù)據(jù)集特征相關(guān)的數(shù)據(jù)的排名或排序。如果排序相似則相關(guān)性強(qiáng)、正且高。但是如果順序接近反轉(zhuǎn),則相關(guān)性為強(qiáng)、負(fù)和低。換句話說等級相關(guān)性僅與值的順序有關(guān),而不與數(shù)據(jù)集中的特定值有關(guān)。

圖1和圖2顯示了較大的 x 值始終對應(yīng)于較大的 y 值的觀察結(jié)果,這是完美的正等級相關(guān)。圖3說明了相反的情況即完美的負(fù)等級相關(guān)。

排名:SciPy 實現(xiàn)

使用 scipy.stats.rankdata() 來確定數(shù)組中每個值的排名。

import numpy as np
import scipy.stats
x = np.arange(10, 20)
y = np.array([2, 1, 4, 5, 8, 12, 18, 25, 96, 48])
z = np.array([5, 3, 2, 1, 0, -2, -8, -11, -15, -16])

# 獲取排名序
scipy.stats.rankdata(x)  # 單調(diào)遞增
array([ 1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10.])
scipy.stats.rankdata(y)
array([ 2.,  1.,  3.,  4.,  5.,  6.,  7.,  8., 10.,  9.])
scipy.stats.rankdata(z) # 單調(diào)遞減
array([10.,  9.,  8.,  7.,  6.,  5.,  4.,  3.,  2.,  1.])

rankdata() 將nan值視為極大。

scipy.stats.rankdata([8, np.nan, 0, 2])
array([3., 4., 1., 2.])

等級相關(guān)性:NumPy 和 SciPy 實現(xiàn)

使用 scipy.stats.spearmanr() 計算 Spearman 相關(guān)系數(shù)。

result = scipy.stats.spearmanr(x, y)
result
SpearmanrResult(correlation=0.9757575757575757, pvalue=1.4675461874042197e-06)

result.correlation
0.9757575757575757

result.pvalue
1.4675461874042197e-06

rho, p = scipy.stats.spearmanr(x, y)
rho
0.9757575757575757

p
1.4675461874042197e-06

等級相關(guān)性:Pandas 實現(xiàn)

使用 Pandas 計算 Spearman 和 Kendall 相關(guān)系數(shù)。

import numpy as np
import scipy.stats
x = np.arange(10, 20)
y = np.array([2, 1, 4, 5, 8, 12, 18, 25, 96, 48])
z = np.array([5, 3, 2, 1, 0, -2, -8, -11, -15, -16])

x, y, z = pd.Series(x), pd.Series(y), pd.Series(z)
xy = pd.DataFrame({'x-values': x, 'y-values': y})
xyz = pd.DataFrame({'x-values': x, 'y-values': y, 'z-values': z})

計算 Spearman 的 rho,method=spearman。

x.corr(y, method='spearman')
0.9757575757575757

xy.corr(method='spearman')
          x-values  y-values
x-values  1.000000  0.975758
y-values  0.975758  1.000000

xyz.corr(method='spearman')
          x-values  y-values  z-values
x-values  1.000000  0.975758 -1.000000
y-values  0.975758  1.000000 -0.975758
z-values -1.000000 -0.975758  1.000000

xy.corrwith(z, method='spearman')
x-values   -1.000000
y-values   -0.975758
dtype: float64

計算 Kendall 的 tau, method=kendall。

x.corr(y, method='kendall')
0.911111111111111

xy.corr(method='kendall')
          x-values  y-values
x-values  1.000000  0.911111
y-values  0.911111  1.000000

xyz.corr(method='kendall')
          x-values  y-values  z-values
x-values  1.000000  0.911111 -1.000000
y-values  0.911111  1.000000 -0.911111
z-values -1.000000 -0.911111  1.000000

xy.corrwith(z, method='kendall')
x-values   -1.000000
y-values   -0.911111
dtype: float64

相關(guān)性的可視化

數(shù)據(jù)可視化在統(tǒng)計學(xué)和數(shù)據(jù)科學(xué)中非常重要??梢詭椭玫乩斫獾臄?shù)據(jù),并更好地了解特征之間的關(guān)系。

這里使用 matplotlib 來進(jìn)行數(shù)據(jù)可視化。

import matplotlib.pyplot as plt
plt.style.use('ggplot')

import numpy as np
import scipy.stats
x = np.arange(10, 20)
y = np.array([2, 1, 4, 5, 8, 12, 18, 25, 96, 48])
z = np.array([5, 3, 2, 1, 0, -2, -8, -11, -15, -16])
xyz = np.array([[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
                [2, 1, 4, 5, 8, 12, 18, 25, 96, 48],
                [5, 3, 2, 1, 0, -2, -8, -11, -15, -16]])

帶有回歸線的 XY 圖

使用 linregress() 獲得回歸線的斜率和截距,以及相關(guān)系數(shù)。

slope, intercept, r, p, stderr = scipy.stats.linregress(x, y)

構(gòu)建線性回歸公式。

line = f' y={intercept:.2f}+{slope:.2f}x, r={r:.2f}'
line
'y=-85.93+7.44x, r=0.76'

.plot() 繪圖

fig, ax = plt.subplots()
ax.plot(x, y, linewidth=0, marker='s', label='Data points')
ax.plot(x, intercept + slope * x, label=line)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.legend(facecolor='white')
plt.show()

相關(guān)矩陣的熱圖 matplotlib

處理特征較多的相關(guān)矩陣用熱圖方式比較理想。

corr_matrix = np.corrcoef(xyz).round(decimals=2)
corr_matrix
array([[ 1.  ,  0.76, -0.97],
       [ 0.76,  1.  , -0.83],
       [-0.97, -0.83,  1.  ]])

其中為了表示方便將相關(guān)的數(shù)據(jù)四舍五入后用 .imshow() 繪制。

fig, ax = plt.subplots()
im = ax.imshow(corr_matrix)
im.set_clim(-1, 1)
ax.grid(False)
ax.xaxis.set(ticks=(0, 1, 2), ticklabels=('x', 'y', 'z'))
ax.yaxis.set(ticks=(0, 1, 2), ticklabels=('x', 'y', 'z'))
ax.set_ylim(2.5, -0.5)
for i in range(3):
    for j in range(3):
        ax.text(j, i, corr_matrix[i, j], ha='center', va='center',
                color='r')
cbar = ax.figure.colorbar(im, ax=ax, format='% .2f')
plt.show()

相關(guān)矩陣的熱圖 seaborn

import seaborn as sns

plt.figure(figsize=(11, 9),dpi=100)
sns.heatmap(data=corr_matrix,
? ? ? ? ? ? annot_kws={'size':8,'weight':'normal', 'color':'#253D24'},#數(shù)字屬性設(shè)置,例如字號、磅值、顏色 ? ? ? ?
? ? ? ? ? ?)

以上就是詳解Python進(jìn)行數(shù)據(jù)相關(guān)性分析的三種方式的詳細(xì)內(nèi)容,更多關(guān)于Python數(shù)據(jù)相關(guān)性分析的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • 在Python的web框架中中編寫日志列表的教程

    在Python的web框架中中編寫日志列表的教程

    這篇文章主要介紹了在Python中編寫日志列表的教程,示例代碼基于Python2.x版本,需要的朋友可以參考下
    2015-04-04
  • Python-OpenCV中的cv2.inpaint()函數(shù)的使用

    Python-OpenCV中的cv2.inpaint()函數(shù)的使用

    大多數(shù)人會在家里放一些舊的退化照片,上面有一些黑點,一些筆畫等。你有沒有想過恢復(fù)它?本文就來介紹一下方法,感興趣的可以了解一下
    2021-06-06
  • 詳解python中return和print的區(qū)別和用途

    詳解python中return和print的區(qū)別和用途

    在 Python 中,return 和 print 是兩種常見的語句,用于在函數(shù)中輸出信息或返回值,盡管它們看起來相似,但它們有不同的作用和用法,本文將詳細(xì)介紹 return 和 print 在函數(shù)中的區(qū)別,并提供豐富的示例代碼,以幫助你更好地理解它們的用途
    2023-11-11
  • pandas添加新列的5種常見方法

    pandas添加新列的5種常見方法

    pandas為DataFrame格式數(shù)據(jù)添加新列的方法非常簡單,下面這篇文章主要給大家介紹了關(guān)于pandas添加新列的5種常見方法,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2022-06-06
  • python打印文件的前幾行或最后幾行教程

    python打印文件的前幾行或最后幾行教程

    今天小編就為大家分享一篇python打印文件的前幾行或最后幾行教程,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-02-02
  • Python實現(xiàn)為PDF大文件批量去除水印

    Python實現(xiàn)為PDF大文件批量去除水印

    在閱讀過程中如果遇到一些帶有水印的資料是比較煩心的,而市面上去水印的功能有多要收費且很不方便,那么,如何通過Python來對這類圖片水印進(jìn)行去除呢,本文就來和大家分享一下實現(xiàn)方法吧
    2023-05-05
  • Python自動化測試selenium指定截圖文件名方法

    Python自動化測試selenium指定截圖文件名方法

    這篇文章主要介紹了Python自動化測試selenium指定截圖文件名方法,Selenium?支持?Web?瀏覽器的自動化,它提供一套測試函數(shù),用于支持?Web?自動化測試,下文基于python實現(xiàn)指定截圖文件名方法,需要的小伙伴可以參考一下
    2022-05-05
  • 最新評論