Python - 線性回歸(Linear Regression) 的 Python 實現


背景

學習 Linear Regression in Python – Real Python,前面幾篇文章分別講了“regression怎么理解“,”線性回歸怎么理解“,現在該是實現的時候了。

線性回歸的 Python 實現:基本思路

  • 導入 Python 包: 有哪些包推薦呢?
  • 准備數據
  • 建模擬合
  • 驗證模型的擬合度
  • 預測:用模型來預測新的數據

實現細節

以最簡單的線性回歸為例,代碼參考的是原文。

重點是掌握基本思路,以及關鍵的幾個函數。影響擬合度的因素很多,數據源首當其沖,模型的選擇也是關鍵,這些在實際應用中具體討論,這里就簡單的對應前面的基本思路將 sample 代碼及運行結果貼一下,稍加解釋。

安裝並導入包

根據自己的需要導入

pip install scikit-learn
pip install numpy
pip install statsmodels

from sklearn.preprocessing import PolynomialFeatures
import numpy as np
from sklearn.linear_model import LinearRegression
import statsmodels.api as sm

准備數據

""" prepare data
x: regressor
y: predictor
reshape: make it two dimentional - one column and many rows
y can also be 2 dimensional
"""

x = np.array([5, 15, 25, 35, 45, 55]).reshape((-1, 1))
"""
[[ 5]
 [15]
 [25]
 [35]
 [45]
 [55]] 
"""
y = np.array([5, 20, 14, 32, 22, 38])
print(x, y)
# [ 5 20 14 32 22 38]

建模

'''create a model and fit it'''
model = LinearRegression()
model = model.fit(x, y)
print(model)
# LinearRegression(copy_X=True, fit_intercept=True, n_jobs=None, normalize=False)

驗證模型的擬合度

'''get result
y = b0 + b1x
'''
r_sq = model.score(x, y)
print('coefficient of determination(𝑅²) :', r_sq)
# coefficient of determination(𝑅²) : 0.715875613747954
print('intercept:', model.intercept_)
# (標量) 系數b0 intercept: 5.633333333333329 -------this will be an array when y is also 2-dimensional
print('slope:', model.coef_)
# (數組)斜率b1 slope: [0.54]        ---------this will be 2-d array when y is also 2-dimensional

預測

'''predict response
given x, get y from the model y = b0+b1x
'''
y_pred = model.predict(x)
print('predicted response:', y_pred, sep='\n')
#predicted response:
#[8.33333333 13.73333333 19.13333333 24.53333333 29.93333333 35.33333333]

'''forecast'''
z = np.arange(5).reshape((-1, 1))
y = model.predict(z)
print(y)
#[5.63333333 6.17333333 6.71333333 7.25333333 7.79333333]

問題

Reference

Changelog

  • 2020-01-14 init

本文由博客一文多發平台 OpenWrite 發布!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM