教程视频:梯度下降算法
学习目标:实现梯度下降算法(GD)和随机梯度下降算法(SGD),输出loss关于Epoch的图像。
一、梯度下降算法(GD)
代码如下(示例):
# -*- coding: UTF-8 -*-
'''===============================================
@Author :kidding
@Date :2021/2/3 14:46
@File :GD
@IDE :PyCharm
=================================================='''
import matplotlib.pyplot as plt
#函数设定为 Y = 2X
x_data = [1.0,2.0,3.0]
y_data = [2.0,4.0,6.0]
#定义权重W
w = 1.0
#定义前馈计算 y_hat = X * W
def forward(x):
return x*w
#定义成本函数 cost
def cost(xs,ys):
cost = 0
for x,y in zip(xs,ys):
y_pred = forward(x) #计算 y_hat
cost += (y_pred-y)**2 # 计算每组数据的损失值 cost = (y_pred-y)*(y_pred-y)
return cost / len(xs) #除数据样本个数,求均值
#计算梯度
def gradient(xs,ys):
grad = 0
for x,y in zip(xs,ys):
grad += 2 * x * (x*w -y) #计算 cost
return grad / len(xs) #除数据样本个数,求均值
Epoch_list =[] #保存epoch
Cost_list = [] #保存每个epoch对应的cost
print('Predict (Before training)',4,forward(4))
#开始训练
for epoch in range(100):
cost_val = cost(x_data,y_data) #第一步:先算当前步的损失值(cost)
grad_val = gradient(x_data,y_data) #第二步:计算梯度(gradient)
w -= 0.01*grad_val #更新权重值 w
#print("Epoch:",epoch,"w =.2f",w,"cost =.2f",cost_val) #原始输出
#对输出进行格式调整
print("Epoch:",epoch,"w ={:.3f}".format(w),"loss ={:.3f}".format(cost_val))
Epoch_list.append(epoch)
Cost_list.append(cost_val)
plt.plot(Epoch_list,Cost_list)
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.grid(ls='--') # 生成网格
plt.show()
print('Predict (after training):',4,forward(4))
实现效果:
Loss图像:
二、随机梯度下降算法(SGD)
代码实现:
# -*- coding: UTF-8 -*-
'''===============================================
@Author :kidding
@Date :2021/2/3 15:37
@File :SGD
@IDE :PyCharm
=================================================='''
import numpy as np
import matplotlib.pyplot as plt
#函数设定为 Y = 2X
x_data = [1.0,2.0,3.0]
y_data = [2.0,4.0,6.0]
#定义权重W
w = 1.0
#定义前馈计算 y_hat = X * W
def forward(x):
return x*w
#定义成本函数 cost
def loss(x,y):
y_pred = forward(x) #随机抽取一个样本进行正向传播,以该样本的梯度代替所有样本的梯度进行梯度下降
return (y_pred - y)**2 # 计算该样本的 y_hat = (y_pred-y)*(y_pred-y)
#计算梯度
def gradient(x,y):
return 2 * x * (x*w -y) #计算 cost
Epoch_list =[] #保存epoch
Cost_list = [] #保存每个epoch对应的cost
print('Predict (Before training)',4,forward(4))
#开始训练
for epoch in range(100):
for x,y in zip(x_data,y_data):
grad_val = gradient(x,y)
w -= 0.01 * grad_val #更新权重值 w
print("\tgrad:", x , y , grad_val)
l = loss(x,y)
Epoch_list.append(epoch)
Cost_list.append(l)
# 对输出进行格式调整
print("Progress Epoch:", epoch, "w ={:.3f}".format(w), "loss ={:.3f}".format(l))
plt.plot(Epoch_list,Cost_list)
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.grid(ls='--') # 生成网格
plt.show()
print('Predict (after training):',4,forward(4))
实现效果:
Loss图像:
**注:**本代码为学生自己编写,不一定准确,如果有错误,希望大家可以在评论区指出来,谢谢。