欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

BN层(Pytorch讲解)

时间:2023-04-26

# -*- coding: utf-8 -*-"""Untitled13.ipynbAutomatically generated by Colaboratory.Original file is located at https://colab.research.google.com/drive/1UmI0eZXtftAp8hd9A3cj4DhffZ7kw_x1"""from torch import nnimport torch"""## 2D的BN层"""rgb = torch.randn(1, 3, 2, 2) # (batchsize,channel,w,h)print(rgb)print(rgb.shape)conv = nn.Conv2d(3, 2, 1)x = conv(rgb)print(x)print(x.shape)bn = nn.BatchNorm2d(2)res = bn(x)print(res)print(res.shape)mean = x.mean(dim=0, keepdim=True).mean(dim=2, keepdim=True).mean(dim=3, keepdim=True)var = ((x - mean) ** 2).mean(dim=0, keepdim=True).mean(dim=2, keepdim=True).mean(dim=3, keepdim=True)x_hat = (x - mean) / torch.sqrt(var + 0.00001)x_hatbn2 = nn.BatchNorm1d(12)# With Learnable Parametersm = nn.BatchNorm1d(2,affine=False)input = torch.randn(2, 2)output = m(input)inputinput.shapeoutputprint(output.shape)mean = input.mean(dim=0)var = ((input - mean) ** 2).mean(dim=0)meanvartest = (input-mean)/ torch.sqrt(var + 1e-5)testm = nn.Linear(20, 30)input = torch.randn(128, 20)output = m(input)print(output.size())bn_layer = nn.BatchNorm1d(30,affine=False)o2 = bn_layer(output)o2.shape

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。