線性回歸下的梯度下降
The Gradient Descent Of Linear Regression
自學視頻PyTorch學這個就夠了!:
課件以及代碼:Pytorch.zip
這節課(lesson 3)用到的資料集和代碼:lesson03代碼及資料.zip
我用的Pycharm運行的,大家關注我就能下載了,不用收費 嗚嗚嗚,
學他學他學他!就學他!講的太透徹了,我剛上初中就能聽明白,小白一枚之前看Pytorch的教程死活看不懂,沒想到這個一看就明白了!兄弟姐妹們學起來!
這里有一個loss函式:
當loss值最低的時候,就是求得的結果與預期結果最接近的時候,
文字描述不完 就直接上圖了


代碼:
import matplotlib.pyplot as plt
from matplotlib import pyplot as plt
import numpy as np
import torch
import pandas as pd
# %matplotlib inline
# %config InlineBackend.figure_format = 'svg'
# 繪制 loss 曲線
train_loss_results = [] # 將每輪的loss記錄在此串列中,為后續畫loss曲線提供資料
points = np.genfromtxt('l3_data.csv',delimiter = ',')
plt.scatter(points[:,0],points[:,1],c = '',edgecolors = 'b',s = 15)
plt.show()
# y = wx + b
def compute_error_for_line_given_points(b, w, points):
"""
計算給定超引數[w,b]的誤差值
"""
totalError = 0
for i in range(0, len(points)):
x = points[i, 0]
y = points[i, 1]
totalError += (y - (w * x + b)) ** 2
return totalError / float(len(points))
def step_gradient(b, w, points, lr):
b_gradient = 0
w_gradient = 0
N = float(len(points))
for i in range(len(points)):
x = points[i, 0]
y = points[i, 1]
b_gradient += -(2/N) * (y - ((w * x) + b))
w_gradient += -(2/N) * x * (y - ((w * x) + b))
b_new = b - (lr * b_gradient)
w_new = w - (lr * w_gradient)
return [b_new, w_new]
def gradient_descent_runner(points, b, w, lr, iterations):
"""
梯度下降
"""
for i in range(iterations):
b, w = step_gradient(b, w, np.array(points), lr)
print("iterations {}, loss: {}".format(i, compute_error_for_line_given_points(b,w,points)))
train_loss_results.append(compute_error_for_line_given_points(b,w,points)) # 將4個step的loss求平均記錄在此變數中
plt.title('Loss Function Curve') # 圖片標題
plt.xlabel('iterations') # x軸變數名稱
plt.ylabel('Loss') # y軸變數名稱
plt.axis([0, 10000, 112, 113])
plt.plot(train_loss_results, label="$Loss$") # 逐點畫出trian_loss_results值并連線,連線圖示是Loss
plt.legend() # 畫出曲線圖示
plt.show() # 畫出影像
return [b, w]
def run():
points = np.genfromtxt('l3_data.csv', delimiter = ',')
lr = 0.0001
initial_b = 0
initial_w = 0
iterations = 10000
print(f"Starting project descent at b = {initial_b}, w = {initial_w}, error = {compute_error_for_line_given_points(initial_b,initial_w,points)}")
print('\nRunning...')
[b, w] = gradient_descent_runner(points, initial_b, initial_w, lr, iterations)
print(f"\nAfter project descent at b = {b}, w = {w},error = {compute_error_for_line_given_points(b,w,points)}")
print('\nb:{},w:{}'.format(b, w))
if __name__ == '__main__':
run()
里面用了三個函式:
第一個函式:compute_error_for_line_given_points(b, w, points):是用來就是來計算loss均值的
第二個函式:step_gradient(b, w, points, lr): 計算 b 和 w的梯度值
第三個函式:gradient_descent_runner(points, b, w, lr, iterations):運行10000次,不斷迭代b和w,批量梯度下降,優化引數
運行結果:


x-y散點圖

loss隨迭代次數下降圖
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/252142.html
標籤:python
下一篇:通過爬蟲使用百度翻譯
