兩個變數的故事

使用 Python 中的 statsmodels 進行回歸入門

Maarten Van den Broeck

Content Developer at DataCamp

瑞典車險資料

  • 每列代表瑞典的一個地理區域。
  • 共有 63 列。
n_claims total_payment_sek
108 392.5
19 46.2
13 15.7
124 422.2
40 119.4
... ...
使用 Python 中的 statsmodels 進行回歸入門

描述統計

import pandas as pd
print(swedish_motor_insurance.mean())
n_claims             22.904762
total_payment_sek    98.187302
dtype: float64
print(swedish_motor_insurance['n_claims'].corr(swedish_motor_insurance['total_payment_sek']))
0.9128782350234068
使用 Python 中的 statsmodels 進行回歸入門

什麼是迴歸?

  • 以統計模型探索應變數與解釋變數之間的關係。
  • 給定解釋變數的值後,你可以預測應變數的值。
n_claims total_payment_sek
108 3925
19 462
13 157
124 4222
40 1194
200 ???
使用 Python 中的 statsmodels 進行回歸入門

術語

應變數(又稱 dependent variable)

你想要預測的變數。

解釋變數(又稱 independent variables)

用來解釋應變數如何改變的變數。

使用 Python 中的 statsmodels 進行回歸入門

線性迴歸與邏輯斯迴歸

線性迴歸

  • 應變數是數值型。

邏輯斯迴歸

  • 應變數是布林型。

簡單線性/邏輯斯迴歸

  • 只有一個解釋變數。
使用 Python 中的 statsmodels 進行回歸入門

視覺化變數對

import matplotlib.pyplot as plt
import seaborn as sns

sns.scatterplot(x="n_claims",
                y="total_payment_sek",    
                data=swedish_motor_insurance)

plt.show()

總理賠金額對理賠件數的散佈圖。理賠件數越多,理賠金額越高。

使用 Python 中的 statsmodels 進行回歸入門

加入線性趨勢線

sns.regplot(x="n_claims",
            y="total_payment_sek",
            data=swedish_motor_insurance,
            ci=None)

與前述相同的散佈圖,加入以線性迴歸計算的趨勢線。對資料的擬合度不錯。

使用 Python 中的 statsmodels 進行回歸入門

課程流程

第 1 章

視覺化與擬合線性迴歸模型。

第 2 章

用線性迴歸模型做預測並理解模型係數。

第 3 章

評估線性迴歸模型的品質。

第 4 章

改用邏輯斯迴歸,流程相同。

使用 Python 中的 statsmodels 進行回歸入門

迴歸的 Python 套件

statsmodels

  • 以洞見為優先(本課程重點)

scikit-learn

  • 以預測為優先(其他 DataCamp 課程重點)
使用 Python 中的 statsmodels 進行回歸入門

一起來練習吧!

使用 Python 中的 statsmodels 進行回歸入門

Preparing Video For Download...