torch_get_start.py 950 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. from __future__ import print_function
  2. import torch
  3. import numpy as np
  4. # pyTorch tensoor
  5. x = torch.Tensor(5, 3)
  6. print('matrix x:\n', x)
  7. print('matrix x size:\n', x.size())
  8. y = torch.rand(5, 3)
  9. print('matrix x + y:\n', x + y)
  10. print('matrix x + y again:\n', torch.add(x, y))
  11. result = torch.Tensor(5, 3)
  12. torch.add(x, y, out=result)
  13. print('matrix x + y result:\n', result)
  14. y.add_(x)
  15. print('matrix x add to y:\n', y)
  16. print('col 2 of matrix x:\n', x[:, 1])
  17. # convert to numpy
  18. a = torch.ones(5)
  19. print('torch array full with number 1:\n', a)
  20. b = a.numpy()
  21. print('numpy array:\n', b)
  22. a.add_(1)
  23. print('torch array after change:\n', a)
  24. print('numpy array after change:\n', b)
  25. na = np.ones(5)
  26. nb = torch.from_numpy(na)
  27. np.add(na, 1, out=na)
  28. print('another numpy array after change:\n', na)
  29. print('another torch array after change:\n', nb)
  30. # CUDA
  31. if torch.cuda.is_available():
  32. x = x.cuda()
  33. y = y.cuda()
  34. print('result from GPU:\n', x + y)