1. 程式人生 > 其它 >機器學習:單元線性迴歸(python簡單實現)

機器學習:單元線性迴歸(python簡單實現)

本篇文章主要記錄和講解使用python如何簡單實現單元線性迴歸演算法

文章簡介

本篇文章主要記錄和講解使用python如何簡單實現單元線性迴歸演算法,鑑於筆者也是初學,所以如果文章有問題,望友好指正,謝謝!

演算法目的

該演算法核心目的是為了求出假設函式h中多個theta的值,使得代入資料集合中的每個x,求得的h(x)與每個資料集合中的y的差值的和最小。簡單來說就是需要生成一個函式,它儘可能貼近實際資料中的每個值,方便我們預測。

核心演算法

  1. 假設函式
    即需要求的函式,為了簡單在此只設置一個x對應一個y,求theta0和theta1
  2. 代價函式
    目的是J最小,也就是每個y到達函式的距離之和最小。
  3. 批量梯度下降函式

    帶假設函式和代價函式帶入到下降函式中可得

演算法實現

import numpy as np
import matplotlib.pyplot as plt

def hypoFunction(x, theta):
h = np.dot(x, theta)
return h


def costFunction(h, y):
"""
代價函式
h:hypothesis,
theta:特徵向量係數
y:特徵值對應的實際值
"""
m = len(y)
J = 1 / (2 * m) * np.sum(np.power(h - y, 2))
return J


def gradientDecent(x, y, h, theta, alpha, number):
"""梯度下降函式
number:設定的梯度下降次數"""
# for i in range(number):
m = len(y)
n = len(theta)
J_history = np.zeros((number,1))
for i in range(number):
theta = theta - (alpha/m) * x.T.dot(h-y)
h = hypoFunction(x, theta)
J_history[i] = costFunction(h,y)
print(theta)
return h

def paint(x,y,hypothesis):
plt.plot(x,y,"ro")
plt.plot(x,hypothesis)
plt.show()

 

def main():
x = np.array([[1,1], [1,2], [1,3], [1,4], [1,5], [1,6]])
y = np.array([[1], [2], [3], [4], [5], [6]])
theta = np.array([[10],[0]])
alpha = 0.1
h = hypoFunction(x, theta)
J = costFunction(h, y)
h= gradientDecent(x, y, h, theta, alpha, 20000)
x = x[:,-1]
print(x)
paint(x,y,h)
pass


if __name__ == "__main__":
main()

簡單解釋

  1. 因為設定了兩個theta,為了方便運算以及滿足矩陣乘法的要求,所以x多添加了一列1。
  2. theta初始值可以任意設定。
  3. alpha大小初始值不要過大,否則有可能導致梯度下降函式不收斂。如果初始值過小,則會導致需要計算很多次才能達到全域性最優解。