关于 Pytorch 几种定义网络的方法
机器学习与生成对抗网络
共 3753字,需浏览 8分钟
·
2021-07-08 21:07
点击上方“机器学习与生成对抗网络”,关注星标
获取有趣、好玩的前沿干货!
来源:知乎—ppgod
地址:https://zhuanlan.zhihu.com/p/80308275
import torch
import torch.nn as nn
from torch.autograd import Variable
from collections import OrderedDict
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(10,10)
self.relu1 = nn.ReLU(inplace=True)
self.fc2 = nn.Linear(10,2)
def forward(self,x):
x = self.fc1(x)
x = self.relu1(x)
x = self.fc2(x)
return x
这是最简单的定义一个网络的方法,但是当网络层数过多的时候,这么写未免太麻烦,于是Pytorch还有第二种定义网络的方法nn.ModuleList()
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.base = nn.ModuleList([nn.Linear(10,10), nn.ReLU(), nn.Linear(10,2)])
def forward(self,x):
x = self.base(x)
return x
base = [nn.Linear(10,10) for i in range(5)]
net = nn.ModuleList(base)
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.base = nn.Sequential(nn.Linear(10,10), nn.ReLU(), nn.Linear(10,2))
def forward(self,x):
x = self.base(x)
return x
class MultiLayerNN5(nn.Module):
def __init__(self):
super(MultiLayerNN5, self).__init__()
self.base = nn.Sequential(OrderedDict([
('0', BasicConv(1, 16, 5, 1, 2)),
('1', BasicConv(16, 32, 5, 1, 2)),
]))
self.fc1 = nn.Linear(32 * 7 * 7, 10)
def forward(self, x):
x = self.base(x)
x = x.view(x.size(0), -1)
x = self.fc1(x)
return x
class MultiLayerNN4(nn.Module):
def __init__(self):
super(MultiLayerNN4, self).__init__()
self.base = nn.Sequential()
self.base.add_module('0', BasicConv(1, 16, 5, 1, 2))
self.base.add_module('1', BasicConv(16, 32, 5, 1, 2))
self.fc1 = nn.Linear(32 * 7 * 7, 10)
def forward(self, x):
x = self.base(x)
x = x.view(x.size(0),-1)
x = self.fc1(x)
tt = [nn.Linear(10,10), nn.Linear(10,2)]
n_1 = nn.Sequential(*tt)
n_2 = nn.ModuleList(tt)
x = torch.rand([1,10,10])
x = Variable(x)
n_1(x)
n_2(x)#会出现NotImplementedError
class DenseLayer(nn.Sequential):
def __init__(self):
super(DenseLayer, self).__init__()
self.add_module("conv1", nn.Conv2d(1, 1, 1, 1, 0))
self.add_module("conv2", nn.Conv2d(1, 1, 1, 1, 0))
def forward(self, x):
new_features = super(DenseLayer, self).forward(x)
return torch.cat([x, new_features], 1)
#这个写法和下面的是一样的
class DenLayer1(nn.Module):
def __init__(self):
super(DenLayer1, self).__init__()
convs = [nn.Conv2d(1, 1, 1, 1, 0), nn.Conv2d(1, 1, 1, 1, 0)]
self.conv = nn.Sequential(*convs)
def forward(self, x):
return torch.cat([x, self.conv(x)], 1)
net = DenLayer1()
x = torch.Tensor([[[[1, 2], [3, 4]]]])
print(x)
x = Variable(x)
print(net(x))
猜您喜欢:
CVPR 2021 | GAN的说话人驱动、3D人脸论文汇总
附下载 |《TensorFlow 2.0 深度学习算法实战》
附下载 | 超100篇!CVPR 2020最全GAN论文梳理汇总!
评论