4.1自定义神经网络

自定义神经网络

pytorch自定义神经网络的方法是重写nn.Module函数,来自于from torch import nn。下面是具体实践。

class CNN(nn.Module):
    def __init__(self,num_classes):
        super(CNN, self).__init__() # 3 64 64
        self.layer1=nn.Sequential(
            torch.nn.Conv2d(
                in_channels=3,
                out_channels=16,
                kernel_size=5,
                stride=2,
                padding=2
            ),
            # nn.Conv2d(3, 16, 3),
            nn.BatchNorm2d(16),
            nn.Sigmoid(),
            nn.MaxPool2d(kernel_size=2,stride=2) #16 32 32\\
        )
        self.layer2=nn.Sequential(
            torch.nn.Conv2d(
                in_channels=16,
                out_channels=32,
                kernel_size=5,
                stride=2,
                padding=2
            ),
            # nn.Conv2d(16, 32, 3, 2),
            nn.BatchNorm2d(32),
            nn.Sigmoid(),
            nn.MaxPool2d(kernel_size=2,stride=2) #32 16 16
        )
        # self.layer3=nn.Sequential(
        #     nn.Conv2d(
        #         in_channels=32,
        #         out_channels=32,
        #         kernel_size=3,
        #         stride=2,
        #         padding=2
        #     ),
        #     # nn.Conv2d(32,32,3,2),
        #     nn.BatchNorm2d(32),
        #     nn.Sigmoid(),
        #     nn.MaxPool2d(kernel_size=2,stride=2) #32 8 8
        # )
        self.fc1=nn.Sequential(
            nn.Linear(32*14*14,120),
            nn.Sigmoid()
        )
        self.fc2=nn.Sequential(
            nn.Linear(120,84),
            nn.Sigmoid(),
            nn.Linear(84,num_classes)
        )
    # 前向传播
    def forward(self,x):
        # print('1 output shape:\t', x.shape)
        x=self.layer1(x)
        # print('2 output shape:\t', x.shape)
        x=self.layer2(x)
        # print('3 output shape:\t', x.shape)
        # x=self.layer3(x)
        # print('4 output shape:\t', x.shape)
        x=x.view(x.size(0),-1)
        # print('5 output shape:\t', x.shape)
        x=self.fc1(x)
        # print('6 output shape:\t', x.shape)
        x=self.fc2(x)
        # print('7 output shape:\t', x.shape)
        return 
#实例化模型
models = CNN(config.num_classes)

需要注意前向传播的输入输出通道需要一致

卷积神神经网络通道变化的计算方法:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值