AttributeError: 'EfficientNet' object has no attribute 'fc'

username: Schroter
cooked: <p>Hi All,</p>
<p>I am trying to create an image classifier using this [tutorial]. (<a href="https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html" class="inline-onebox" rel="noopener nofollow ugc">Transfer Learning for Computer Vision Tutorial — PyTorch Tutorials 1.13.1+cu117 documentation</a>) In my case I am trying to use the <code>EfficientNet</code> model. I plugged the regent model instead of the <code>resnet</code> model used in the tutorial. However, I get an error for the code. Please find the code below and the respective error.</p>
<pre><code class="lang-auto">#model_conv = torchvision.models.regnet_y_32gf(weights = 'RegNet_Y_32GF_Weights.IMAGENET1K_SWAG_E2E_V1')
model_conv = torchvision.models.efficientnet_b7(weights = 'EfficientNet_B7_Weights.IMAGENET1K_V1')

for param in model_conv.parameters():
    param.requires_grad = False

# Parameters of newly constructed modules have requires_grad=True by default
num_ftrs = model_conv.fc.in_features
model_conv.fc = nn.Linear(num_ftrs, 2)

model_conv = model_conv.to(device)

criterion = nn.CrossEntropyLoss()

# Observe that only parameters of final layer are being optimized as
# opposed to before.
optimizer_conv = optim.SGD(model_conv.fc.parameters(), lr=0.001, momentum=0.9)

# Decay LR by a factor of 0.1 every 7 epochs
exp_lr_scheduler = lr_scheduler.StepLR(optimizer_conv, step_size=7, gamma=0.1)
</code></pre>
<p>Error:</p>
<pre><code class="lang-auto">---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
/tmp/ipykernel_23/272062303.py in &lt;module&gt;
      6 
      7 # Parameters of newly constructed modules have requires_grad=True by default
----&gt; 8 num_ftrs = model_conv.fc.in_features
      9 model_conv.fc = nn.Linear(num_ftrs, 2)
     10 

/opt/conda/lib/python3.7/site-packages/torch/nn/modules/module.py in __getattr__(self, name)
   1264                 return modules[name]
   1265         raise AttributeError("'{}' object has no attribute '{}'".format(
-&gt; 1266             type(self).__name__, name))
   1267 
   1268     def __setattr__(self, name: str, value: Union[Tensor, 'Module']) -&gt; None:

AttributeError: 'EfficientNet' object has no attribute 'fc'
</code></pre>
<p>Would anyone be able to help me in this matter.<br>
Thanks &amp; Best Regards<br>
AMJS</p>

username: ptrblck
cooked: <p>You would have to use the <code>.classifier</code> attribute as torchvision’s EfficientNet implementations don’t use the <code>.fc</code> attribute name.</p>

username: Schroter
cooked: <p>Hi,<br>
Thanks for the reply. However, when I replace <code>.fc</code> with <code>.classifier</code> I get the following error.</p>
<pre><code class="lang-auto">AttributeError: 'Sequential' object has no attribute 'in_features'
</code></pre>
<p>Would you be able to help me in this matters please.<br>
Thanks &amp; Best Regards<br>
AMJS</p>

username: J_Johnson
cooked: <pre><code class="lang-auto">self.classifier = nn.Sequential(
            nn.Dropout(p=dropout, inplace=True),
            nn.Linear(lastconv_output_channels, num_classes),
        )
</code></pre>
<p>This is what it is in the code. If you want the Linear layer’s number of features, you might need to use an index of 1:</p>
<pre><code class="lang-auto">num_ftrs = model_conv.classifier[1].in_features
</code></pre>