Pytorch code isn't showing Epoch neither errors

username: NancyShehata
cooked: <p>I tried to run this PyTorch code, it doesn’t show any Epoch and also not showing any errors or warnings, can someone please help?</p>
<p><div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/1/0/10949ac74ff4821d4efe101705396fcfddc7d06c.png" data-download-href="https://discuss.pytorch.org/uploads/default/10949ac74ff4821d4efe101705396fcfddc7d06c" title="image"><img src="https://discuss.pytorch.org/uploads/default/original/3X/1/0/10949ac74ff4821d4efe101705396fcfddc7d06c.png" alt="image" data-base62-sha1="2mG1s2cXjpbHkfNEzPDmkUypTGc" width="690" height="363" data-dominant-color="F0F0F0"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">image</span><span class="informations">1600×843 26.9 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div></p>
<p><div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/8/4/84023689fef7da8f0fc307c19dca878be0bf1185.png" data-download-href="https://discuss.pytorch.org/uploads/default/84023689fef7da8f0fc307c19dca878be0bf1185" title="image"><img src="https://discuss.pytorch.org/uploads/default/original/3X/8/4/84023689fef7da8f0fc307c19dca878be0bf1185.png" alt="image" data-base62-sha1="iPNLAm4gWqGZ9iS7xJdbfPk3t4h" width="543" height="500" data-dominant-color="F0F0F0"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">image</span><span class="informations">895×823 16.5 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div></p>
<p>loss_func = nn.CrossEntropyLoss()<br>
loss_func</p>
<p>from torch import optim<br>
optimizer = optim.Adam(cnn.parameters(), lr = 0.01)<br>
optimizer</p>
<p>from torch.autograd import Variable<br>
num_epochs = 20<br>
def train(num_epochs, cnn, loaders):</p>
<pre><code>cnn.train()
    
# Train the model
total_step = len(loaders['train'])
    
for epoch in range(num_epochs):
    for i, (images, labels) in enumerate(loaders['train']):
        
        # gives batch data, normalize x when iterate train_loader
        b_x = Variable(images)   # batch x
        b_y = Variable(labels)   # batch y
        output = cnn(b_x)[0]               
        loss = loss_func(output, b_y)

        
        # clear gradients for this training step   
        optimizer.zero_grad()           
        
        # backpropagation, compute gradients 
        loss.backward()    
        # apply gradients             
        optimizer.step()                
        
        if (i+1) % 100 == 0:
            print ('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}' 
                   .format(epoch + 1, num_epochs, i + 1, total_step, loss.item()))
</code></pre>
<p>train(num_epochs, cnn, loaders)</p>

username: ptrblck
cooked: <p>Your code is unfortunately not formatted so a bit hard to debug.<br>
You can post code snippets by wrapping them into three backticks ```.</p>
<p>To debug the issue further, add <code>print</code> statements to your script and check which lines are executed and where the code gets stuck.</p>

username: NancyShehata
cooked: <p>Thank you so much for your reply and help, I tried to edit my post so that it is easier now to debug, however in some cells I had to take screenshot so it is easier to read.<br>
I tried to add print after each line/part and all lines/parts are printed without a problem and still the code is not getting the Epoch. can you please advise? Thank you</p>

username: ptrblck
cooked: <p>This might indicate that your <code>loaders['train']</code> <code>DataLoader</code> does not contain 100 batches and you might need to adapt the <code>if</code> condition to print the epoch stats.<br>
What does <code>len(loaders['train'])</code> return?</p>

username: NancyShehata
cooked: <p>When I add print to the total_step which it is =  len(loaders[‘train’])<br>
then I get value 40, if this what you mean!</p>

username: ptrblck
cooked: <p>Yes, that’s what I meant.<br>
It shows that your <code>DataLoader</code> only contains 40 batches and your <code>if</code> condition will thus never return <code>True</code> since you explicitly only print the first loss value after 100 batches:</p>
<pre><code class="lang-python">  if (i+1) % 100 == 0:
            print ('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}' 
                   .format(epoch + 1, num_epochs, i + 1, total_step, loss.item()))
</code></pre>
<p>Remove the if condition or change the modulo operation to return <code>True</code> for less iterations.</p>

username: NancyShehata
cooked: <p>Oh thank you so much, I changed the modulo operation conditions and now it is showing the Epoch, thank you so much for your help <img src="https://discuss.pytorch.org/images/emoji/apple/slight_smile.png?v=12" title=":slight_smile:" class="emoji" alt=":slight_smile:" loading="lazy" width="20" height="20"></p>