当前位置:   article > 正文

37.深度学习中的梯度下降法及其实现

37.深度学习中的梯度下降法及其实现

在深度学习的优化过程中,梯度下降法及其变体是必不可少的工具。通过对梯度下降法的理论学习,我们能够更好地理解深度学习模型的训练过程。本篇文章将介绍梯度下降的基本原理,并通过代码实现展示其具体应用。我们会从二维平面的简单梯度下降开始,逐步过渡到三维,再对比多种优化器的效果。

一、梯度下降法简介

梯度下降法(Gradient Descent)是一种常用的优化算法,广泛应用于机器学习和深度学习中。其基本思想是通过迭代更新参数,使得损失函数逐步减小,最终找到最优解。常见的梯度下降法包括随机梯度下降(SGD)、动量法(Momentum)、自适应学习率方法(Adagrad、RMSprop、Adadelta)和Adam等。

二、梯度下降的二维实现

首先,我们来实现一个简单的二维平面内的梯度下降法。目标是找到函数 f(x)=x2+4x+1 的最小值。

  1. import torch
  2. import matplotlib.pyplot as plt
  3. # 定义目标函数
  4. def f(x):
  5. return x**2 + 4*x + 1
  6. # 初始化参数
  7. x = torch.tensor([2.0], requires_grad=True)
  8. learning_rate = 0.7
  9. # 记录每次梯度下降的值
  10. xs, ys = [], []
  11. # 梯度下降迭代
  12. for i in range(100):
  13. y = f(x)
  14. y.backward()
  15. with torch.no_grad():
  16. x -= learning_rate * x.grad
  17. x.grad.zero_()
  18. xs.append(x.item())
  19. ys.append(y.item())
  20. # 打印最终结果
  21. print(f"最终x值: {x.item()}")
  22. # 可视化
  23. x_vals = torch.linspace(-4, 2, 100)
  24. y_vals = f(x_vals)
  25. plt.plot(x_vals.numpy(), y_vals.numpy(), label='f(x)=x^2 + 4x + 1')
  26. plt.scatter(xs, ys, color='red', label='Gradient Descent')
  27. plt.xlabel('x')
  28. plt.ylabel('f(x)')
  29. plt.legend()
  30. plt.show()

通过以上代码,我们能够看到从初始点出发,梯度下降法逐步逼近最小值。

三、梯度下降的三维实现

增加一个维度,函数变为 f(x,y)=x2+y2,我们希望通过梯度下降法找到该函数的最小值。

  1. from mpl_toolkits.mplot3d import Axes3D
  2. # 定义目标函数
  3. def f(x, y):
  4. return x**2 + y**2
  5. # 初始化参数
  6. x = torch.tensor([2.0], requires_grad=True)
  7. y = torch.tensor([2.0], requires_grad=True)
  8. learning_rate = 0.1
  9. # 记录每次梯度下降的值
  10. xs, ys, zs = [], [], []
  11. # 梯度下降迭代
  12. for i in range(100):
  13. z = f(x, y)
  14. z.backward()
  15. with torch.no_grad():
  16. x -= learning_rate * x.grad
  17. y -= learning_rate * y.grad
  18. x.grad.zero_()
  19. y.grad.zero_()
  20. xs.append(x.item())
  21. ys.append(y.item())
  22. zs.append(z.item())
  23. # 打印最终结果
  24. print(f"最终x, y值: {x.item()}, {y.item()}")
  25. # 可视化
  26. fig = plt.figure()
  27. ax = fig.add_subplot(111, projection='3d')
  28. ax.plot(xs, ys, zs, label='Gradient Descent Path', marker='o')
  29. ax.set_xlabel('X')
  30. ax.set_ylabel('Y')
  31. ax.set_zlabel('Z')
  32. plt.legend()
  33. plt.show()
  34. # 等高线图
  35. plt.figure()
  36. X, Y = torch.meshgrid(torch.linspace(-3, 3, 100), torch.linspace(-3, 3, 100))
  37. Z = f(X, Y)
  38. plt.contourf(X.numpy(), Y.numpy(), Z.numpy(), 50)
  39. plt.plot(xs, ys, 'r-o', label='Gradient Descent Path')
  40. plt.xlabel('x')
  41. plt.ylabel('y')
  42. plt.legend()
  43. plt.show()

通过以上代码,我们能够在三维空间中看到梯度下降的路径。

四、不同优化器的对比

接下来,我们生成一个数据集,使用不同的优化器进行对比,观察它们的收敛效果。

 

  1. import torch.utils.data as data
  2. # 生成数据集
  3. def generate_data(num_samples=1000):
  4. x = torch.rand(num_samples, 1)
  5. y = torch.rand(num_samples, 1)
  6. z = f(x, y) + torch.randn(num_samples, 1)
  7. return x, y, z
  8. x, y, z = generate_data()
  9. dataset = data.TensorDataset(torch.cat([x, y], dim=1), z)
  10. train_size = int(0.8 * len(dataset))
  11. test_size = len(dataset) - train_size
  12. train_dataset, test_dataset = data.random_split(dataset, [train_size, test_size])
  13. train_loader = data.DataLoader(train_dataset, batch_size=32)
  14. test_loader = data.DataLoader(test_dataset, batch_size=32)
  15. # 定义模型
  16. class SimpleNN(torch.nn.Module):
  17. def __init__(self):
  18. super(SimpleNN, self).__init__()
  19. self.fc = torch.nn.Linear(2, 1)
  20. def forward(self, x):
  21. return self.fc(x)
  22. # 初始化模型和优化器
  23. models = [SimpleNN() for _ in range(6)]
  24. optimizers = [
  25. torch.optim.SGD(models[0].parameters(), lr=0.01),
  26. torch.optim.SGD(models[1].parameters(), lr=0.01, momentum=0.9),
  27. torch.optim.Adagrad(models[2].parameters(), lr=0.01),
  28. torch.optim.RMSprop(models[3].parameters(), lr=0.01),
  29. torch.optim.Adadelta(models[4].parameters()),
  30. torch.optim.Adam(models[5].parameters(), lr=0.01)
  31. ]
  32. loss_fn = torch.nn.MSELoss()
  33. # 训练和测试函数
  34. def train_epoch(model, optimizer, loader):
  35. model.train()
  36. total_loss = 0
  37. for x_batch, y_batch in loader:
  38. optimizer.zero_grad()
  39. y_pred = model(x_batch)
  40. loss = loss_fn(y_pred, y_batch)
  41. loss.backward()
  42. optimizer.step()
  43. total_loss += loss.item()
  44. return total_loss / len(loader)
  45. def test_epoch(model, loader):
  46. model.eval()
  47. total_loss = 0
  48. with torch.no_grad():
  49. for x_batch, y_batch in loader:
  50. y_pred = model(x_batch)
  51. loss = loss_fn(y_pred, y_batch)
  52. total_loss += loss.item()
  53. return total_loss / len(loader)
  54. # 记录误差
  55. train_losses = [[] for _ in range(6)]
  56. test_losses = [[] for _ in range(6)]
  57. # 训练和测试过程
  58. num_epochs = 50
  59. for epoch in range(num_epochs):
  60. for i in range(6):
  61. train_loss = train_epoch(models[i], optimizers[i], train_loader)
  62. test_loss = test_epoch(models[i], test_loader)
  63. train_losses[i].append(train_loss)
  64. test_losses[i].append(test_loss)
  65. # 可视化收敛曲线
  66. plt.figure(figsize=(12, 6))
  67. for i, name in enumerate(['SGD', 'Momentum', 'Adagrad', 'RMSprop', 'Adadelta', 'Adam']):
  68. plt.plot(train_losses[i], label=f'Train {name}')
  69. plt.plot(test_losses[i], '--', label=f'Test {name}')
  70. plt.xlabel('Epoch')
  71. plt.ylabel('Loss')
  72. plt.legend()
  73. plt.show()

通过上述代码,我们能够对比不同优化器的收敛效果,从图中可以看到各个优化器的表现差异。

五、总结

本文通过代码实现详细展示了梯度下降法在二维和三维空间中的应用,并对比了多种优化器的效果。通过这些实践,我们能够更直观地理解梯度下降法的工作原理及其在深度学习中的应用。希望大家通过本篇文章,能够更加熟练地应用梯度下降及其变体进行模型训练。加油!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/815828?site
推荐阅读
相关标签
  

闽ICP备14008679号