Advertisement
Guest User

Untitled

a guest
Jul 22nd, 2019
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. from keras.callbacks import Callback
  2. import keras.backend as K
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5.  
  6. class LRFinder(Callback):
  7. def __init__(self, min_lr, max_lr):
  8. self.min_lr = min_lr
  9. self.max_lr = max_lr
  10.  
  11. def on_train_begin(self, logs={}):
  12. n_iterations = self.params['samples']//self.params['batch_size']
  13. self.learning_rates = np.geomspace(self.min_lr, self.max_lr, \
  14. num=n_iterations+1)
  15. self.losses=[]
  16. self.iteration=0
  17. self.best_loss=0
  18.  
  19.  
  20. def on_batch_end(self, batch, logs={}):
  21. loss = logs.get('loss')
  22. if self.iteration==0 or loss < self.best_loss:
  23. self.best_loss = loss
  24. lr = self.learning_rates[self.iteration]
  25. K.set_value(self.model.optimizer.lr, lr)
  26. self.losses.append(loss)
  27. self.iteration += 1
  28. if loss > self.best_loss*10: # Stop criteria
  29. self.model.stop_training = True
  30.  
  31. def on_train_end(self, logs=None):
  32. plt.figure(figsize=(12, 6))
  33. plt.plot(self.learning_rates[:len(self.losses)], self.losses)
  34. plt.xlabel("Learning Rate")
  35. plt.ylabel("Loss")
  36. plt.xscale('log')
  37. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement