< Back
Env
import torch
Visit
 
Indexes and slices
X = torch.arange(12, dtype=torch.float32).reshape((3,4))
Y = torch.tensor([[2.0, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])
X, Y
(tensor([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.]]),
tensor([[2., 1., 4., 3.],
[1., 2., 3., 4.],
[4., 3., 2., 1.]]))
X[1, 1]
tensor(5.)
X[0, -1]
tensor(3.)
X[0:2, :]
tensor([[0., 1., 2., 3.],
[4., 5., 6., 7.]])
 
len
len(X)
Output
3
 
shape
X.shape
Output
torch.Size([3, 4])
new assignment (save memory)
 
why this is important
X = torch.arange(12, dtype=torch.float32).reshape((3,4))
Y = torch.tensor([[2.0, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])
before = id(Y)
Y = Y + X
id(Y) == before
False
 
safe way
Y[:] = X + Y
id(Y) == before
True
Y += X
id(Y) == before
True
New assignment (indexes and slices)
X[0:2, :] = 12
X
tensor([[12., 12., 12., 12.],
[12., 12., 12., 12.],
[ 8., 9., 10., 11.]])
Change to other objects
 
array, tensor
A = X.numpy()
B = torch.tensor(A)
A,B
(array([[12., 12., 12., 12.],
[12., 12., 12., 12.],
[ 8., 9., 10., 11.]], dtype=float32),
tensor([[12., 12., 12., 12.],
[12., 12., 12., 12.],
[ 8., 9., 10., 11.]]))
type(A), type(B)
(numpy.ndarray, torch.Tensor)
 
python scalar
a = torch.tensor([3.5])
a
tensor([3.5000])
a.item()
3.5
float(a)
3.5
int(a)
3
a.item() == float(a)
True