x | y |
---|---|
1 | 2 |
2 | 4 |
3 | 6 |
梯度的方向一定是函数值上升的方向,最小值是0
梯度下降公式:(α为学习率)
=
=
python代码:
x_data = [1.0,2.0,3.0]
y_data = [2.0,4.0,6.0]
w = 1.0
def forward(x):
return x*w
def cost(xs,ys):
cost = 0
for x,y in zip(xs,ys):
y_pred = forward(x)
cost +=(y_pred-y) ** 2
return cost/len(xs)
def gradient(xs,ys):
grad = 0
for x,y in zip(xs,ys):
grad+=2*x*(x*w-y)
return grad/len(xs)
print('Predict (before training)',4,forward(4))
for epoch in range(100):
cost_val = cost(x_data,y_data)
grad_val = gradient(x_data,y_data)
w-=0.01*grad_val
print('Epoch:',epoch,'w=',w,'loss=',cost_val)
print('Predict (after training)',4,forward(4))
若曲线波动比较大,可以用指数加权均值平滑
梯度下降公式:
=
注意这里是对每一个样本求梯度,而梯度下降是对全部样本求梯度,这里就有一个很明显的问题,对于梯度下降在计算f(x)的梯度和计算f(x+1)的梯度是可以并行计算的,然而在随机梯度下降中显然是不行的,因为其计算每一个样本的梯度然后更新w,这个w又用于f(x+1)的计算,所以从时间复杂度上来看随机梯度下降差,但是性能上随机梯度下降好一些。
本文地址:https://blog.csdn.net/luoshiyong123/article/details/107283498
如对本文有疑问, 点击进行留言回复!!
故事向|在3A游戏公司工作多年的3D建模师自述,制作3A大作经验心得(上)
「建模学习」zbrush中如何制作拉链?拉链笔刷来帮忙,轻松搞定
LeetCode hot-100 简单and中等难度,21-30.
Second season eighth episode,Ross made a list about Rachel,compared to Julie??!!
2020.08.07 J - MaratonIME goes to Mito
网友评论