当前位置:   article > 正文

动手学深度学习——批量归一化_拉伸和偏移参数怎么迭代

拉伸和偏移参数怎么迭代

1、批量归一化

损失出现在最后,后面的层训练较快;

数据在最底部,底部的层训练的慢;底部层一变化,所有都得跟着变;最后的那些层需要重新学习多次;导致收敛变慢;

固定小批量里面的均差和方差:

然后再做额外的调整(可学习的参数):

2、批量归一化层

可学习的参数为γ和β;

作用在全连接层和卷积层输出上,激活函数前;全连接层和卷积层输入上;

对全连接层,作用在特征维;

对于卷积层,作用在通道维上。

3、批量归一化在做什么

最初是想用它来减少内部变量转移;后续指出它可能就是通过在每个小批量里加入噪音来控制模型复杂度。

 因此没有必要跟丢弃法混合使用。

4、总结

批量归一化固定小批量中的均值和方差,然后学习出适合的便宜和缩放;

可以加速收敛速度,但一般不改变模型精度。

5、代码实现

  1. """批量归一化 从零开始实现"""
  2. import time
  3. import torch
  4. from torch import nn, optim
  5. import torch.nn.functional as F
  6. import sys
  7. sys.path.append("..")
  8. import d2lzh_pytorch as d2l
  9. device = torch.device('cuda' if torch.cuda.is_available() else'cpu')
  10. def batch_norm(is_training, X, gamma, beta, moving_mean,moving_var, eps, momentum):
  11. # 判断当前模式是训练模式还是预测模式
  12. if not is_training:
  13. # 如果是在预测模式下,直接使⽤传⼊的移动平均所得的均值和⽅差
  14. X_hat = (X - moving_mean) / torch.sqrt(moving_var + eps)
  15. else:
  16. assert len(X.shape) in (2, 4)
  17. if len(X.shape) == 2:
  18. # 使⽤全连接层的情况,计算特征维上的均值和⽅差
  19. mean = X.mean(dim=0)
  20. var = ((X - mean) ** 2).mean(dim=0)
  21. else:
  22. # 使⽤⼆维卷积层的情况,计算通道维上(axis=1)的均值和⽅差。这⾥我们需要保持
  23. mean = X.mean(dim=0, keepdim=True).mean(dim=2,keepdim=True).mean(dim=3, keepdim=True)
  24. var = ((X - mean) ** 2).mean(dim=0,keepdim=True).mean(dim=2, keepdim=True).mean(dim=3, keepdim=True)
  25. # 训练模式下⽤当前的均值和⽅差做标准化
  26. X_hat = (X - mean) / torch.sqrt(var + eps)
  27. # 更新移动平均的均值和⽅差
  28. moving_mean = momentum * moving_mean + (1.0 - momentum) *mean
  29. moving_var = momentum * moving_var + (1.0 - momentum) * var
  30. Y = gamma * X_hat + beta # 拉伸和偏移
  31. return Y, moving_mean, moving_var
  32. #创建一个正确的BatchNorm图层
  33. class BatchNorm(nn.Module):
  34. def __init__(self, num_features, num_dims):
  35. super(BatchNorm, self).__init__()
  36. if num_dims == 2:
  37. shape = (1, num_features)
  38. else:
  39. shape = (1, num_features, 1, 1)
  40. # 参与求梯度和迭代的拉伸和偏移参数,分别初始化成0和1
  41. self.gamma = nn.Parameter(torch.ones(shape))
  42. self.beta = nn.Parameter(torch.zeros(shape))
  43. # 不参与求梯度和迭代的变量,全在内存上初始化成0
  44. self.moving_mean = torch.zeros(shape)
  45. self.moving_var = torch.zeros(shape)
  46. def forward(self, X):
  47. # 如果X不在内存上,将moving_mean和moving_var复制到X所在显存上
  48. if self.moving_mean.device != X.device:
  49. self.moving_mean = self.moving_mean.to(X.device)
  50. self.moving_var = self.moving_var.to(X.device)
  51. # 保存更新过的moving_mean和moving_var, Module实例的traning属性默认为true, 调⽤.eval()后设成false
  52. Y, self.moving_mean, self.moving_var = batch_norm(self.training, X, self.gamma, self.beta, self.moving_mean,self.moving_var, eps=1e-5, momentum=0.9)
  53. return Y
  54. """ 使⽤批量归⼀化层的LeNet"""
  55. net = nn.Sequential( nn.Conv2d(1, 6, 5),
  56. # in_channels, out_channels,kernel_size
  57. BatchNorm(6, num_dims=4),
  58. nn.Sigmoid(),
  59. nn.MaxPool2d(2, 2), # kernel_size, stride
  60. nn.Conv2d(6, 16, 5),
  61. BatchNorm(16, num_dims=4),
  62. nn.Sigmoid(),
  63. nn.MaxPool2d(2, 2),
  64. d2l.FlattenLayer(),
  65. nn.Linear(16*4*4, 120),
  66. BatchNorm(120, num_dims=2),
  67. nn.Sigmoid(),
  68. nn.Linear(120, 84),
  69. BatchNorm(84, num_dims=2),
  70. nn.Sigmoid(),
  71. nn.Linear(84, 10)
  72. )
  73. #训练修改后的模型
  74. batch_size = 256
  75. train_iter, test_iter =d2l.load_data_fashion_mnist(batch_size=batch_size)
  76. lr, num_epochs = 0.001, 5
  77. optimizer = torch.optim.Adam(net.parameters(), lr=lr)
  78. d2l.train_ch5(net, train_iter, test_iter, batch_size, optimizer,device, num_epochs)
  79. """批量归一化 简介实现"""
  80. net = nn.Sequential(
  81. nn.Conv2d(1, 6, 5), # in_channels, out_channels,kernel_size
  82. nn.BatchNorm2d(6),
  83. nn.Sigmoid(),
  84. nn.MaxPool2d(2, 2), # kernel_size, stride
  85. nn.Conv2d(6, 16, 5),
  86. nn.BatchNorm2d(16),
  87. nn.Sigmoid(),
  88. nn.MaxPool2d(2, 2),
  89. d2l.FlattenLayer(),
  90. nn.Linear(16*4*4, 120),
  91. nn.BatchNorm1d(120),
  92. nn.Sigmoid(),
  93. nn.Linear(120, 84),
  94. nn.BatchNorm1d(84),
  95. nn.Sigmoid(),
  96. nn.Linear(84, 10)
  97. )
  98. #使⽤同样的超参数进⾏训练。
  99. batch_size = 256
  100. train_iter, test_iter =d2l.load_data_fashion_mnist(batch_size=batch_size)
  101. lr, num_epochs = 0.001, 5
  102. optimizer = torch.optim.Adam(net.parameters(), lr=lr)
  103. d2l.train_ch5(net, train_iter, test_iter, batch_size, optimizer,device, num_epochs)

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

闽ICP备14008679号