In [1]:
import torch
import numpy as np
from __future__ import print_function
In [2]:
x = torch.Tensor(5, 3)
print(x)
In [3]:
x.zero_()
Out[3]:
In [4]:
torch.Tensor([[1, 2, 3], # rank 2 tensor
[4, 5, 6],
[7, 8, 9]])
Out[4]:
In [5]:
x.size()
Out[5]:
In [6]:
x = torch.rand(5, 3)
print(x)
In [7]:
npy = np.random.rand(5, 3)
y = torch.from_numpy(npy)
print(y)
In [40]:
z = x + y #can we do this addition?
In [9]:
x.type(), y.type()
Out[9]:
In [10]:
z = x + y.float()
print(z)
In [11]:
torch.add(x, y.float())
Out[11]:
In [12]:
x
Out[12]:
In [13]:
x.add_(1)
Out[13]:
In [14]:
x
Out[14]:
In [15]:
x[:2, :2]
Out[15]:
In [16]:
x * y.float()
Out[16]:
In [17]:
torch.exp(x)
Out[17]:
In [18]:
torch.transpose(x, 0, 1)
Out[18]:
In [19]:
#transposing, indexing, slicing, mathematical operations, linear algebra, random numbers
In [20]:
torch.trace(x)
Out[20]:
In [21]:
x.numpy()
Out[21]:
In [22]:
torch.cuda.is_available()
Out[22]:
In [23]:
if torch.cuda.is_available():
x_gpu = x.cuda()
print(x_gpu)
In [24]:
from torch.autograd import Variable
In [25]:
x = torch.rand(5, 3)
print(x)
In [26]:
x = Variable(torch.rand(5, 3))
print(x)
Each variable holds data, a gradient, and information about the function that created it. <img src="figures/intro_to_pytorch/pytorch_variable.svg",width=400,height=400>
In [28]:
x.data
Out[28]:
In [29]:
# should be nothing right now
assert x.grad_fn is None
assert x.grad is None
In [31]:
x = Variable(torch.Tensor([2]), requires_grad=True)
w = Variable(torch.Tensor([3]), requires_grad=True)
b = Variable(torch.Tensor([1]), requires_grad=True)
z = x * w
y = z + b
y
Out[31]:
Compare the above computations to the below graph.. and then the one below that!
In [32]:
y.backward()
In [33]:
y, b
Out[33]:
Since the derivative of w*x wrt x is w, and vice versa:
In [34]:
w.grad, w
Out[34]:
In [35]:
x.grad, x
Out[35]:
$ y = 2w + b$, since $x = 2$
Say we want: $\displaystyle\frac{\partial y}{\partial w}$
In [36]:
a = Variable(torch.Tensor([2]), requires_grad=True)
Let's compute, $\displaystyle\frac{\partial}{\partial a}(3a^2 + 2a + 1)$ when $a = 2$
In [37]:
y = 3*a*a + 2*a + 1
In [38]:
y.backward()
In [39]:
a.grad
Out[39]:
checks out, since $\displaystyle\frac{\partial}{\partial a}(3a^2 + 2a + 1) = 6a + 2$ and $a = 2$