本笔记来源于b站刘二大人:《PyTorch深度学习实践》3.梯度下降
一、代码
import matplotlib.pyplot as plt
# prepare the training set
x_data = [1.0, 2.0, 3.0]
y_data = [2.0, 4.0, 6.0]
# initial guess of weight
w = 1.0
# define the model linear model y = w*x
def forward(x):
return x*w
#define the cost function MSE
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)
# define the gradient function gd
def gradient(xs,ys):
grad = 0
for x, y in zip(xs,ys):
grad += 2*x*(x*w - y)
return grad / len(xs)
epoch_list = []
cost_list = []
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 # 0.01 learning rate
print('epoch:', epoch, 'w=', w, 'loss=', cost_val)
epoch_list.append(epoch)
cost_list.append(cost_val)
print('predict (after training)', 4, forward(4))
plt.plot(epoch_list,cost_list)
plt.ylabel('cost')
plt.xlabel('epoch')
plt.show()
二、何为梯度
首选明确梯度是什么:梯度的本意是一个向量(矢量),表示某一函数在该点处的方向导数沿着该方向取得最大值,即函数在该点处沿着该方向变化最快,变化率最大。
既然是函数,那么就会有一元与多元的区分
一元函数:
如上图,对于cost和w组成的函数上的任一点就是这一点的切线向量:
二元函数:
在一元上进行推导,对多元函数而言这一点的梯度就是由这一点所有自变量的偏导数组成的向量。如对cost = f(w1,w2,w3),
三、再来理解梯度下降算法
上面说了函数在该点处沿着梯度变化最快,变化率最大。那么对于我们的损失函数cost和权重w而言,深度学习需要让cost随着w的变化尽快的下降到最小,直到无限趋近于0或者等于0。
既然函数在该点处沿着梯度上升变化最快,那么沿着梯度反方向就是下降最快,也就是我们需要的情况,这就是梯度下降算法。
表现在数学上就是,其中
就是学习率,也就是我们沿着梯度这根线下降一次多少,
要取合适值,太大太小都不好