Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 787
biepansiri Avatar asked Oct 16 '25 15:10

biepansiri


1 Answers

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

like image 148
C P Vikram Adithya Avatar answered Oct 19 '25 04:10

C P Vikram Adithya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!