其他分享
首页 > 其他分享> > pytorch 官网教程 [神经网络] 笔记

pytorch 官网教程 [神经网络] 笔记

作者:互联网

官网中文文档 神经网络

核心代码

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


class Net(nn.Module):

    def __init__(self):
        super(Net, self).__init__()
        # 输入图像channel:1;输出channel:6;5x5卷积核
        self.conv1 = nn.Conv2d(1, 6, 5)
        self.conv2 = nn.Conv2d(6, 16, 5)
        # an affine operation: y = Wx + b
        self.fc1 = nn.Linear(16 * 5 * 5, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 10)

    def forward(self, x):
        # 2x2 Max pooling
        x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
        # 如果是方阵,则可以只使用一个数字进行定义
        x = F.max_pool2d(F.relu(self.conv2(x)), 2)
        x = x.view(-1, self.num_flat_features(x))
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x

    def num_flat_features(self, x):
        size = x.size()[1:]  # 除去批处理维度的其他所有维度
        num_features = 1
        for s in size:
            num_features *= s
        return num_features

查看可学习参数

params = list(net.parameters())
len(params)
params[0].size()  # conv1's .weight

输出

10
torch.Size([6, 1, 5, 5])

这 10 个参数分别是

conv1.weight	conv1.bias
conv2.weight    conv2.bias
fc1.weight      fc1.bias
fc2.weight      fc2.bias
fc3.weight      fc3.bias

如果想要详细查看,

params[0]
# 或
for parameter in net.named_parameters() :
	print(parameter)

conv1.weight 和 conv2.weight 的大小如下,分别表示 6 个 1 * 5 * 5 的卷积核,16 个 6 * 5 * 5 的卷积核

torch.Size([6, 1, 5, 5])
torch.Size([16, 6, 5, 5])

卷积过程

标签:nn,weight,self,torch,神经网络,pytorch,官网,conv1,features
来源: https://blog.csdn.net/weixin_43742643/article/details/112541979