Guest User

Untitled

a guest
Mar 18th, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.61 KB | None | 0 0
  1. N = 64;
  2. D_in = 1000;
  3. H = 100;
  4. D_out = 10;
  5.  
  6. % init input and output
  7. x = rand(N, D_in)-0.5;
  8. y = rand(N, D_out)-0.5;
  9.  
  10. % init weights
  11. w1 = rand(D_in, H)-0.5;
  12. w2 = rand(H, D_out)-0.5;
  13.  
  14. lr = 1e-4;
  15. total_loss = {};
  16. for i = 1:500
  17. % forward
  18. h = x * w1;
  19. h_relu = max(h, 0);
  20. y_pred = h_relu * w2;
  21. loss = norm(y_pred-y, 2);
  22. disp(loss);
  23. total_loss{i} = loss;
  24. % backward
  25. grad_y_pred = 2 * (y_pred-y);
  26. grad_w2 = h_relu' * grad_y_pred;
  27. grad_h_relu = grad_y_pred * w2';
  28. grad_h = grad_h_relu .* (h>=0);
  29. grad_w1 = x' * grad_h;
  30. % optimizer
  31. w1 = w1 - lr * grad_w1;
  32. w2 = w2 - lr * grad_w2;
  33. end
  34.  
  35. total_loss = cell2mat(total_loss)
  36. plot(total_loss)
Add Comment
Please, Sign In to add comment