60 min Blitz Flashcards
create an empty matrix with dim 5,3
torch.empty(5,3)
create random matrix with dim 5,3
torch.random(5,3)
create zeros matrix of a type
torch.zeros(5,3,dtype=torch.long)
construct a tensor directly from data
torch.tensor([5.5, 3])
create a tensor based on an existing tensor
x = x.new_ones(5, 3, dtype=torch.double) x = torch.randn_like(x, dtype=torch.float)
get size of matrix
x. size()
torch. Size([5,3])
operations
x+y
torch. add(x,y,out=result)
y. add_(x)
resize/reshape tensor
y = x.view(16) z = x.view(-1, 8) (the size -1 is inferred from other dimensions)
get the value of one element tensor
x.item()
convert a torch tensor to a numpy array and vice versa
b = a.numpy()
import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
move tensors in and out of GPU
if torch.cuda.is_available():
device = torch.device(“cuda”) # a CUDA device object
y = torch.ones_like(x, device=device) # directly create a tensor on GPU
x = x.to(device) # or just use strings .to("cuda")
z = x + y
package that provides automatic differentiation for all operations on Tensors
autograd
track all operations on a torch.Tensor
set its attribute .requires_grad as True
compute all the gradients automatically
call .backward()
attribute which has the gradient
.grad
stop a tensor from tracking history
call .detach()
when wrapping the code block in with torch.no_grad(): is hepful
when evaluating a model