基于Pytorch的网络设计语法2

发布时间 2024-01-03 14:18:31作者: wenluderen
import  torch.nn as nn
import  torch.functional as F
import  torch.optim as optim
from collections  import OrderedDict

class Net2(nn.Module):# 从nn.Module  继承
    def __init__(self):# 在类的初始化函数里完成曾的构建
        super(Net2,self).__init__()
        #Sequential里面的顺序 就是前往传播的顺序
        self.conv=nn.Sequential(
            nn.Conv2d(3,32,3,1,1),
            nn.ReLU(),
            nn.MaxPool2d(2))
        self.dense= nn.Sequential(
            nn.Linear(32*3*3,128),
            nn.ReLU(),
            nn.Linear(128,10)
             )
    def forward(self,input_x):# 构建前向传播的流程
        conv_out=self.conv(input_x)
        res=conv_out.view(conv_out.size(0),-1)#拉伸处理
        out =self.dense(res)

        return  out

gsznet = Net2()
print(gsznet)
if __name__ == '__main__':
    print("XXXXXXXXXXXXXX")

  输出结果

C:\Users\ai\AppData\Local\Programs\Python\Python38\python.exe E:\yousan.ai-master\computer_vision\projects\classification\pytorch\simpleconv3\设计网络.py
Net2(
(conv): Sequential(
(0): Conv2d(3, 32, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(1): ReLU()
(2): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
)
(dense): Sequential(
(0): Linear(in_features=288, out_features=128, bias=True)
(1): ReLU()
(2): Linear(in_features=128, out_features=10, bias=True)
)
)
XXXXXXXXXXXXXX

进程已结束,退出代码为 0

 

 

 

优点 打印出来的 顺序 和前往传播的顺序   基本一致