深度学习基础2:Batch Gradient Descent(BGD)
·
import matplotlib.pyplot as plt
x_data = [1.0, 2.0, 3.0]
y_data = [2.0, 4.0, 6.0]
w = 1.0
#forward(x):前向传播(模型预测)
def forward(x):
return x * w
#cost(xs, ys):损失函数,计算所有样本上的均方误差(MSE)
def cost(xs, ys):
cost = 0
for x, y in zip(xs, ys):
y_pred = forward(x)
cost += (y - y_pred) ** 2
return cost / len(xs)
# gradient(xs, ys):梯度计算函数,计算损失函数关于参数 w 的导数。公式推导如下:
# 单个样本损失:loss=(y-w*x)^2
# 对 w 求导:d(loss)/dw = 2*(y-w*x)*(-x)=2*x*(w*x-y).对所有样本求平均即得总梯度。
def gradient(xs, ys):
gred = 0;
for x, y in zip(xs, ys):
gred += 2 * x * (x * w - y)
return gred / len(xs)
# 两个空列表,用来记录数据
epochs = [] # 记录每一次的epoch数
costs = [] # 记录每一次的cost值
print('Predict (before training):', 4, forward(4))
for epoch in range(100): # 迭代100次
cost_val = cost(x_data, y_data) # 1. 计算当前损失
grad_val = gradient(x_data, y_data) # 2. 计算当前梯度
w -= 0.01 * grad_val # 3. 核心:沿负梯度方向更新参数(# 0.01是学习率learning_rate,控制每一步更新的大小)
print('Epoch:', epoch , ', w:', w, ', Cost:', cost_val)
# 记录当前的数据
epochs.append(epoch) # 当前是第几次迭代
costs.append(cost_val) # 当前的损失值是多少
print('Predict (after training):', 4, forward(4))
# ============= 绘图部分 =============
# 1. 创建画布
plt.figure()
# 2. 绘制折线图:x轴是epoch_history,y轴是cost_history
# 'b-' 表示蓝色实线,linewidth=2 表示线宽为2
plt.plot(epochs, costs, 'b-', linewidth=2)
# 3. 添加坐标轴标签
plt.xlabel('Epoch')
plt.ylabel('Cost(MSE)')
# 4. 添加标题
plt.title('Gradient Descent: Cost vs Epoch')
# 5. 添加网格线(可选,让读数更清晰)
plt.grid(True, linestyle='--', alpha=0.5)
# 6. 显示图像
plt.show()
更多推荐
所有评论(0)