2.1.11.2.Linear regression with Python
1. 匯入基本的library
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns將圖表直接嵌入到Notebook之中
%matplotlib inline2.讀取資料並了解資料
讀取資料
df = pd.read_csv('USA_Housing.csv')可以確認前幾筆資料的內容長怎樣, 例如確認前10筆
df.head(10)了解資料欄位的型別以及變數的型態
df.info()取得資料的基本統計數值: 如數量, 平均值, 標準差, 四分位數等數值
df.describe()取得df中的欄位名稱
df.columns output: Index(['Avg. Area Income', 'Avg. Area House Age', 'Avg. Area Number of Rooms', 'Avg. Area Number of Bedrooms', 'Area Population', 'Price', 'Address'], dtype='object')
3.繪製圖表分析資料
利用seaborn繪製多變量圖(pairplot), 多變量圖的輸入資料可以用sns.load_dataset()讀入資料, 也可以用pd.read_csv所讀入的資料

其中df.corr()會拿資料中的數值欄位來形成相關係數矩陣

5. 使用Skikit-learn library
Skikit-learn model的使用方式都是用from sklearn.family import model的形式
首先介紹train_test_split, 這個函式可以隨機劃分訓練集和測試集
舉例來說, 如果我們想用每天的氣溫資料預測飲料的銷售業績, 則可以把X帶入每天的氣溫資料, Y帶入飲料的銷售業績資料
建立複回歸模型
在這個例子中, 我們希望做的事情是用Avg. Area Income (平均區域所得), Avg. Area House Age (平均屋齡), Avg. Area Number of Rooms (平均房間數), Avg. Area Number of Bedrooms (平均臥房數), Area Population (區域人數)來預估Price (房價), 回歸模型中若有多個變量參與則稱為複回歸模型
建立線性回歸模型
6. 利用Skikit-learn進行預測
用測試集資料進行預測
繪圖來看看預測值與測試集的一致性
散布圖

直方圖

評估線性回歸模型品質的指標 (Regression Evaluation Metrics) 1. Mean Absolute Error (MAE): 即為平均誤差
2. Mean Square Error (MSE): 平均平方誤差
3. Root Mean Square Error (RMSE) 
Last updated
Was this helpful?
