Guest User

Untitled

a guest
Jun 18th, 2018
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.78 KB | None | 0 0
  1. class SoftmaxCrossent(Module):
  2.  
  3. def run(self, x, labels):
  4. # Calculate exp(x-max(x))
  5. x -= x.max(1, keepdims=True)
  6. sum_e_x = np.exp(x).sum(1, keepdims=True)
  7.  
  8. # Calculate log(softmax(x))
  9. log_soft = x - np.log(sum_e_x)
  10. crossed = - np.multiply(labels, log_soft)
  11.  
  12. # Cache values
  13. self.cache_value(log_soft=log_soft, labels=labels)
  14. return crossed.sum(1).mean()
  15.  
  16. def backprop(self, grad=1.0):
  17. # Get cached values
  18. cache = self.get_cached_values()
  19. labels, log_soft = cache['labels'], cache['log_soft']
  20. batch_size = labels.shape[0]
  21.  
  22. # backprop through mean() == divide by batch_size
  23. scaling = grad / batch_size
  24. return scaling * (np.exp(log_soft) - labels)
Add Comment
Please, Sign In to add comment