pytorch使用自定义网络

1、定义网络结构

import torch.nn as nn

import torch.nn.functional as F

class Model(nn.Module):

     def __init__(self):

          super(Model,self).__init__()

          self.conv1=nn.Conv2d(1,20,5)

          self.conv2=nn.Conv2d(20,20,5)

    def forward(self,x):

          x=F.relu(self.conv1(x))

          return F.relu(self.conv2(x))

这个例子定义了一个只有两层的网络Model,其中两个函数:

--初始化函数 __init__(self):定义了具体网络有什么层,这里实际上没有决定网络的结构,也就是说将上面的例子中的self.conv1和self.conv2定义的前后顺序调换是完全没有影响的。

--forward函数定义了网络的前向传播的顺序

2、网络参数初始化

pytorch官方提供了多种初始化函数

torch.nn.init.uniform(tensor,a=0,b=1)

torch.nn.init.normal(tensor,mean=0,std=1)

torch.nn.init.constant(tensor,val)

torch.nn.init.xavier_uniform(tensor,gain=1)

初始化函数可以直接作用于神经网络参数

1、对网络的某一层参数进行初始化

import torch.nn as nn

import torch.nn.init as init

conv1=nn.Conv2d(3,64,kernel_size=7,stride=2,padding=3)

init.xavier _uniform(conv1.weight)

init.constant(conv1.bas,0.1)

2、对整个网络的参数进行初始化

def weights_init(m):

    if isinstance(m,nn.Conv2d):

        xavier(m.weight.data)

        xavier(m.bias.data)

下面举一个例子,定义一个网络MyNet,网络由6层的卷积构成:

import torch
import torch.nn as nn
import torch.nn.init as init

class MyNet(nn.Module):
    def __init__(self):
        super(MyNet,self).__init__()
        self.conv1=nn.ReLU(inplace=True)
        self.relu1=nn.ReLU(inplace=True)
        self.conv2=nn.Conv2d(64,128,7,padding=3)
        self.relu2=nn.ReLU(inplace=True)
        self.conv3=nn.Conv2d(128,256,5,padding=2)
        self.relu3=nn.ReLU(inplace=True)
        self.conv4=nn.Conv2d(256,128,5,padding=2)
        self.relu4=nn.ReLU(inplace=True)
        self.conv5=nn.conv2d(128,64,3,padding=1)
        self.relu5=nn.ReLU(inplace=True)
        self.conv6=nn.conv2d(64,6,3,padding=1)
        self.relu6=nn.ReLU(inplace=True)

        for m in self.modules():
            if isinstance(m,nn.Conv2d):
                init.xavier_uniform(m.weight.data)
                init.constant(m.bias.data,0.1)

        def forward(self,x):
            x=self.relu1(self.conv1(x))
            x=self.relu2(self.conv2(x))
            x=self.relu3(self.conv3(x))
            x=self.relu4(self.conv4(x))
            x=self.relu5(self.conv5(x))
            f=self.relu6(self.conv6(x))
            return f

 

 

你可能感兴趣的:(深度学习,pytorch,搭建网络)