相關係數的注意事項

Python 統計學入門

Maggie Matsui

Content Developer, DataCamp

非線性關係

具二次關係的變數散佈圖

$$r = 0.18$$

Python 統計學入門

非線性關係

我們看到的是:

具二次關係且含二次趨勢線的散佈圖

相關係數看到的是:

具二次關係但以線性趨勢線擬合的散佈圖

Python 統計學入門

相關係數只捕捉線性關係

別盲目使用相關係數

df['x'].corr(df['y'])
0.081094

一定要視覺化資料

具二次關係的變數散佈圖

Python 統計學入門

哺乳動物的睡眠資料

print(msleep)
                 name       genus   vore         order  ... sleep_cycle  awake  brainwt   bodywt
1             Cheetah    Acinonyx  carni     Carnivora  ...         NaN   11.9      NaN   50.000
2          Owl monkey       Aotus   omni      Primates  ...         NaN    7.0  0.01550    0.480
3     Mountain beaver  Aplodontia  herbi      Rodentia  ...         NaN    9.6      NaN    1.350
4 Greater short-ta...     Blarina   omni  Soricomorpha  ...    0.133333    9.1  0.00029    0.019
5                 Cow         Bos  herbi  Artiodactyla  ...    0.666667   20.0  0.42300  600.000
..                ...         ...    ...           ...  ...         ...    ...      ...      ...
79         Tree shrew      Tupaia   omni    Scandentia  ...    0.233333   15.1  0.00250    0.104
80 Bottle-nosed do...    Tursiops  carni       Cetacea  ...         NaN   18.8      NaN  173.330
81              Genet     Genetta  carni     Carnivora  ...         NaN   17.7  0.01750    2.000
82         Arctic fox      Vulpes  carni     Carnivora  ...         NaN   11.5  0.04450    3.380
83            Red fox      Vulpes  carni     Carnivora  ...    0.350000   14.2  0.05040    4.230
Python 統計學入門

體重 vs 清醒時間

體重與清醒時間的散佈圖

msleep['bodywt'].corr(msleep['awake'])
0.3119801
Python 統計學入門

體重的分佈

bodywt 變數的直方圖

Python 統計學入門

對數轉換

msleep['log_bodywt'] = np.log(msleep['bodywt'])

sns.lmplot(x='log_bodywt', y='awake', data=msleep, ci=None) plt.show()
msleep['log_bodywt'].corr(msleep['awake'])
0.5687943

log 體重與清醒時間的散佈圖

Python 統計學入門

其他轉換方式

  • 對數轉換(log(x)
  • 平方根轉換(sqrt(x)
  • 倒數轉換(1 / x

  • 也可組合,例如:

    • log(x)log(y)
    • sqrt(x)1 / y
Python 統計學入門

為何要做轉換?

  • 某些統計方法仰賴變數之間具線性關係
    • 相關係數
    • 線性迴歸

 

Introduction to Linear Modeling in Python

Python 統計學入門

相關不代表因果

                「xy 相關」不代表x 導致 y

美國人均人造奶油消費與緬因州離婚率的散佈圖。兩者高度相關,相關係數為 0.99

Python 統計學入門

混雜因子(Confounding)

  喝咖啡(x)指向肺癌(y)

Python 統計學入門

混雜因子(Confounding)

  喝咖啡(x)指向肺癌(y),上方有抽菸(混雜因子)

Python 統計學入門

混雜因子(Confounding)

  喝咖啡(x)指向肺癌(y),抽菸(混雜因子)與喝咖啡之間有雙向箭頭,標示「association」。

Python 統計學入門

混雜因子(Confounding)

  喝咖啡(x)指向肺癌(y),抽菸(混雜因子)與喝咖啡之間有雙向箭頭,標示「association」。抽菸指向肺癌,標示「causation」

Python 統計學入門

混雜因子(Confounding)

  喝咖啡(x)與肺癌(y)之間為雙向箭頭,標示「association」。抽菸與喝咖啡為雙向箭頭,標示「association」。抽菸指向肺癌,標示「causation」。

  假期(x)指向零售銷售(y)。特別優惠(混雜因子)與假期為雙向箭頭,且指向零售銷售。

Python 統計學入門

一起來練習吧!

Python 統計學入門

Preparing Video For Download...