I’m using vgg16 model. I got this error from the block of code
num_ftrs = model_ft.classifier[0].out_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)
######################################################################
Train and evaluate
^^^^^^^^^^^^^^^^^^

On CPU this will take about half the time compared to previous scenario.
This is expected as gradients don’t need to be computed for most of the
network. However, forward does need to be computed.

model_conv = train_model(model_conv, criterion, optimizer_conv,
exp_lr_scheduler, num_epochs=25)
######################################################################

visualize_model(model_conv)
plt.ioff()
plt.show()
RuntimeError                              Traceback (most recent call last)
 in ()
24
25 model_conv = train_model(model_conv, criterion, optimizer_conv,
—> 26                          exp_lr_scheduler, num_epochs=25)
27
28 ######################################################################
2 frames
/usr/local/lib/python3.6/dist-packages/torch/autograd/init.py in backward(tensors, grad_tensors, retain_graph, create_graph, grad_variables)
91     Variable._execution_engine.run_backward(
92         tensors, grad_tensors, retain_graph, create_graph,
—> 93         allow_unreachable=True)  # allow_unreachable flag
94
95
RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn
Can you please help me how to solve this issue?
Thanks