image.png
配置環境
# 選擇 Python 2 版本
conda create -n python2 python=2
# 安裝 pandas, matplotlib, scikit-learn
conda install pandas matplotlib scikit-learn
Linear Regression:根據動物的大腦重量來預測對應體重
import pandas as pd
from sklearn import linear_model
import matplotlib.pyplot as plt
# Read data
dataframe = pd.read_fwf('brain_body.txt')
x_values = dataframe[['Brain']]
y_values = dataframe[['Body']]
# Train model on data
body_reg = linear_model.LinearRegression()
body_reg.fit(x_values, y_values)
# Visualize results
plt.scatter(x_values, y_values)
plt.plot(x_values, body_reg.predict(x_values))
plt.show()
Breaking it Down
Machine Learing - Defining the outcome & letting our algorithm learn the steps to get there
3 Learning styles - supervised, unsupervised & reinforcement learning
Linear Regression models relationship between independent & dependent variables via line of best fit
線性回歸練習:各國男性人口的 BMI 與該國人口平均壽命的回歸
其中 "Country" 列記錄出生國家,"Life expectancy" 列記錄該國平均壽命,"BMI" 列記錄該國男性 BMI 數據。你將使用 BMI 數據來預測平均壽命。
# Import statements
import pandas as pd
from sklearn.linear_model import LinearRegression
# Load the data
bmi_life_data = pd.read_csv("bmi_and_life_expectancy.csv")
# Make and fit the linear regression model
bmi_life_model = LinearRegression()
bmi_life_model.fit(bmi_life_data[['BMI']], bmi_life_data[['Life expectancy']])
# Mak a prediction using the model
laos_life_exp = bmi_life_model.predict(21.07931)
線性回歸注意事項
最適用于線性數據
線性回歸會根據訓練數據生成直線模型。如果訓練數據包含非線性關系,你需要選擇:調整數據(進行數據轉換)、增加特征數量(參考下節內容)或改用其他模型。
image.png
容易受到異常值影響
線性回歸的目標是求取對訓練數據而言的 “最優擬合” 直線。如果數據集中存在不符合總體規律的異常值,最終結果將會存在不小偏差。
image.png
多元線性回歸
使用到波士頓房價數據集。數據集中包含 506 棟房屋的 13 個特征與房價中值(單位為 1000 美元)。你將根據這 13 個特征擬合模型,并預測房價。
from sklearn.linear_model import LinearRegression
from sklearn.datasets import load_boston
# Load the data from the the boston house-prices dataset
boston_data = load_boston()
x = boston_data['data']
y = boston_data['target']
# Make and fit the linear regression model
model = LinearRegression()
model.fit(x, y)
# Make a prediction using the model
sample_house = [[2.29690000e-01, 0.00000000e+00, 1.05900000e+01, 0.00000000e+00, 4.89000000e-01,
6.32600000e+00, 5.25000000e+01, 4.35490000e+00, 4.00000000e+00, 2.77000000e+02,
1.86000000e+01, 3.94870000e+02, 1.09700000e+01]]
prediction = model.predict(sample_house)