How to modify the final FC layer based on the torch.model

zhongtao93: <p>Hi, everyone.</p>
<p>I want to use the VGG19 in my own dataset, which has 8 classes.Ｓo I want to change the output of the last fc layer  to 8. So what should I do to change the last fc layer to fit it.</p>
<p>Thank you very much!</p>

panovr: <p>You can get the idea from this post <a href="https://discuss.pytorch.org/t/how-to-perform-finetuning-in-pytorch/419">https://discuss.pytorch.org/t/how-to-perform-finetuning-in-pytorch/419</a></p>

Ismail_Elezi: <p>Something like:</p>
<pre><code>model = torchvision.models.vgg19(pretrained=True)
for param in model.parameters():
    param.requires_grad = False
    # Replace the last fully-connected layer
    # Parameters of newly constructed modules have requires_grad=True by default
model.fc = nn.Linear(512, 8) # assuming that the fc7 layer has 512 neurons, otherwise change it 
model.cuda()</code></pre>

zhongtao93: <p>Thank you, I’ll try it!</p>

Ismail_Elezi: <p>Don’t forget to retrain the last layer though. At the moment the weights of it have just random numbers, so you must retrain it. You can do the retraining the same way as normal, the only change is that now the weights of the other layers won’t change because I set the requires_grad to False. If you have enough data to do a full training, then simply remove the line which does that, but it will surely take much longer to train.</p>

zhongtao93: <p>My torch==0.1.9 while torchvision==0.1.7, but the APIs of torchvision.models.vgg19() seems is different from the docs. Here is the <a href="http://error.It" rel="nofollow noopener">error.It</a>’s the version problem?<br>
I followed the solution from <a href="https://discuss.pytorch.org/t/pre-trained-vgg16/664">Pre-trained VGG16</a>, but it also has problem.</p>
<pre><code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
&lt;ipython-input-9-cbf958b7f4be&gt; in &lt;module&gt;()
      3 import torch.nn as nn
      4 import torch.nn.functional as F
----&gt; 5 model = torchvision.models.vgg19(pretrained=True)
      6 for param in model.parameters():
      7     param.requires_grad = False

TypeError: vgg19() takes no arguments (1 given)</code></pre>

Crazyai: <p>I ran into the same problem. I cloned the latest code  repos of <code>pytorch</code> and <code>pytorchvision</code> and built both manually.<br>
Or you can refer to <a href="https://discuss.pytorch.org/t/pre-trained-vgg16/664">this issue</a></p>

Ismail_Elezi: <p>Hmm, I didn’t try the code yesterday and just changed the line from a residual network.</p>
<p>Now I tried it, and got the same error as you. It seems that you can get just the model, but not the weights of it. Which actually contradicts the documentation when it is written that you can give the pretrained argument.</p>
<p>As <a class="mention" href="/u/crazyai">@Crazyai</a> said, you can refer to that issue and download the model from github. However, bear in mind that they are not planning to release the version with batch normalization. Alternately, use a residual network and finetune it, probably getting even better results than with VGG.</p>

apaszke: <p>Pretrained VGG models are a new thing. Updating <strong>torchvision</strong> to the newest version should fix it.</p>

zhongtao93: <p>I uninstalled the current torchvision, and rebulid the newest version, and it worked. Thank you very much!</p>

zhongtao93: <p>My network initialized as below:</p>
<pre><code>#VGG19
import torchvision
import torch.nn as nn
import torch.nn.functional as F
vgg19 = torchvision.models.vgg19(pretrained=True)
for param in vgg19.parameters():
    param.requires_grad = False
requires_grad=True by default
vgg19.fc = nn.Linear(1000, 8) neurons, otherwise change it 
vgg19.cuda()
import torch.optim as optim
criterion = nn.CrossEntropyLoss() 
optimizer = optim.SGD(vgg19.fc.parameters(), lr=0.001, momentum=0.9)#lr 0.001
</code></pre>
<p>But when I train with code as below, there is a error in <strong>loss.backward()</strong>:<br>
code</p>
<pre><code>        inputs, labels = Variable(inputs.cuda()), Variable(labels.cuda())
        # zero the parameter gradients
        optimizer.zero_grad()
        # forward + backward + optimize
        outputs = vgg19(inputs)
        #print(type(outputs),type(inputs))
        loss = criterion(outputs, labels)
        #loss = F.nll_loss(outputs, labels)
        loss.backward()        
        optimizer.step()
        step += 1
        # print statistics
        running_loss += loss.data[0]
</code></pre>
<p>error</p>
<p><code>RuntimeError: there are no graph nodes that require computing gradients</code></p>

Cysu: <p>That’s because vgg19 doesn’t have a <code>fc</code> member variable. Instead, it has a</p>
<pre><code class="lang-python">  (classifier): Sequential (
    (0): Dropout (p = 0.5)
    (1): Linear (25088 -&gt; 4096)
    (2): ReLU (inplace)
    (3): Dropout (p = 0.5)
    (4): Linear (4096 -&gt; 4096)
    (5): ReLU (inplace)
    (6): Linear (4096 -&gt; 100)
  )
</code></pre>
<p>To replace the last linear layer, a temporary solution would be</p>
<pre><code class="lang-python">vgg19.classifier._modules['6'] = nn.Linear(4096, 8)
</code></pre>

zhongtao93: <p>Thank you, then how should I change the last layer to <strong>param.requires_grad = True</strong></p>

Cysu: <p>Newly constructed layer has <code>requires_grad=True</code> by default. You don’t need to do it manually.</p>

micklexqg: <aside class="quote no-group" data-username="Cysu" data-post="12" data-topic="766">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/cysu/48/113_2.png" class="avatar"> Cysu:</div>
<blockquote>
<p>To replace the last linear layer</p>
</blockquote>
</aside>
<p>thank you. what should I change if I want to  add dropout in ‘fc’? the last classifier layer has been changed in terms of the number of classes and I want to add dropout before it.</p>

chenglu: <p>There’s already a dropout layer before the final FC layer, the code is</p>
<pre><code class="lang-auto">        self.classifier = nn.Sequential(
            nn.Linear(512 * 7 * 7, 4096),
            nn.ReLU(True),
            nn.Dropout(),
            nn.Linear(4096, 4096),
            nn.ReLU(True),
            nn.Dropout(),
            nn.Linear(4096, num_classes),
        )
</code></pre>
<p>you only need to replace the last 4096, num_classes to your own fc layer.</p>

Praveen_raja_sekar: <p>i am trying to convert the classification network to regression netowork by replacing the last layer with number of outputs as one can you please suggest any solution ay help would be greatly appreciated i am new to pytorch</p>

ptrblck: <p>You can just do exactly this by setting the last layer as:</p>
<pre><code class="lang-python">nn.Linear(4096, 1)
</code></pre>
<p>In your training procedure you probably want to use <code>nn.MSELoss</code> as your criterion.</p>

Praveen_raja_sekar: <p>Hi ,<br>
Thank you for your response. However, i tried that here is my code but the model returns nothing</p>
<pre><code class="lang-python">class FineTuneModel(nn.Module):
    def __init__(self, original_model, num_classes):
        super(FineTuneModel, self).__init__()
        # Everything except the last linear layer
        self.features = nn.Sequential(*list(original_model.children())[:-1])
        self.classifier = nn.Sequential(
            nn.Linear(512, 1)
        )
        self.modelName = 'LightCNN-29'
        # Freeze those weights
        for p in self.features.parameters():
            p.requires_grad = False


    def forward(self, x):
        f = self.features(x)        
        f = f.view(f.size(0), -1)
        y = self.classifier(f)
        return y

model = FineTuneModel(original_model, args.num_classes)
print(model)
</code></pre>
<p>Output:</p>
<pre><code class="lang-python">FineTuneModel(
  (features): Sequential()
  (classifier): Sequential(
    (0): Linear(in_features=512, out_features=1, bias=True)
  )
)
</code></pre>
<p>original model is pretrained resnet model</p>

Praveen_raja_sekar: <pre><code class="lang-python">class FineTuneModel(nn.Module):
    def __init__(self, original_model, num_classes):
        super(FineTuneModel, self).__init__()
        # Everything except the last linear layer
        self.features = nn.Sequential(*list(original_model.children())[:-1])
        self.classifier = nn.Sequential(
            nn.Linear(512, 1)
        )
        self.modelName = 'LightCNN-29'
        # Freeze those weights
        for p in self.features.parameters():
            p.requires_grad = False


    def forward(self, x):
        f = self.features(x)        
        f = f.view(f.size(0), -1)
        y = self.classifier(f)
        return y
</code></pre>