pytorch 网络构建
import torch
torch.manual_seed(0)
torch.backends.cudnn.deterministic= False
torch.backends.cudnn.benchmark = True
import torchvision.models as models
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
from torch.utils.data.dataset import Dataset
一、pytorch常用网络
1.Linear介绍 [全连接层]
nn.Linear(input_feature,out_feature,bias=True)
2.卷积介绍 [2D卷积层]
nn.Conv2d(in_channels,out_channels,kernel_size,stride=1,padding=0,
dilation=1,groups,bias=True,padding_mode='zeros')
##kernel_size,stride,padding 都可以是元组
## dilation 为在卷积核中插入的数量
3.转置卷积介绍 [2D反卷积层]
nn.ConvTranspose2d(in_channels,out_channels,kernel_size,stride=1,
padding=0,out_padding=0,groups=1,bias=True,dilation=1,padding_mode='zeros')
##padding是输入填充,out_padding填充到输出
4.最大值池化层 [2D池化层]
nn.MaxPool2d(kernel_size,stride=None,padding=0,dilation=1)
4.批量归一化层 [2D归一化层]
nn.BatchNorm2d(num_features,eps,momentum,affine=True,
track_running_stats=True)
affine=True 表示批量归一化的α,β是被学到的
track_running_stats=True 表示对数据的统计特征进行关注
https://www.jianshu.com/p/a646cbc913b4
二 pytorch 创建模型的四种方法
假设创建
卷积层–》Relu层–》池化层–》全连接层–》Relu层–》全连接层
# 导入包
import torch
import torch.nn.functional as F
from collections import OrderedDict
1.自定义型[定义在init,前向过程在forward]
class Net1(torch.nn.Module):
def __init__(self):
super(Net1, self).__init__()
self.conv1 = torch.nn.Conv2d(3, 32, 3, 1, 1)
self.dense1 = torch.nn.Linear(32 * 3 * 3, 128)
self.dense2 = torch.nn.Linear(128, 10)
def forward(self, x):
x = F.max_pool2d(F.relu(self.conv(x)),