線性回歸算法實現(Python)


線性回歸Python底層實現
一、實現目標
      1.了解最優線性回歸模型參數的解析解的求解過程
      2.幫助大家加深線性回歸模型的基本求解原理
      3.掌握通過一個簡單的工具包調用過程幫助大家掌握快速實現線性回歸模型的方法。

二、案例內容介紹
      線性回歸是極其學習中最基本的模型,用來擬合自變量和因變量之間呈現線性關系的數據,當自變量只有一個時我們稱使用的回歸模型是一元線性回歸模型,
當自變量有多個時稱使用的回歸模型是多元線性回歸模型。根據已知數據,求解線性回歸模型的參數最常用到的方法是最小二乘法,求解使得損失函數取得最小值的模型參數的解  析解或者使用梯度下降算法求得最優的模型參數。

 

三、理論熟悉網址:

一元線性回歸原理及python簡單實現

參考網址:https://blog.csdn.net/u011208984/article/details/107645460


四、實驗步驟
      數據集說明:本本實驗使用的是構造的數據集,數據構造的過程在代碼中有明確顯示。

 

---------------------------------------------------------------------------------------------------------------------

1、一元線性回歸Python底層實現

 

# 一元線性回歸的實現

# 導入matplotlib庫,主要用於可視化
import numpy as np
from matplotlib.font_manager import FontProperties
import matplotlib.pyplot as plt
%matplotlib inline

# 引入本地字體文件,否則中文會有亂碼
# font_set = FontProperties(fname=r"./work/ simsun.ttc", size=12)

# 構造用於訓練的數據集
x_train = [4, 8, 5, 10, 12]
y_train = [20, 50, 30, 70, 60]


# 畫圖函數


def draw(x_train, y_train):
plt.scatter(x_train, y_train)


# 定義函數求得斜率w和截距b
# 使用最小二乘法對斜率和截距求導並使得導數值等於0求解出斜率和截距


def fit(x_train, y_train):
size = len(x_train)
numerator = 0 # 初始化分子
denominator = 0 # 初始化分母
for i in range(size):
numerator += (x_train[i] - np.mean(x_train)) * \
(y_train[i] - np.mean(y_train))
denominator += (x_train[i] - np.mean(x_train)) ** 2
w = numerator / denominator
b = np.mean(y_train) - w * np.mean(x_train)
return w, b


# 根據斜率w和截距b,輸入x計算輸出值


def predict(x, w, b):
# 預測模型
y = w * x + b
return y


# 根據W,B畫圖


def fit_line(w, b):
# 測試集進行測試,並作圖
# linspace 創建等差數列的函數 #numpy.limspace(start,stop,num,endpoint=True,retstep=False,dtype=None,axis=0#)
x = np.linspace(4, 15, 9)
y = w * x + b
plt.plot(x, y)
plt.show()


if __name__ == "__main__":
draw(x_train, y_train)

 

w, b = fit(x_train, y_train)
print(w, b) # 輸出斜率和截距
fit_line(w, b) # 繪制預測函數圖像


免責聲明!

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



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