QBoard » Artificial Intelligence & ML » AI and ML - PyTorch » How to make early stopping in image classification pytorch

How to make early stopping in image classification pytorch

  • I'm new with Pytorch and machine learning I'm follow this tutorial in this tutorial https://www.learnopencv.com/image-classification-using-transfer-learning-in-pytorch/ and use my custom dataset. Then I have same problem in this tutorial but I dont know how to make early stopping in pytorch and if do you have better without create early stopping process please tell me.
      September 23, 2021 1:57 PM IST
    0
  • Try with below code.

    # Check early stopping condition
         if epochs_no_improve == n_epochs_stop:
            print('Early stopping!' )
            early_stop = True
            break
         else:
            continue
         break
    if early_stop:
        print("Stopped")
        break
      October 1, 2021 1:19 PM IST
    0
  • This is what I did in each epoch

    val_loss += loss
    val_loss = val_loss / len(trainloader)
    if val_loss < min_val_loss:
      #Saving the model
      if min_loss > loss.item():
        min_loss = loss.item()
        best_model = copy.deepcopy(loaded_model.state_dict())
        print('Min loss %0.2f' % min_loss)
      epochs_no_improve = 0
      min_val_loss = val_loss
    
    else:
      epochs_no_improve += 1
      # Check early stopping condition
      if epochs_no_improve == n_epochs_stop:
        print('Early stopping!' )
        loaded_model.load_state_dict(best_model)

     

    Donno how correct it is (I took most parts of this code from a post on another website, but forgot where, so I can't put the reference link. I have just modified it a bit), hope you find it useful, in case I'm wrong, kindly point out the mistake. Thank you

     
      October 4, 2021 1:47 PM IST
    0