Guest User

Untitled

a guest
Mar 17th, 2018
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.83 KB | None | 0 0
  1. import torch
  2.  
  3. # Batch Size = 32, Input Dimension = 500, Hidden Dimension = 50, Output Dimension = 5
  4.  
  5. dtype = torch.FloatTensor
  6.  
  7. # Create random tensors for data and weights
  8. x = torch.randn(32, 500).type(dtype)
  9. y = torch.randn(32, 5).type(dtype)
  10. w1 = torch.randn(500, 50).type(dtype)
  11. w2 = torch.randn(50, 5).type(dtype)
  12.  
  13. learning_rate = 1e-6
  14. for t in range(250):
  15. # Forward pass: Compute predictions and loss
  16. h = x.mm(w1)
  17. h_relu = h.clamp(min=0)
  18. y_pred = h_relu.mm(w2)
  19. loss = (y_pred - y).pow(2).sum()
  20.  
  21. # Backward pass: Compute gradients
  22. grad_y_pred = 2.0 * (y_pred - y)
  23. grad_w2 = h_relu.t().mm(grad_y_pred)
  24. grad_h_relu = grad_y_pred.mm(w2.t())
  25. grad_h = grad_h_relu.clone()
  26. grad_h[h < 0] = 0
  27. grad_w1 = x.t().mm(grad_h)
  28.  
  29. # Gradient descent step on weights
  30. w1 -= learning_rate * grad_w1
  31. w2 -= learning_rate * grad_w2
Add Comment
Please, Sign In to add comment