pytorch取得nn.Sequentialの中間層出力

4960 ワード

nnについてSequential構造では,中間ネットワーク層の出力を取得するには,ループループループを用いて得ることができる.
import torch
import torch.nn as nn
model = nn.Sequential(
            nn.Conv2d(3, 9, 1, 1, 0, bias=False),
            nn.BatchNorm2d(9),
            nn.ReLU(inplace=True),
            nn.AdaptiveAvgPool2d((1, 1)),
        )
#       ReLu   
x = torch.rand([2, 3, 224, 224])
for i in range(len(model)):
    x = model[i](x)
    if i == 2:
        ReLu_out = x
print('ReLu_out.shape:
\t'
,ReLu_out.shape) print('x.shape:
\t'
,x.shape)

結果
ReLu_out.shape:
  torch.Size([2, 9, 224, 224])
x.shape:
  torch.Size([2, 9, 1, 1])