目录
Create Tensor
#create tensors with specific dimension
a = torch.tensor(5, device = "cpu")
c = torch.empty(2, 3)
k = torch.ones(2, 2, dtype = torch.int). # torch.float16
t = torch.randn(2, 2)
#check the size:
k.size()
#create a tensor from list
d = torch.tensor([1, 2, 3])
Oprations on Tensor
- Plus, Minus, Multiplication, Diviation
z = x + y z = torch.add(x, y) z = y.add_(x) # dash line means inplace operation z = x - y z = torch.sub(x, y) z = x*y z = torch.mul(x, y) z = x/y z = torch.div(x, y)
- slicing & Reshape
#slicing: x = torch.randn(5, 3) print(x[:, 0]) # select all the rows and the first column #When you have only one element in your tensor, you can use the .item() to get specific value value = x[1,1].item() # reshape a tensor: the total number of elements must still be the same x = torch.randn(4, 4) y = x.view(16) y = x.view(-1, 8) # specify the number of column but leave the number of rows caculated by python self
-
Numpy — Tensor (can only operate on cpu)
# a and b share cpu memory now, if we modify one of them, the other one will change accordingly a = torch.ones(5) b = a.numpy() a = np.ones(5) b = torch.from_numpy(a)
-
Create a Tensor on GPU
# How to create a Tensor on GPU if torch.cuda.is_available(): device = torch.device("cuda") x = torch.randn(5, device = device) y = torch.randn(5) y.to(device) # numpy can't handle gpu tensor print(y.numpy()) ----- Erro