pytorch基本学习

本文详细介绍了如何使用PyTorch搭建一个卷积神经网络(CNN),包括模型的定义、参数的设置以及前向传播过程。通过实例展示了CNN各层的参数大小,并输出了模型的结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import torch.nn as nn
import torch.nn.functional as F

class Net(nn.Module):
    def __init__(self):
        super(Net,self).__init__()
        self.conv1=nn.Conv2d(1,6,5)
        self.conv2=nn.Conv2d(6,16,5)
        self.fc1=nn.Linear(16*5*5,120)
        self.fc2=nn.Linear(120,84)
        self.fc3=nn.Linear(84,10)
    def forward(self,x):
        x=F.max_pool2d(F.relu(self.conv1(x)),(2,2))
        x=F.max_pool2d(F.relu(self.conv2(x)),2)
        x=x.view(x.size()[0],-1)
        print(x)
        x=F.relu(self.fc1(x))
        x=F.relu(self.fc2(x))
        x=self.fc3(x)
        return x
net=Net()
params=list(net.parameters())

#输出可学习参数的名称和可学习参数的size
for name,parameters in net.named_parameters():
    print(name,':',parameters.size())
print(len(params))#输出可学习参数的个数
print(net)  #输出模型
--------------------- 
作者:zouxiaolv 
来源:优快云 
原文:https://blog.youkuaiyun.com/zouxiaolv/article/details/83032779?utm_source=copy 
版权声明:本文为博主原创文章,转载请附上博文链接!

import torch.nn as nn
import torch.nn.functional as F

class Net(nn.Module):
    def __init__(self):
        super(Net,self).__init__()
        self.conv1=nn.Conv2d(1,6,5)
        self.conv2=nn.Conv2d(6,16,5)
        self.fc1=nn.Linear(16*5*5,120)
        self.fc2=nn.Linear(120,84)
        self.fc3=nn.Linear(84,10)
    def forward(self,x):
        x=F.max_pool2d(F.relu(self.conv1(x)),(2,2))
        x=F.max_pool2d(F.relu(self.conv2(x)),2)
        x=x.view(x.size()[0],-1)
        print(x)
        x=F.relu(self.fc1(x))
        x=F.relu(self.fc2(x))
        x=self.fc3(x)
        return x
net=Net()
params=list(net.parameters())

#输出可学习参数的名称和可学习参数的size
for name,parameters in net.named_parameters():
    print(name,':',parameters.size())
print(len(params))#输出可学习参数的个数
print(net)  #输出模型

print的结果:

('conv1.weight', ':', torch.Size([6, 1, 5, 5]))
('conv1.bias', ':', torch.Size([6]))
('conv2.weight', ':', torch.Size([16, 6, 5, 5]))
('conv2.bias', ':', torch.Size([16]))
('fc1.weight', ':', torch.Size([120, 400]))
('fc1.bias', ':', torch.Size([120]))
('fc2.weight', ':', torch.Size([84, 120]))
('fc2.bias', ':', torch.Size([84]))
('fc3.weight', ':', torch.Size([10, 84]))
('fc3.bias', ':', torch.Size([10]))
10
Net (
  (conv1): Conv2d(1, 6, kernel_size=(5, 5), stride=(1, 1))
  (conv2): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1))
  (fc1): Linear (400 -> 120)
  (fc2): Linear (120 -> 84)
  (fc3): Linear (84 -> 10)
)

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值