Rainbow
Rainbow

Reputation: 301

How to change the first conv layer in the resnet 18?

I have a data with 20 class, and I'd like to use pretraied model with a bit of modification. I know if we want to change the last linear of ResNet18 to categorize 20 calss (instead of 1000); we could write the following:

resnet.fc = nn.linear(512,20)

But I don't know how to access to any other layers? Like the second convolution in Bacic block?

When I call resnet.layer1 it returns:

Sequential(
  (0): BasicBlock(
    (conv1): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
    (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
    (relu): ReLU(inplace=True)
    (conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
    (bn2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  )
  (1): BasicBlock(
    (conv1): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
    (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
    (relu): ReLU(inplace=True)
    (conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
    (bn2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  )
)

But how to grab and change conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)?

enter image description here

Upvotes: 0

Views: 939

Answers (1)

A.Mounir
A.Mounir

Reputation: 588

You can access to the layer (conv2) in sequential number (0) of layer.1 as follow:

from torchvision import datasets, transforms, models
resnet = models.resnet18(pretrained=True)
print(resnet.layer1[0].conv2)

Output:

Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), 
bias=False)

Upvotes: 1

Related Questions