123456789101112131415161718192021222324252627282930313233343536373839404142434445464748 |
- from __future__ import print_function
- import torch
- import numpy as np
- # pyTorch tensoor
- x = torch.Tensor(5, 3)
- print('matrix x:\n', x)
- print('matrix x size:\n', x.size())
- y = torch.rand(5, 3)
- print('matrix x + y:\n', x + y)
- print('matrix x + y again:\n', torch.add(x, y))
- result = torch.Tensor(5, 3)
- torch.add(x, y, out=result)
- print('matrix x + y result:\n', result)
- y.add_(x)
- print('matrix x add to y:\n', y)
- print('col 2 of matrix x:\n', x[:, 1])
- # convert to numpy
- a = torch.ones(5)
- print('torch array full with number 1:\n', a)
- b = a.numpy()
- print('numpy array:\n', b)
- a.add_(1)
- print('torch array after change:\n', a)
- print('numpy array after change:\n', b)
- na = np.ones(5)
- nb = torch.from_numpy(na)
- np.add(na, 1, out=na)
- print('another numpy array after change:\n', na)
- print('another torch array after change:\n', nb)
- # CUDA
- if torch.cuda.is_available():
- x = x.cuda()
- y = y.cuda()
- print('result from GPU:\n', x + y)
|