【pytorch学习笔记】ModuleList()

本文详细介绍了PyTorch中nn.Linear模块的使用,包括其在全连接层中的作用,输入输出张量的形状转换。同时,讲解了nn.ModuleList的用法,展示了如何在自定义模块中利用ModuleList存储和操作多个线性层。通过实例代码,阐述了ModuleList作为可迭代对象的特性。
摘要由CSDN通过智能技术生成

torch.nn.Linear

pytorch中的nn.Linear()是用来设置网络全连接层的,在二维图像处理的任务中,全连接层的输入与输出一般都设置为二维张量,形状通常为[batch_size, size],不同于卷积层要求输入输出是四维张量。用法与形参说明如下:
在这里插入图片描述
in_features——输入二维张量大小,即输入的[batch_size, size]中的size
out_features——输出二维张量大小,即输出的二维张量的形状为[batch_size,output_size],也代表了该全连接层的神经元个数。
从输入输出的张量的shape角度来理解,相当于一个输入为[batch_size, in_features]的张量变换成了[batch_size, out_features]的输出张量。

import torch
from torch import nn

# in_features由输入张量的形状决定,out_features则决定了输出张量的形状 
connected_layer = nn.Linear(in_features = 64*64*3, out_features = 1)

# 假定输入的图像形状为[64,64,3]
input = torch.randn(1,64,64,3)

# 将四维张量转换为二维张量之后,才能作为全连接层的输入
input = input.view(1, 64*64*3)
print(input.shape)  #torch.Size([1, 12288])
output = connected_layer(input) # 调用全连接层
print(output.shape)  # torch.Size([1, 1])

ModuleList

顾名思义,专门用于存储module的list。

import torch
import torch.nn as nn
class MyModule(nn.Module):
    def __init__(self):
        super(MyModule, self).__init__()
        self.linears = nn.ModuleList([nn.Linear(10, 10) for i in range(10)])

    def forward(self, x):
        # ModuleList can act as an iterable, or be indexed using ints
        for i, l in enumerate(self.linears):
            x = self.linears[i // 2](x) + l(x)
        return x
test_module = MyModule()
test_module.train()
input = torch.tensor(range(10), dtype=torch.float)
out = test_module(input)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值