随机梯度下降 Stochastic Gradient Descent(SGD)
随机梯度下降相比于梯度下降,随机梯度是从N个样本中随机选取其中单个样本来计算它的损失
梯度下降公式
其中
随机梯度下降公式
其中
随机梯度下降的损失函数
代码
准备训练数据
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 loss(x, y):
y_pred = forward(x)
return (y_pred - y) ** 2
定义随机梯度下降函数
def gradient(x, y):
return 2 * x * (x * w - y)
打印训练前梯度
print('Predict (before training)', 4, forward(4))
定义保存用plt库显示的数据
loss_list = []
epoch_list = []
训练
for epoch in range(100):
for x, y in zip(x_data, y_data):
grad = gradient(x, y)
w -= 0.01 * grad
print("\tgrad:", x, y, grad)
l = loss(x, y)
print("epoch:", epoch, "w=", w, "loss=", loss)
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()