Add some optional layer to the last layers of pretrained model

Hi, I am trying to add some layer to the resnet18 pre-trained network using this code.
class T(nn.Module):
def init(self, class_num):
super(T, self).init()
self.base = models.resnet18(pretrained=True)
self.sigmoid = nn.Sigmoid()
self.class_num = class_num
self.num_ftrs = self.base.fc.in_features

    self.linear = nn.Linear(10,1)

def freez(self, net):
    ct = 0
    for child in net.children():
        ct += 1
        if ct < 7:
            for param in child.parameters():
                param.requires_grad = False
def fc(self, net):
    net.fc =  nn.Linear(self.num_ftrs, self.class_num)
    return net               

def one_forward(self, x):
    self.base = self.freez(models.resnet18(pretrained=True))
    print(self.base)
    self.base = self.fc(self.base)
    net = self.sigmoid(self.base)
    out = net(x)
    return out

I’ve got this error
Exception has occurred: AttributeError

‘NoneType’ object has no attribute ‘fc’

how can I handle it?
any help would be appreciated.

Hi S!

As posted, freez() has no return statement, so, in effect, it returns None.
You set self.base to freez(), that is, None and call self.fc(self.base)
which tries to evaluate net.fc (i.e., self.base.fc), but net (self.base)
is None, hence the error.

Best.

K. Frank

1 Like

Hi @KFrank, thank you so much. how about this issue, I want add sigmid function just after the last fully connected layer of resnet18 so the follow code is added:
net = self.simoid(self.base)

but It cause an error
Exception has occurred: TypeError
sigmoid(): argument ‘input’ (position 1) must be Tensor, not ResNet

Hi S!

The error message is self-explanatory.

self.base is a ResNet, not a Tensor, so you can’t apply the sigmoid()
function to it.

But more to the point, why would you expect that calling
self.sigmoid (self.base) would add a layer to your network?

Try writing your own very simple network from scratch, and then experiment
with ways to add layers to it. If you still have questions, please post them
with complete sample code for your toy model.

Best.

K. Frank