原文地址:

https://blog.csdn.net/weixin_40123108/article/details/83509838

--------------------------------------------------------------------------------------------------------

pytorch之添加BN层

批标准化

模型训练并不容易,特别是一些非常复杂的模型,并不能非常好的训练得到收敛的结果,所以对数据增加一些预处理,同时使用批标准化能够得到非常好的收敛结果,这也是卷积网络能够训练到非常深的层的一个重要原因。

数据预处理

目前数据预处理最常见的方法就是中心化和标准化,中心化相当于修正数据的中心位置,实现方法非常简单,就是在每个特征维度上减去对应的均值,最后得到 0 均值的特征。标准化也非常简单,在数据变成 0 均值之后,为了使得不同的特征维度有着相同的规模,可以除以标准差近似为一个标准正态分布,也可以依据最大值和最小值将其转化为 -1 ~ 1之间,这两种方法非常的常见,如果你还记得,前面我们在神经网络的部分就已经使用了这个方法实现了数据标准化,至于另外一些方法,比如 PCA 或者 白噪声已经用得非常少了。

Batch Normalization

前面在数据预处理的时候,尽量输入特征不相关且满足一个标准的正态分布,
这样模型的表现一般也较好。但是对于很深的网路结构,网路的非线性层会使得输出的结果变得相关,且不再满足一个标准的 N(0, 1) 的分布,甚至输出的中心已经发生了偏移,这对于模型的训练,特别是深层的模型训练非常的困难。

所以在 2015 年一篇论文提出了这个方法,批标准化,简而言之,就是对于每一层网络的输出,对其做一个归一化,使其服从标准的正态分布,这样后一层网络的输入也是一个标准的正态分布,所以能够比较好的进行训练,加快收敛速度。batch normalization 的实现非常简单,

对于给定的一个 batch 的数据  算法的公式如下

第一行和第二行是计算出一个 batch 中数据的均值和方差,接着使用第三个公式对 batch 中的每个数据点做标准化,ϵϵ 是为了计算稳定引入的一个小的常数,通常取 10−5105,最后利用权重修正得到最后的输出结果,非常的简单,

实现一下简单的一维的情况,也就是神经网络中的情况

  1. import sys
  2. sys.path.append('..')
  3.  
  4. import torch
  5. def simple_batch_norm_1d(x, gamma, beta):
  6. eps = 1e-5
  7. x_mean = torch.mean(x, dim=0, keepdim=True) # 保留维度进行 broadcast
  8. x_var = torch.mean((x - x_mean) ** 2, dim=0, keepdim=True)
  9. x_hat = (x - x_mean) / torch.sqrt(x_var + eps)
  10. return gamma.view_as(x_mean) * x_hat + beta.view_as(x_mean)
  11. x = torch.arange(15).view(5, 3)
    x=x.type(torch.float)
  12. gamma = torch.ones(x.shape[1])
  13. beta = torch.zeros(x.shape[1])
  14. print('before bn: ')
  15. print(x)
  16. y = simple_batch_norm_1d(x, gamma, beta)
  17. print('after bn: ')
  18. print(y)

可以看到这里一共是 5 个数据点,三个特征,每一列表示一个特征的不同数据点,使用批标准化之后,每一列都变成了标准的正态分布这个时候会出现一个问题,就是测试的时候该使用批标准化吗?答案是肯定的,因为训练的时候使用了,而测试的时候不使用肯定会导致结果出现偏差,但是测试的时候如果只有一个数据集,那么均值不就是这个值,方差为 0 吗?这显然是随机的,所以测试的时候不能用测试的数据集去算均值和方差,而是用训练的时候算出的移动平均均值和方差去代替

实现以下能够区分训练状态和测试状态的批标准化方法

  1. def batch_norm_1d(x, gamma, beta, is_training, moving_mean, moving_var, moving_momentum=0.1):
  2. eps = 1e-5
  3. x_mean = torch.mean(x, dim=0, keepdim=True) # 保留维度进行 broadcast
  4. x_var = torch.mean((x - x_mean) ** 2, dim=0, keepdim=True)
  5. if is_training:
  6. x_hat = (x - x_mean) / torch.sqrt(x_var + eps)
  7. moving_mean[:] = moving_momentum * moving_mean + (1. - moving_momentum) * x_mean
  8. moving_var[:] = moving_momentum * moving_var + (1. - moving_momentum) * x_var
  9. else:
  10. x_hat = (x - moving_mean) / torch.sqrt(moving_var + eps)
  11. return gamma.view_as(x_mean) * x_hat + beta.view_as(x_mean)

下面使用深度神经网络分类 mnist 数据集的例子来试验一下批标准化是否有用

  1. import numpy as np
  2. from torchvision.datasets import mnist # 导入 pytorch 内置的 mnist 数据
  3. from torch.utils.data import DataLoader
  4. from torch import nn
  5. from torch.autograd import Variable

使用内置函数下载 mnist 数据集

  1. train_set = mnist.MNIST('./data', train=True)
  2. test_set = mnist.MNIST('./data', train=False)
  3.  
  4. def data_tf(x):
  5. x = np.array(x, dtype='float32') / 255
  6. x = (x - 0.5) / 0.5 # 数据预处理,标准化
  7. x = x.reshape((-1,)) # 拉平
  8. x = torch.from_numpy(x)
  9. return x
  10.  
  11. train_set = mnist.MNIST('./data', train=True, transform=data_tf, download=True) # 重新载入数据集,申明定义的数据变换
  12. test_set = mnist.MNIST('./data', train=False, transform=data_tf, download=True)
  13. train_data = DataLoader(train_set, batch_size=64, shuffle=True)
  14. test_data = DataLoader(test_set, batch_size=128, shuffle=False)
  15. class multi_network(nn.Module):
  16. def __init__(self):
  17. super(multi_network, self).__init__()
  18. self.layer1 = nn.Linear(784, 100)
  19. self.relu = nn.ReLU(True)
  20. self.layer2 = nn.Linear(100, 10)
  21.  
  22. self.gamma = nn.Parameter(torch.randn(100))
  23. self.beta = nn.Parameter(torch.randn(100))
  24.  
  25. self.moving_mean = Variable(torch.zeros(100))
  26. self.moving_var = Variable(torch.zeros(100))
  27.  
  28. def forward(self, x, is_train=True):
  29. x = self.layer1(x)
  30. x = batch_norm_1d(x, self.gamma, self.beta, is_train, self.moving_mean, self.moving_var)
  31. x = self.relu(x)
  32. x = self.layer2(x)
  33. return x
  34. net = multi_network()
  35. # 定义 loss 函数
  36. criterion = nn.CrossEntropyLoss()
  37. optimizer = torch.optim.SGD(net.parameters(), 1e-1) # 使用随机梯度下降,学习率 0.1
  38.  
  39. from datetime import datetime
  40. import torch
  41. import torch.nn.functional as F
  42. from torch import nn
  43. from torch.autograd import Variable
  44. def get_acc(output, label):
  45. total = output.shape[0]
  46. _, pred_label = output.max(1)
  47. num_correct = (pred_label == label).sum().item()
  48. return num_correct / total
  49.  
  50. #定义训练函数
  51. def train(net, train_data, valid_data, num_epochs, optimizer, criterion):
  52. if torch.cuda.is_available():
  53. net = net.cuda()
  54. prev_time = datetime.now()
  55. for epoch in range(num_epochs):
  56. train_loss = 0
  57. train_acc = 0
  58. net = net.train()
  59. for im, label in train_data:
  60. if torch.cuda.is_available():
  61. im = Variable(im.cuda()) # (bs, 3, h, w)
  62. label = Variable(label.cuda()) # (bs, h, w)
  63. else:
  64. im = Variable(im)
  65. label = Variable(label)
  66. # forward
  67. output = net(im)
  68. loss = criterion(output, label)
  69. # backward
  70. optimizer.zero_grad()
  71. loss.backward()
  72. optimizer.step()
  73. train_loss += loss.item()
  74. train_acc += get_acc(output, label)
  75.  
  76. cur_time = datetime.now()
  77. h, remainder = divmod((cur_time - prev_time).seconds, 3600)
  78. m, s = divmod(remainder, 60)
  79. time_str = "Time %02d:%02d:%02d" % (h, m, s)
  80. if valid_data is not None:
  81. valid_loss = 0
  82. valid_acc = 0
  83. net = net.eval()
  84. for im, label in valid_data:
  85. if torch.cuda.is_available():
  86. im = Variable(im.cuda(), volatile=True)
  87. label = Variable(label.cuda(), volatile=True)
  88. else:
  89. im = Variable(im, volatile=True)
  90. label = Variable(label, volatile=True)
  91. output = net(im)
  92. loss = criterion(output, label)
  93. valid_loss += loss.item()
  94. valid_acc += get_acc(output, label)
  95. epoch_str = (
  96. "Epoch %d. Train Loss: %f, Train Acc: %f, Valid Loss: %f, Valid Acc: %f, "
  97. % (epoch, train_loss / len(train_data),
  98. train_acc / len(train_data), valid_loss / len(valid_data),
  99. valid_acc / len(valid_data)))
  100. else:
  101. epoch_str = ("Epoch %d. Train Loss: %f, Train Acc: %f, " %
  102. (epoch, train_loss / len(train_data),
  103. train_acc / len(train_data)))
  104. prev_time = cur_time
  105. print(epoch_str + time_str)
  106.  
  107. train(net, train_data, test_data, 10, optimizer, criterion)

#这里的 γγ 和 ββ 都作为参数进行训练,初始化为随机的高斯分布,
#moving_mean 和 moving_var 都初始化为 0,并不是更新的参数,训练完 10 次之后,我们可以看看移动平均和移动方差被修改为了多少
#打出 moving_mean 的前 10 项

  1. print(net.moving_mean[:10])
  2. no_bn_net = nn.Sequential(
  3. nn.Linear(784, 100),
  4. nn.ReLU(True),
  5. nn.Linear(100, 10)
  6. )
  7.  
  8. optimizer = torch.optim.SGD(no_bn_net.parameters(), 1e-1) # 使用随机梯度下降,学习率 0.1
  9. train(no_bn_net, train_data, test_data, 10, optimizer, criterion)

可以看到虽然最后的结果两种情况一样,但是如果我们看前几次的情况,可以看到使用批标准化的情况能够更快的收敛,因为这只是一个小网络,所以用不用批标准化都能够收敛,但是对于更加深的网络,使用批标准化在训练的时候能够很快地收敛从上面可以看到,我们自己实现了 2 维情况的批标准化,对应于卷积的 4 维情况的标准化是类似的,只需要沿着通道的维度进行均值和方差的计算,但是我们自己实现批标准化是很累的,pytorch 当然也为我们内置了批标准化的函数,一维和二维分别是 torch.nn.BatchNorm1d() 和 torch.nn.BatchNorm2d(),不同于我们的实现,pytorch 不仅将 γ 和 β 作为训练的参数,也将 moving_mean 和 moving_var 也作为参数进行训练

下面在卷积网络下试用一下批标准化看看效果

  1. def data_tf(x):
  2. x = np.array(x, dtype='float32') / 255
  3. x = (x - 0.5) / 0.5 # 数据预处理,标准化
  4. x = torch.from_numpy(x)
  5. x = x.unsqueeze(0)
  6. return x
  7.  
  8. train_set = mnist.MNIST('./data', train=True, transform=data_tf, download=True) # 重新载入数据集,申明定义的数据变换
  9. test_set = mnist.MNIST('./data', train=False, transform=data_tf, download=True)
  10. train_data = DataLoader(train_set, batch_size=64, shuffle=True)
  11. test_data = DataLoader(test_set, batch_size=128, shuffle=False)

使用批标准化

  1. class conv_bn_net(nn.Module):
  2. def __init__(self):
  3. super(conv_bn_net, self).__init__()
  4. self.stage1 = nn.Sequential(
  5. nn.Conv2d(1, 6, 3, padding=1),
  6. nn.BatchNorm2d(6),
  7. nn.ReLU(True),
  8. nn.MaxPool2d(2, 2),
  9. nn.Conv2d(6, 16, 5),
  10. nn.BatchNorm2d(16),
  11. nn.ReLU(True),
  12. nn.MaxPool2d(2, 2)
  13. )
  14.  
  15. self.classfy = nn.Linear(400, 10)
  16. def forward(self, x):
  17. x = self.stage1(x)
  18. x = x.view(x.shape[0], -1)
  19. x = self.classfy(x)
  20. return x
  21.  
  22. net = conv_bn_net()
  23. optimizer = torch.optim.SGD(net.parameters(), 1e-1) # 使用随机梯度下降,学习率 0.1
  24. train(net, train_data, test_data, 5, optimizer, criterion)

不使用批标准化

  1. class conv_no_bn_net(nn.Module):
  2. def __init__(self):
  3. super(conv_no_bn_net, self).__init__()
  4. self.stage1 = nn.Sequential(
  5. nn.Conv2d(1, 6, 3, padding=1),
  6. nn.ReLU(True),
  7. nn.MaxPool2d(2, 2),
  8. nn.Conv2d(6, 16, 5),
  9. nn.ReLU(True),
  10. nn.MaxPool2d(2, 2)
  11. )
  12.  
  13. self.classfy = nn.Linear(400, 10)
  14. def forward(self, x):
  15. x = self.stage1(x)
  16. x = x.view(x.shape[0], -1)
  17. x = self.classfy(x)
  18. return x
  19.  
  20. net = conv_no_bn_net()
  21. optimizer = torch.optim.SGD(net.parameters(), 1e-1) # 使用随机梯度下降,学习率 0.1
  22. train(net, train_data, test_data, 5, optimizer, criterion)

--------------------------------------------------------------------------------------------------------

ps:    个人补充

本文中给出的  一维  批正则 和  未加批正则的代码:

  1. #!/usr/bin/env python3
  2. #encoding:UTF-8
  3.  
  4. import torch
  5. import numpy as np
  6. import torch.nn.functional as F
  7. from torch import nn
  8. from torch.autograd import Variable
  9. from torchvision.datasets import mnist # 导入 pytorch 内置的 mnist 数据
  10. from torch.utils.data import DataLoader
  11. from datetime import datetime
  12.  
  13. def batch_norm_1d(x, gamma, beta, is_training, moving_mean, moving_var, moving_momentum=0.1):
  14. eps = 1e-5
  15. x_mean = torch.mean(x, dim=0, keepdim=True) # 保留维度进行 broadcast
  16. x_var = torch.mean((x - x_mean) ** 2, dim=0, keepdim=True)
  17. if torch.cuda.is_available():
  18. x_mean=x_mean.cuda()
  19. x_var=x_var.cuda()
  20. moving_mean=moving_mean.cuda()
  21. moving_var=moving_var.cuda()
  22. if is_training:
  23. x_hat = (x - x_mean) / torch.sqrt(x_var + eps)
  24. moving_mean[:] = moving_momentum * moving_mean + (1. - moving_momentum) * x_mean
  25. moving_var[:] = moving_momentum * moving_var + (1. - moving_momentum) * x_var
  26. else:
  27. x_hat = (x - moving_mean) / torch.sqrt(moving_var + eps)
  28. return gamma.view_as(x_mean) * x_hat + beta.view_as(x_mean)
  29.  
  30. def data_tf(x):
  31. x = np.array(x, dtype='float32') / 255
  32. x = (x - 0.5) / 0.5 # 数据预处理,标准化
  33. x = x.reshape((-1,)) # 拉平
  34. x = torch.from_numpy(x)
  35. return x
  36.  
  37. # 重新载入数据集,申明定义的数据变换
  38. train_set = mnist.MNIST('./data', train=True, transform=data_tf, download=True)
  39. test_set = mnist.MNIST('./data', train=False, transform=data_tf, download=True)
  40.  
  41. train_data = DataLoader(train_set, batch_size=64, shuffle=True)
  42. test_data = DataLoader(test_set, batch_size=128, shuffle=False)
  43.  
  44. class multi_network(nn.Module):
  45. def __init__(self):
  46. super(multi_network, self).__init__()
  47. self.layer1 = nn.Linear(784, 100)
  48. self.relu = nn.ReLU(True)
  49. self.layer2 = nn.Linear(100, 10)
  50.  
  51. self.gamma = nn.Parameter(torch.randn(100))
  52. self.beta = nn.Parameter(torch.randn(100))
  53.  
  54. self.moving_mean = Variable(torch.zeros(100))
  55. self.moving_var = Variable(torch.zeros(100))
  56.  
  57. def forward(self, x, is_train=True):
  58. x = self.layer1(x)
  59. x = batch_norm_1d(x, self.gamma, self.beta, is_train, self.moving_mean, self.moving_var)
  60. x = self.relu(x)
  61. x = self.layer2(x)
  62. return x
  63.  
  64. net = multi_network()
  65. # 定义 loss 函数
  66. criterion = nn.CrossEntropyLoss()
  67. # 使用随机梯度下降,学习率 0.1
  68. optimizer = torch.optim.SGD(net.parameters(), 1e-1)
  69.  
  70. def get_acc(output, label):
  71. total = output.shape[0]
  72. _, pred_label = output.max(1)
  73. num_correct = (pred_label == label).sum().item()
  74. return num_correct / total
  75.  
  76. #定义训练函数
  77. def train(net, train_data, valid_data, num_epochs, optimizer, criterion):
  78. if torch.cuda.is_available():
  79. net = net.cuda()
  80. prev_time = datetime.now()
  81. for epoch in range(num_epochs):
  82. train_loss = 0
  83. train_acc = 0
  84. net = net.train()
  85. for im, label in train_data:
  86. if torch.cuda.is_available():
  87. im = Variable(im.cuda()) # (bs, 3, h, w)
  88. label = Variable(label.cuda()) # (bs, h, w)
  89. else:
  90. im = Variable(im)
  91. label = Variable(label)
  92. # forward
  93. output = net(im)
  94. loss = criterion(output, label)
  95. # backward
  96. optimizer.zero_grad()
  97. loss.backward()
  98. optimizer.step()
  99. train_loss += loss.item()
  100. train_acc += get_acc(output, label)
  101.  
  102. cur_time = datetime.now()
  103. h, remainder = divmod((cur_time - prev_time).seconds, 3600)
  104. m, s = divmod(remainder, 60)
  105. time_str = "Time %02d:%02d:%02d" % (h, m, s)
  106. if valid_data is not None:
  107. valid_loss = 0
  108. valid_acc = 0
  109. net = net.eval()
  110. for im, label in valid_data:
  111. if torch.cuda.is_available():
  112. im = Variable(im.cuda())
  113. label = Variable(label.cuda())
  114. else:
  115. im = Variable(im, volatile=True)
  116. label = Variable(label, volatile=True)
  117. output = net(im)
  118. loss = criterion(output, label)
  119. valid_loss += loss.item()
  120. valid_acc += get_acc(output, label)
  121. epoch_str = (
  122. "Epoch %d. Train Loss: %f, Train Acc: %f, Valid Loss: %f, Valid Acc: %f, "
  123. % (epoch, train_loss / len(train_data),
  124. train_acc / len(train_data), valid_loss / len(valid_data),
  125. valid_acc / len(valid_data)))
  126. else:
  127. epoch_str = ("Epoch %d. Train Loss: %f, Train Acc: %f, " %
  128. (epoch, train_loss / len(train_data),
  129. train_acc / len(train_data)))
  130. prev_time = cur_time
  131. print(epoch_str + time_str)
  132.  
  133. print("使用自编写的批正则层:")
  134. train(net, train_data, test_data, 10, optimizer, criterion)
  135.  
  136. #################################################
  137. print(net.moving_mean[:10])
  138. no_bn_net = nn.Sequential(
  139. nn.Linear(784, 100),
  140. nn.ReLU(True),
  141. nn.Linear(100, 10)
  142. )
  143.  
  144. optimizer = torch.optim.SGD(no_bn_net.parameters(), 1e-1) # 使用随机梯度下降,学习率 0.1
  145.  
  146. print("未使用批正则层")
  147. train(no_bn_net, train_data, test_data, 10, optimizer, criterion)

cnn   二维批正则:

  1. #!/usr/bin/env python3
  2. #encoding:UTF-8
  3.  
  4. import torch
  5. import numpy as np
  6. import torch.nn.functional as F
  7. from torch import nn
  8. from torch.autograd import Variable
  9. from torchvision.datasets import mnist # 导入 pytorch 内置的 mnist 数据
  10. from torch.utils.data import DataLoader
  11. from datetime import datetime
  12.  
  13. def data_tf(x):
  14. x = np.array(x, dtype='float32') / 255
  15. x = (x - 0.5) / 0.5 # 数据预处理,标准化
  16. x = torch.from_numpy(x)
  17. x = x.unsqueeze(0)
  18. return x
  19.  
  20. train_set = mnist.MNIST('./data', train=True, transform=data_tf, download=True) # 重新载入数据集,申明定义的数据变换
  21. test_set = mnist.MNIST('./data', train=False, transform=data_tf, download=True)
  22. train_data = DataLoader(train_set, batch_size=64, shuffle=True)
  23. test_data = DataLoader(test_set, batch_size=128, shuffle=False)
  24.  
  25. def get_acc(output, label):
  26. total = output.shape[0]
  27. _, pred_label = output.max(1)
  28. num_correct = (pred_label == label).sum().item()
  29. return num_correct / total
  30.  
  31. criterion = nn.CrossEntropyLoss()
  32.  
  33. #定义训练函数
  34. def train(net, train_data, valid_data, num_epochs, optimizer, criterion):
  35. if torch.cuda.is_available():
  36. net = net.cuda()
  37. prev_time = datetime.now()
  38. for epoch in range(num_epochs):
  39. train_loss = 0
  40. train_acc = 0
  41. net = net.train()
  42. for im, label in train_data:
  43. if torch.cuda.is_available():
  44. im = Variable(im.cuda()) # (bs, 3, h, w)
  45. label = Variable(label.cuda()) # (bs, h, w)
  46. else:
  47. im = Variable(im)
  48. label = Variable(label)
  49. # forward
  50. output = net(im)
  51. loss = criterion(output, label)
  52. # backward
  53. optimizer.zero_grad()
  54. loss.backward()
  55. optimizer.step()
  56. train_loss += loss.item()
  57. train_acc += get_acc(output, label)
  58.  
  59. cur_time = datetime.now()
  60. h, remainder = divmod((cur_time - prev_time).seconds, 3600)
  61. m, s = divmod(remainder, 60)
  62. time_str = "Time %02d:%02d:%02d" % (h, m, s)
  63. if valid_data is not None:
  64. valid_loss = 0
  65. valid_acc = 0
  66. net = net.eval()
  67. for im, label in valid_data:
  68. if torch.cuda.is_available():
  69. im = Variable(im.cuda())
  70. label = Variable(label.cuda())
  71. else:
  72. im = Variable(im, volatile=True)
  73. label = Variable(label, volatile=True)
  74. output = net(im)
  75. loss = criterion(output, label)
  76. valid_loss += loss.item()
  77. valid_acc += get_acc(output, label)
  78. epoch_str = (
  79. "Epoch %d. Train Loss: %f, Train Acc: %f, Valid Loss: %f, Valid Acc: %f, "
  80. % (epoch, train_loss / len(train_data),
  81. train_acc / len(train_data), valid_loss / len(valid_data),
  82. valid_acc / len(valid_data)))
  83. else:
  84. epoch_str = ("Epoch %d. Train Loss: %f, Train Acc: %f, " %
  85. (epoch, train_loss / len(train_data),
  86. train_acc / len(train_data)))
  87. prev_time = cur_time
  88. print(epoch_str + time_str)
  89.  
  90. class conv_bn_net(nn.Module):
  91. def __init__(self):
  92. super(conv_bn_net, self).__init__()
  93. self.stage1 = nn.Sequential(
  94. nn.Conv2d(1, 6, 3, padding=1),
  95. nn.BatchNorm2d(6),
  96. nn.ReLU(True),
  97. nn.MaxPool2d(2, 2),
  98. nn.Conv2d(6, 16, 5),
  99. nn.BatchNorm2d(16),
  100. nn.ReLU(True),
  101. nn.MaxPool2d(2, 2)
  102. )
  103.  
  104. self.classfy = nn.Linear(400, 10)
  105. def forward(self, x):
  106. x = self.stage1(x)
  107. x = x.view(x.shape[0], -1)
  108. x = self.classfy(x)
  109. return x
  110.  
  111. net = conv_bn_net()
  112. optimizer = torch.optim.SGD(net.parameters(), 1e-1) # 使用随机梯度下降,学习率 0.1
  113. train(net, train_data, test_data, 5, optimizer, criterion)
  114.  
  115. #################################################
  116.  
  117. class conv_no_bn_net(nn.Module):
  118. def __init__(self):
  119. super(conv_no_bn_net, self).__init__()
  120. self.stage1 = nn.Sequential(
  121. nn.Conv2d(1, 6, 3, padding=1),
  122. nn.ReLU(True),
  123. nn.MaxPool2d(2, 2),
  124. nn.Conv2d(6, 16, 5),
  125. nn.ReLU(True),
  126. nn.MaxPool2d(2, 2)
  127. )
  128.  
  129. self.classfy = nn.Linear(400, 10)
  130. def forward(self, x):
  131. x = self.stage1(x)
  132. x = x.view(x.shape[0], -1)
  133. x = self.classfy(x)
  134. return x
  135.  
  136. net = conv_no_bn_net()
  137. optimizer = torch.optim.SGD(net.parameters(), 1e-1) # 使用随机梯度下降,学习率 0.1
  138. train(net, train_data, test_data, 5, optimizer, criterion)

【转载】 pytorch之添加BN的更多相关文章

  1. [转载]PyTorch上的contiguous

    [转载]PyTorch上的contiguous 来源:https://zhuanlan.zhihu.com/p/64551412 这篇文章写的非常好,我这里就不复制粘贴了,有兴趣的同学可以去看原文,我 ...

  2. [转载]PyTorch中permute的用法

    [转载]PyTorch中permute的用法 来源:https://blog.csdn.net/york1996/article/details/81876886 permute(dims) 将ten ...

  3. [转载]Pytorch详解NLLLoss和CrossEntropyLoss

    [转载]Pytorch详解NLLLoss和CrossEntropyLoss 来源:https://blog.csdn.net/qq_22210253/article/details/85229988 ...

  4. [转载]Pytorch中nn.Linear module的理解

    [转载]Pytorch中nn.Linear module的理解 本文转载并援引全文纯粹是为了构建和分类自己的知识,方便自己未来的查找,没啥其他意思. 这个模块要实现的公式是:y=xAT+*b 来源:h ...

  5. 【转载】 Pytorch(1) pytorch中的BN层的注意事项

    原文地址: https://blog.csdn.net/weixin_40100431/article/details/84349470 ------------------------------- ...

  6. 【转载】Pyqt 添加右键菜单方法

    转载地址: http://www.cnblogs.com/yogalau/p/3954042.html?utm_source=tuicool QListWidget 是继承 QWidget 的, 所以 ...

  7. 【转载】LoadRunner添加windows多台压力机

    添加多台压力机 1.前置条件 1)保证压力机上都安装了loadrunner Agent,并启动,状态栏中会有小卫星. 2)添加的压力机与controller所在机器是否在同一个网段,建议关闭防火墙.在 ...

  8. 【转载】 详解BN(Batch Normalization)算法

    原文地址: http://blog.csdn.net/hjimce/article/details/50866313 作者:hjimce ------------------------------- ...

  9. 转载:mysql添加用户、删除用户、授权、修改密码

    mysql添加用户.删除用户.授权.修改密码等 MySql中添加用户,新建数据库,用户授权,删除用户,修改密码1.新建用户. //登录MYSQL @>mysql -u root -p @> ...

随机推荐

  1. noip2013转圈游戏

    题目描述 n个小伙伴(编号从 0到 n−1)围坐一圈玩游戏.按照顺时针方向给 n个位置编号,从0 到 n−1.最初,第 0号小伙伴在第 0号位置,第 1号小伙伴在第 1 号位置,……,依此类推. 游戏 ...

  2. Struts 2 初步入门(五)之接受参数

    1.使用action的属性接受参数 执行顺序为:前端提交参数--->LoginAction.do进行处理--->处理成功后,跳转到sucess.jsp文件. (1)新建login.jsp文 ...

  3. vs 编译库文件

    vs编译的库文件 静态库  debug和release版本 需要分开编译,我编译和实践的结果. 但是我也发现有的debug release都用同一个(搞不清楚). 然后添加到工程应用. 静态库  附件 ...

  4. numpy ndarray

    >>> aarray([[1, 2], [3, 4]])>>> a.shape(2, 2)>>> barray([2, 3])>>&g ...

  5. ubuntu shell编程笔记

    and 命令 if  [   A  -a   B ] then else fi while [ ] do done set command set  these are parameters $1 s ...

  6. 整数中1出现的次数(1~n)

    题目描述 求出1~13的整数中1出现的次数,并算出100~1300的整数中1出现的次数?为此他特别数了一下1~13中包含1的数字有1.10.11.12.13因此共出现6次,但是对于后面问题他就没辙了. ...

  7. console.log()显示图片以及为文字加样式

    有兴趣的同学可以文章最后的代码复制贴到控制台玩玩. Go for Code 在正常模式下,一般只能向console 控制台输出简单的文字信息.但为了把信息输出得更优雅更便于阅读,除了cosole.lo ...

  8. markdown语法模板

    (GitHub-Flavored) Markdown Editor Basic useful feature list: Ctrl+S / Cmd+S to save the file Ctrl+Sh ...

  9. [POJ2985]The k-th Largest Group

    Problem 刚开始,每个数一个块. 有两个操作:0 x y 合并x,y所在的块 1 x 查询第x大的块 Solution 用并查集合并时,把原来的大小删去,加上两个块的大小和. Notice 非旋 ...

  10. 【资料搜集】Python学习

    python学习手册 | 演道网 http://dev.go2live.cn/python/python%e5%ad%a6%e4%b9%a0%e6%89%8b%e5%86%8c.html