Talking about the meaning of nn.Sequential(*net[3: 5]) in pytorch

This article mainly introduces the meaning of nn.Sequential(*net[3: 5]) in pytorch. The article introduces it in detail through sample codes. It has a certain reference learning value for everyone's deep learning or work. Need Friends, follow the editor to learn together

see this in the code

1

2

3

4

5

6

7

8

9

10

11

12

13

14

1 class ResNeXt101(nn.Module):

    2 def __init__(self):

        3 super(ResNeXt101, self).__init__()

        4 net = resnext101()

        # print(os.getcwd(), net)

        5 net = list(net.children())  # net.children()得到resneXt 的表层网络

        # for i, value in enumerate(net):

        #     print(i, value)

        6 self.layer0 = nn.Sequential(net[:3])  # 将前三层打包0, 1, 2两层

        print(self.layer0)

        7 self.layer1 = nn.Sequential(*net[3: 5])  # 将3, 4两层打包

        8 self.layer2 = net[5]

        9 self.layer3 = net[6]

You can see that the sixth line in the code (remove the serial number by yourself, I typed it in)  self.layer0 = nn.Sequential(net[:3])and
the seventh line self.layer1 = nn.Sequential(*net[3: 5])
have a nn.Sequential(net[:3])
and nn.Sequential(*net[3: 5])
Today I won’t talk about nn.Sequential()usage, meaning, and function because I don’t really understand it. Shockingly, *net[3: 5]why should this thing be included? When “ * ”
the code is not included , the following problems will occur when running*

It means that the list is not a subclass, which means that the parameters are wrong

1

net = list(net.children())

This line of code is to take out each layer of the model to build a list, just try to print it yourself. The approximate output is [conv(),BatchNorm2d(), ReLU,MaxPool2d]to wait

A total of one element, and the general list is not the same.

When we fetch net[:3], the parameter passed in is a list, but *net[:3]when we use it, it passes in a single element

1

2

3

4

list1 = ["conv", ("relu", "maxing"), ("relu", "maxing", 3), 3]

list2 = [list1[:1]]

list3 = [*list1[:1]]

print("list2:{}, *list1[:2]:{}".format(list1[:1], *list1[:1]))

The result without ✳ is a list, and the one with ✳ is an element, so nn.Sequential(*net[3: 5])in *net[3: 5]is to nn.Sequential()pass multiple layers into this container.

So far, this article about the meaning of nn.Sequential(*net[3: 5]) in pytorch is introduced here. For more related pytorch nn.Sequential(*net[3: 5]) content, please search Read the previous articles of developpaer or continue to browse the related articles below. I hope you will support developpaer in the future!

Guess you like

Origin blog.csdn.net/qq_42514371/article/details/127825062