PyTorch深度学习实践 3.梯度下降算法-->mini-batch stochastic gradient descent

分治法

w1和w2
假设横竖都是64
横竖都分成4份,一共16份。
第一次在这16份里,找出比较小的点,
再来几轮,基本就OK了。
从原来的16x16变成了16+16
在这里插入图片描述

贪心法

梯度下降法,局部最优,实际上,大家发现神经网络里并没有很多的局部最优点

鞍点g=0,无法迭代了
在这里插入图片描述
在这里插入图片描述

import numpy as np
import matplotlib.pyplot as plt

xxl=0.01

w=1.0

# 定义模型
def forward(x):
    return x*w

def cost(xs,ys):
    cost=0
    for x,y in zip(xs,ys):
        y_prediction=forward(x)
        cost+=(y_prediction-y)**2
        return cost/len(xs)

def gradient(xs,ys):
    grad=0
    for x,y in zip(xs,ys):
        y_prediction = forward(x)
        grad+=2 * x * (y_prediction - y)
    return grad/len(xs)

# 定义训练集
x_data = [1.0, 2.0, 3.0]
y_data = [2.0, 4.0, 6.0]

print('Prediciton(before training)',4,forward(4))

for epoch in range(100):
    cost_val=cost(x_data,y_data)
    grad=gradient(x_data,y_data)
    w=w-xxl*grad
    print("progress:",epoch,"w=",w,"loss=",cost_val)
print('Prediction(after training)',4,forward(4))

在这里插入图片描述

指数加权均值,更平滑
在这里插入图片描述
一定要收敛,发散说明失败了,可能是学习率太大

在这里插入图片描述
随机梯度下降,可以克服鞍点
在这里插入图片描述
在这里插入图片描述

项目速度效果(鞍点)
梯度下降快(因为可以并行 xi和xi+1的函数值无关)
随机梯度下降慢(只能串行,因为w与上一个有关)

所以折中
批量随机梯度下降batch
mini-batch stochastic gradient descent
在这里插入图片描述

# 随机梯度下降
import numpy as np
import matplotlib.pyplot as plt

xxl=0.01

w=1.0

# 定义模型
def forward(x):
    return x*w

def Loss_Function(x,y):
    y_prediction=forward(x)
    return (y_prediction-y)**2

def gradient(x,y):
    y_prediction = forward(x)
    return 2 * x *(y_prediction-y)

# 定义训练集
x_data = [1.0, 2.0, 3.0]
y_data = [2.0, 4.0, 6.0]

print('Prediciton(before training)',4,forward(4))

for epoch in range(100):
    for x,y in zip(x_data,y_data):
        grad=gradient(x,y)
        w=w-xxl*grad
        print('\tgradient:',x,y,grad)
        l=Loss_Function(x,y)
    print("progress:",epoch,"w=",w,"loss=",l)
print('Prediction(after training)',4,forward(4))

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值