梯度下降算法
现在的问题转化为找到使目标函数(损失函数)达到最小值的参数w,即优化问题:
在深度学习中局部最优问题不常见,不多,最大的问题是要解决鞍点问题:梯度为零,无法更新参数进行迭代,如下图:
梯度下降算法MSE更新迭代公式:
代码实操,找到最佳的epoch可视化:
import numpy as np
import matplotlib.pyplot as plt
X = [1.0,2.0,3.0]
Y = [2.0,4.0,6.0]
#定义初始的w
w = 1.0
loss = []
#定义前馈传播
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('beginning training',4,forward(4))
for epoch in range(100):
cost_val = Cost(X,Y)
loss.append(cost_val)
grad_val = gradient(X,Y)
w -= 0.01*grad_val
print('epoch:',epoch,'w:',w,'loss:',cost_val)
print('end training',4,forward(4))
#画图
epoch = np.arange(0,100,1)
plt.plot(epoch,loss)
plt.xlabel('epoch')
plt.ylabel('loss')
plt.show()
但是实际操作中上图这个曲线不可能这么平滑,可能会出现下边的问题曲线很抖,采用滑动指数加权平均来解决这个问题让这个曲线变的更光滑:
如果出现下边这种曲线,说明训练失败了,来调整学习率大小可能学习率太大了
随机梯度下降来解决可能会出现鞍点,加入噪声后,可能会解决这个鞍点问题,主要是通过一个样本的损失来进行梯度更新,不是用原来的所有样本的均值来进行梯度下降,随机梯度下降对每个样本的梯度进行更新,但是这个时间复杂度比较高
但是梯度下降算法性能低容易陷入局部最优,但可以并行化处理时间复杂度低,随机梯度下降性能好不易局部最优,但是不能并行化处理时间复杂度高,为了达到性能高,时间复杂度低的效果,所以采用mini Batch小批量随机梯度下降算法,深度学习基本都采用这个
import matplotlib.pyplot as plt
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
# calculate loss function
def loss(x, y):
y_pred = forward(x)
return (y_pred - y)**2
# define the gradient function sgd
def gradient(x, y):
return 2*x*(x*w - y)
epoch_list = []
loss_list = []
print('predict (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 - 0.01*grad # update weight by every grad of sample of training set
print("\tgrad:", x, y,grad)
l = loss(x,y)
print("progress:",epoch,"w=",w,"loss=",l)
epoch_list.append(epoch)
loss_list.append(l)
print('predict (after training)', 4, forward(4))
plt.plot(epoch_list,loss_list)
plt.ylabel('loss')
plt.xlabel('epoch')
plt.show()
这里面两个代码的区别在于,在计算梯度和损失的时候用for循环遍历整个样本计算平均值,还是单个样本定义梯度和损失函数,放在epoch后进行两个for循环一个个样本继续梯度更新