機器學習——簡單線性回歸(原理推導+算法描述+代碼實現)


實驗環境:Python 3.6

編輯器:Jupyter Notebook 6.0.1

實驗要求:可以調用numpy、pandas基礎拓展程序包,不可以調用sklearn機器學

 

 

——————————————————我是分割線喵————————————————————

 ————————————(如果想要代碼可以直接下拉到最后)————————————

 

線性模型的一般形式:

  

 

向量形式:

  

 

線性模型的優點:

  1、形式簡單、易於建模

  2、可解釋性

  3、是非線性模型的基礎,可以在線性模型的基礎上引入層級結構或高維映射

 

舉個西瓜書里的例子:

  系數可以反應該屬性對該瓜是否是好瓜的影響因素大小

  

 

單一屬性的線性回歸目標:

  

 

參數/模型估計:最小二乘法

    

 

最小化均方誤差:

  

 

分別對ω和b求導,得:

  

 

 得到閉式解:

  

 

 

 ——————————————————我是分割線喵————————————————————

 

在jupyter notebook中的代碼實現:

    1、先用一個例子,模擬出點:    

  

 

 

    2、通過最小二乘法得到線性回歸,紅色標出:

 

 

 

 ——————————————————代碼———————————————————

 

二元的簡單線性回歸算法代碼,可以作為自定義包留着以后用,我在sublime里面寫的。

  (如何在jupyter中導入自定義包?)

 

 1 import numpy as np
 2 
 3 class SimpleLinearRegression1:
 4     def __init__(self):
 5         """初始化Simple Linear Regression 模型"""
 6         self.a_ = None
 7         self.b_ = None
 8         #a和b不是用戶送來的參數,是得出的結果
 9     #x_train和y_train只用來提供訓練,訓練得出所需參數之后,數據就沒用了
10 
11     def fit(self, x_train, y_train):
12         """根據訓練數據集x_train,y_train訓練Simple Linear Regression 模型"""
13         assert x_train.ndim == 1, \
14             "Simple Linear Regressor can only solve simple feature training data"
15         assert len(x_train) == len(y_train), \
16             "the size of x_train must be equal to the size of y_train"
17         #算法實現代碼
18         x_mean = np.mean(x_train)
19         y_mean = np.mean(y_train)
20 
21         num = 0.0
22         d = 0.0
23         for x, y in zip(x_train, y_train):
24             num += (x - x_mean) * (y - y_mean)
25             d += (x - x_mean) ** 2
26 
27         self.a_ = num / d
28         self.b_ = y_mean - self.a_ * x_mean
29 
30         return self
31     
32     def predict(self, x_predict):
33         """給定待預測數據集x_predict, 返回表示x_predict的結果向量"""
34         assert x_predict.ndim == 1, \
35             "Simple Linear Regressor can only solve single feature training data"
36         assert self.a_ is not None and self.b_ is not None, \
37             "must fit before predict"
38 
39         return np.array([self._predict(x) for x in x_predict])
40 
41     def _predict(self, x_single):
42         """給定單個待預測數據x_single, 返回x_single的預測結果值"""
43         return self.a_ * x_single + self.b_
44 
45     def __repr__(self):
46         return "SimpleLinearRegression1()"

 

 

接着在jupyter notebook測試一下剛剛寫好的算法:

(myMachineLearningCode是我自定義的文件夾,上面的代碼文件命名為SimpleLinearRegression.py)

 

  

 

這樣簡單的線性回歸算法就實現了,但是用for循環去得到最小二乘法的分子分母效率很低,可以改成使用向量法得到分子分母。

(機器學習——簡單線性回歸之向量法(代碼實現))

 


免責聲明!

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



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