55 KiB
55 KiB
In [1]:
import torchIn [2]:
x = torch.tensor(3.0)
y = torch.tensor(2.0)
x + y, x * y, x / y, x**yOut [2]:
(tensor(5.), tensor(6.), tensor(1.5000), tensor(9.))
In [3]:
x = torch.arange(3)
xOut [3]:
tensor([0, 1, 2])
In [4]:
x[2]Out [4]:
tensor(2)
In [5]:
len(x)Out [5]:
3
In [6]:
x.shapeOut [6]:
torch.Size([3])
In [7]:
A = torch.arange(6).reshape(3, 2)
AOut [7]:
tensor([[0, 1],
[2, 3],
[4, 5]])In [8]:
A.TOut [8]:
tensor([[0, 2, 4],
[1, 3, 5]])In [9]:
A = torch.tensor([[1, 2, 3], [2, 0, 4], [3, 4, 5]])
A == A.TOut [9]:
tensor([[True, True, True],
[True, True, True],
[True, True, True]])In [10]:
torch.arange(24).reshape(2, 3, 4)Out [10]:
tensor([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]],
[[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]]])In [11]:
A = torch.arange(6, dtype=torch.float32).reshape(2, 3)
B = A.clone() # Assign a copy of A to B by allocating new memory
A, A + BOut [11]:
(tensor([[0., 1., 2.],
[3., 4., 5.]]),
tensor([[ 0., 2., 4.],
[ 6., 8., 10.]]))In [12]:
A * BOut [12]:
tensor([[ 0., 1., 4.],
[ 9., 16., 25.]])In [13]:
a = 2
X = torch.arange(24).reshape(2, 3, 4)
a + X, (a * X).shapeOut [13]:
(tensor([[[ 2, 3, 4, 5],
[ 6, 7, 8, 9],
[10, 11, 12, 13]],
[[14, 15, 16, 17],
[18, 19, 20, 21],
[22, 23, 24, 25]]]),
torch.Size([2, 3, 4]))In [14]:
x = torch.arange(3, dtype=torch.float32)
x, x.sum()Out [14]:
(tensor([0., 1., 2.]), tensor(3.))
In [15]:
A.shape, A.sum()Out [15]:
(torch.Size([2, 3]), tensor(15.))
In [16]:
A.shape, A.sum(axis=0).shapeOut [16]:
(torch.Size([2, 3]), torch.Size([3]))
In [17]:
A.shape, A.sum(axis=1).shapeOut [17]:
(torch.Size([2, 3]), torch.Size([2]))
In [18]:
A.sum(axis=[0, 1]) == A.sum() # Same as A.sum()Out [18]:
tensor(True)
In [19]:
A.mean(), A.sum() / A.numel()Out [19]:
(tensor(2.5000), tensor(2.5000))
In [20]:
A.mean(axis=0), A.sum(axis=0) / A.shape[0]Out [20]:
(tensor([1.5000, 2.5000, 3.5000]), tensor([1.5000, 2.5000, 3.5000]))
In [21]:
sum_A = A.sum(axis=1, keepdims=True)
sum_A, sum_A.shapeOut [21]:
(tensor([[ 3.],
[12.]]),
torch.Size([2, 1]))In [22]:
A / sum_AOut [22]:
tensor([[0.0000, 0.3333, 0.6667],
[0.2500, 0.3333, 0.4167]])In [23]:
A.cumsum(axis=0)Out [23]:
tensor([[0., 1., 2.],
[3., 5., 7.]])In [24]:
y = torch.ones(3, dtype = torch.float32)
x, y, torch.dot(x, y)Out [24]:
(tensor([0., 1., 2.]), tensor([1., 1., 1.]), tensor(3.))
In [25]:
torch.sum(x * y)Out [25]:
tensor(3.)
In [26]:
A.shape, x.shape, torch.mv(A, x), A@xOut [26]:
(torch.Size([2, 3]), torch.Size([3]), tensor([ 5., 14.]), tensor([ 5., 14.]))
In [27]:
B = torch.ones(3, 4)
torch.mm(A, B), A@BOut [27]:
(tensor([[ 3., 3., 3., 3.],
[12., 12., 12., 12.]]),
tensor([[ 3., 3., 3., 3.],
[12., 12., 12., 12.]]))In [28]:
u = torch.tensor([3.0, -4.0])
torch.norm(u)Out [28]:
tensor(5.)
In [29]:
torch.abs(u).sum()Out [29]:
tensor(7.)
In [30]:
torch.norm(torch.ones((4, 9)))Out [30]:
tensor(6.)