Model not training

Shiv: <p>Hi. I am moving from keras to pytorch. My code is running fine but the model is not training irrespective of different parameters settings. I have not initialised weights of any conv2d layer and pytorch must be doing what it is supposed to do by default. Are the uninitialised weights reason behind this ambiguity? Also, how could I initialise ‘normal distribution’ weights for conv2d?</p>

alexis-jacq: <p>For the normal initialisation you can simply do:</p>
<pre><code class="lang-auto">my_conv = nn.Conv2d(... )
nn.init.normal(my_conv.weight)
</code></pre>
<p>What do you mean by “the model is not training”? Is your loss increasing? Or the parameters remain unchanged?</p>

Shiv: <p>My parameters are not changing irrespective of different learning rates.</p>

alexis-jacq: <p>Are you sure you are well defining your optimizer with the parameters of your model? And that you are calling <code>.backward()</code> method before doing <code>optimizer.step()</code>? Can you show some lines of code then?</p>

Shiv: <p>Here is code:</p>
<p>for i, (train_images_1, train_labels_1) in enumerate(train_loader):</p>
<pre><code>	running_loss = 0.0
	running_corrects = 0
             #wrap them in Variable
            if use_gpu:
            	train_images_1, train_labels_1 = Variable(train_images_1.cuda()), \
             Variable(train_labels_1.cuda())

	

            # zero the parameter gradients
            optimizer.zero_grad()

            # forward
            outputs = cnn(train_images_1)

            _, preds = torch.max(outputs.data, 1)
            loss = criterion(outputs, train_labels_1)
            loss.backward()
            optimizer.step()</code></pre>

alexis-jacq: <p>Ok, if I understand your targets are the arguments max. This may not work, you should have a vector of zeros with a “one” where you want an activation:</p>
<pre><code class="lang-python">for i, (train_images_1, train_labels_1) in enumerate(train_loader):
  # prepare target
  target = torch.zeros(1, num_labels)
  target[0,train_labels_1] = 1
  
  running_loss = 0.0
  running_corrects = 0
  #wrap them in Variable
  train_images_1 = Variable(train_images_1.cuda(), requires_grad=True)
  target = Variable(target.cuda(), requires_grad=False)
  
  # zero the parameter gradients
  optimizer.zero_grad()

  # forward
  outputs = cnn(train_images_1)
  loss = criterion(outputs, target)
  loss.backward()
  optimizer.step()
</code></pre>

Shiv: <p>I was using vector before. Then pytorch was treating it as multitarget problem and throwing run time error. I made the above changes too but its not working.</p>
<p>Thanks for your efforts. <img src="//discuss.pytorch.org/images/emoji/apple/slight_smile.png?v=5" title=":slight_smile:" class="emoji" alt=":slight_smile:"></p>

Shivam_Chandhok: <p>Hey,did you find any solution.<br>
I am facing the same problem</p>

Shivam_Chandhok: <aside class="quote" data-post="8" data-topic="5055">
  <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/shivam_chandhok/48/10384_2.png" class="avatar">
    <a href="https://discuss.pytorch.org/t/model-not-training/5055/8">Model not training</a> 
  </div>
  <blockquote>
    Hey,did you find any solution. 
I am facing the same problem
  </blockquote>
</aside>


ptrblck: <p>Could you describe your problem a bit and what you’ve tried so far?<br>
Do you get an error or is the model not learning at all?<br>
If you have a working Keras model, we could try to compare both implementations and look for differences and code bugs.</p>

vijaytida: <p>Hi my model is not training properly when I added one layer to the pretrained vgg16 model<br>
Here is the code I modified<br>
num_ftrs = model_conv.classifier[6].out_features<br>
model_conv.add_module(“classifier1”,nn.ReLU(inplace=True))<br>
model_conv.classifier1=nn.Sequential(model_conv.classifier1,nn.Dropout(0.5),nn.Linear(num_ftrs,2))<br>
model_conv.classifier.requires_grad=True<br>
print(model_conv)<br>
model_conv = model_conv.to(device)</p>
<p>when I run the code I got RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn to avoid this I added line  loss = Variable(loss, requires_grad=True) to train_model function. Can you please help me?</p>

ptrblck: <p>If you want to replace the last linear layer in <code>model_conv.classifier</code>, you would have to reassign the new <code>nn.Sequential</code> module back to <code>.classifier</code> instead of <code>.classifier1</code>.</p>

vijaytida: <p>Thanks I solved the problem before I used sequential on the basic model which I had problem to access trainable weights.</p>

Prakyath_Kantharaju: <p><a class="mention" href="/u/ptrblck">@ptrblck</a> I saw this issue now. I have a similar problem noted here: <a href="https://discuss.pytorch.org/t/training-not-working/130592" class="inline-onebox">Training not working</a></p>
<p>Can you please help me out with this?</p>