找出多個時間序列之間的關係

使用 Python 視覺化時間序列資料

Thomas Vincent

Head of Data Science, Getty Images

兩變數之相關

  • 在統計學中,相關係數用來衡量兩個變數之間關係的強度或是否無關:
    • 若關係被認為是線性,可用 Pearson 係數計算相關係數
    • 若關係被認為是非線性,可用 Kendall Tau 或 Spearman 等級相關計算相關係數
使用 Python 視覺化時間序列資料

計算相關係數

from scipy.stats.stats import pearsonr
from scipy.stats.stats import spearmanr
from scipy.stats.stats import kendalltau
x = [1, 2, 4, 7]
y = [1, 3, 4, 8]
pearsonr(x, y)
SpearmanrResult(correlation=0.9843, pvalue=0.01569)
spearmanr(x, y)
SpearmanrResult(correlation=1.0, pvalue=0.0)
kendalltau(x, y)
KendalltauResult(correlation=1.0, pvalue=0.0415)
使用 Python 視覺化時間序列資料

什麼是相關矩陣?

  • 當計算超過兩個變數的相關係數時,會得到一個相關矩陣
    • 範圍:[-1, 1]
    • 0:無關係
    • 1:強正相關
    • -1:強負相關
使用 Python 視覺化時間序列資料

什麼是相關矩陣?

  • 相關矩陣一定是「對稱」的
  • 對角線的值永遠為 1
   x     y     z
x  1.00 -0.46  0.49
y -0.46  1.00 -0.61
z  0.49 -0.61  1.00
使用 Python 視覺化時間序列資料

用 Pandas 計算相關矩陣

corr_p = meat[['beef', 'veal','turkey']].corr(method='pearson')
print(corr_p)
          beef     veal     turkey
beef      1.000   -0.829    0.738
veal     -0.829    1.000   -0.768
turkey    0.738   -0.768    1.000
corr_s = meat[['beef', 'veal','turkey']].corr(method='spearman')
print(corr_s)
          beef     veal     turkey
beef      1.000   -0.812    0.778
veal     -0.812    1.000   -0.829
turkey    0.778   -0.829    1.000
使用 Python 視覺化時間序列資料

用 Pandas 計算相關矩陣

corr_mat = meat.corr(method='pearson')
使用 Python 視覺化時間序列資料

熱度圖(Heatmap)

import seaborn as sns

sns.heatmap(corr_mat)
使用 Python 視覺化時間序列資料

熱度圖(Heatmap)

相關矩陣的熱度圖

使用 Python 視覺化時間序列資料

叢集圖(Clustermap)

sns.clustermap(corr_mat)
使用 Python 視覺化時間序列資料

相關矩陣的叢集圖

使用 Python 視覺化時間序列資料

一起來練習吧!

使用 Python 視覺化時間序列資料

Preparing Video For Download...