Pytorch 搭建神经网络(2)网络搭建
Pytorch 搭建网络
官方文档 中文 https://www.pytorchtutorial.com/docs/
官方文档 https://pytorch.org/docs/stable/index.html
1 神经网络
官方文档:https://pytorch.org/docs/1.8.1/nn.html
2 Containers框架
- 官方示例
1 | # 示例 |
- 简单尝试
1 | import torch |
3 stride & padding
torch.nn.functional.conv2d
1. stride
1 | import torch |
2. padding
对输入图像的填充
1 | output_padding1 = F.conv2d(input, kernel, padding=1, stride=2) |
4 卷积层
1. Convolution
2. 调用和参数
- 调用
1 | class torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros') |
- 参数
1 | # in_channels: 输入 |
- dilation
3. 简单原理
- in_channels & out_channels
4. 示例代码
1 | import torch |
1 | # 网络结构 |
1 | # 在tensorboard展示 |
如果希望卷积后,通道变多,但尺寸不变,则需要填充padding,公式
5 池化层
1. Pooling
2. 调用和参数
1 | torch.nn.MaxPool2d(kernel_size, stride=None, padding=0, dilation=1, return_indices=False, ceil_mode=False) |
- 注意输入的input和输出output均为
1 | (N, C, H, W) # (batch_size层数, Channel通道数, Height高, Width宽) |
- 注意池化不可对long操作,故
1 | input = torch.tensor([ |
3. 示例代码
1 | import torch |
6 非线性激活(激活函数)
1. Non-linear Activations
relu, sigmoid…
2. 调用和参数
1 | # 是否内存拷贝 |
3. 示例代码
1 | import torch |
7 正则化层
1. Normalization
2. 调用和参数
1 | torch.nn.BatchNorm2d(num_features, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) |
1 | - input - (N, C, H, W) |
3. 示例代码
1 | # With Learnable Parameters |
8 线性层
1. Linear
2. 调用和参数
1 | torch.nn.Linear(in_features, out_features, bias=True) |
3. 示例代码
1 | import torch |
9 pytorch提供的模型
https://pytorch.org/docs/1.8.1/nn.html
10 Sequential
1. Sequential简化
torch.nn -> container -> Sequential
1 | torch.nn.Sequential(*args) |
1 | # Example of using Sequential |
2. 案例:CIFAR分类
- CIFAR Model 结构
- Note: 计算padding和stride
- tensorboard可视化结构
1 | x_test = torch.ones((64, 3, 32, 32)) |
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来源 isKage`Blog!