{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# For tips on running notebooks in Google Colab, see\n",
"# https://pytorch.org/tutorials/beginner/colab\n",
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Introduction to PyTorch\n",
"=======================\n",
"\n",
"Introduction to Torch\\'s tensor library\n",
"---------------------------------------\n",
"\n",
"All of deep learning is computations on tensors, which are\n",
"generalizations of a matrix that can be indexed in more than 2\n",
"dimensions. We will see exactly what this means in-depth later. First,\n",
"let\\'s look what we can do with tensors.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Author: Robert Guthrie\n",
"\n",
"import torch\n",
"\n",
"torch.manual_seed(1)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Creating Tensors\n",
"================\n",
"\n",
"Tensors can be created from Python lists with the torch.tensor()\n",
"function.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# torch.tensor(data) creates a torch.Tensor object with the given data.\n",
"V_data = [1., 2., 3.]\n",
"V = torch.tensor(V_data)\n",
"print(V)\n",
"\n",
"# Creates a matrix\n",
"M_data = [[1., 2., 3.], [4., 5., 6]]\n",
"M = torch.tensor(M_data)\n",
"print(M)\n",
"\n",
"# Create a 3D tensor of size 2x2x2.\n",
"T_data = [[[1., 2.], [3., 4.]],\n",
" [[5., 6.], [7., 8.]]]\n",
"T = torch.tensor(T_data)\n",
"print(T)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"What is a 3D tensor anyway? Think about it like this. If you have a\n",
"vector, indexing into the vector gives you a scalar. If you have a\n",
"matrix, indexing into the matrix gives you a vector. If you have a 3D\n",
"tensor, then indexing into the tensor gives you a matrix!\n",
"\n",
"A note on terminology: when I say \\\"tensor\\\" in this tutorial, it refers\n",
"to any torch.Tensor object. Matrices and vectors are special cases of\n",
"torch.Tensors, where their dimension is 2 and 1 respectively. When I am\n",
"talking about 3D tensors, I will explicitly use the term \\\"3D tensor\\\".\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Index into V and get a scalar (0 dimensional tensor)\n",
"print(V[0])\n",
"# Get a Python number from it\n",
"print(V[0].item())\n",
"\n",
"# Index into M and get a vector\n",
"print(M[0])\n",
"\n",
"# Index into T and get a matrix\n",
"print(T[0])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can also create tensors of other data types. To create a tensor of\n",
"integer types, try torch.tensor(\\[\\[1, 2\\], \\[3, 4\\]\\]) (where all\n",
"elements in the list are integers). You can also specify a data type by\n",
"passing in `dtype=torch.data_type`. Check the documentation for more\n",
"data types, but Float and Long will be the most common.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can create a tensor with random data and the supplied dimensionality\n",
"with torch.randn()\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"x = torch.randn((3, 4, 5))\n",
"print(x)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Operations with Tensors\n",
"=======================\n",
"\n",
"You can operate on tensors in the ways you would expect.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"x = torch.tensor([1., 2., 3.])\n",
"y = torch.tensor([4., 5., 6.])\n",
"z = x + y\n",
"print(z)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"See [the documentation](https://pytorch.org/docs/torch.html) for a\n",
"complete list of the massive number of operations available to you. They\n",
"expand beyond just mathematical operations.\n",
"\n",
"One helpful operation that we will make use of later is concatenation.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# By default, it concatenates along the first axis (concatenates rows)\n",
"x_1 = torch.randn(2, 5)\n",
"y_1 = torch.randn(3, 5)\n",
"z_1 = torch.cat([x_1, y_1])\n",
"print(z_1)\n",
"\n",
"# Concatenate columns:\n",
"x_2 = torch.randn(2, 3)\n",
"y_2 = torch.randn(2, 5)\n",
"# second arg specifies which axis to concat along\n",
"z_2 = torch.cat([x_2, y_2], 1)\n",
"print(z_2)\n",
"\n",
"# If your tensors are not compatible, torch will complain. Uncomment to see the error\n",
"# torch.cat([x_1, x_2])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Reshaping Tensors\n",
"=================\n",
"\n",
"Use the .view() method to reshape a tensor. This method receives heavy\n",
"use, because many neural network components expect their inputs to have\n",
"a certain shape. Often you will need to reshape before passing your data\n",
"to the component.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"x = torch.randn(2, 3, 4)\n",
"print(x)\n",
"print(x.view(2, 12)) # Reshape to 2 rows, 12 columns\n",
"# Same as above. If one of the dimensions is -1, its size can be inferred\n",
"print(x.view(2, -1))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Computation Graphs and Automatic Differentiation\n",
"================================================\n",
"\n",
"The concept of a computation graph is essential to efficient deep\n",
"learning programming, because it allows you to not have to write the\n",
"back propagation gradients yourself. A computation graph is simply a\n",
"specification of how your data is combined to give you the output. Since\n",
"the graph totally specifies what parameters were involved with which\n",
"operations, it contains enough information to compute derivatives. This\n",
"probably sounds vague, so let\\'s see what is going on using the\n",
"fundamental flag `requires_grad`.\n",
"\n",
"First, think from a programmers perspective. What is stored in the\n",
"torch.Tensor objects we were creating above? Obviously the data and the\n",
"shape, and maybe a few other things. But when we added two tensors\n",
"together, we got an output tensor. All this output tensor knows is its\n",
"data and shape. It has no idea that it was the sum of two other tensors\n",
"(it could have been read in from a file, it could be the result of some\n",
"other operation, etc.)\n",
"\n",
"If `requires_grad=True`, the Tensor object keeps track of how it was\n",
"created. Let\\'s see it in action.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Tensor factory methods have a ``requires_grad`` flag\n",
"x = torch.tensor([1., 2., 3], requires_grad=True)\n",
"\n",
"# With requires_grad=True, you can still do all the operations you previously\n",
"# could\n",
"y = torch.tensor([4., 5., 6], requires_grad=True)\n",
"z = x + y\n",
"print(z)\n",
"\n",
"# BUT z knows something extra.\n",
"print(z.grad_fn)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"So Tensors know what created them. z knows that it wasn\\'t read in from\n",
"a file, it wasn\\'t the result of a multiplication or exponential or\n",
"whatever. And if you keep following z.grad\\_fn, you will find yourself\n",
"at x and y.\n",
"\n",
"But how does that help us compute a gradient?\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Let's sum up all the entries in z\n",
"s = z.sum()\n",
"print(s)\n",
"print(s.grad_fn)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"So now, what is the derivative of this sum with respect to the first\n",
"component of x? In math, we want\n",
"\n",
"$$\\frac{\\partial s}{\\partial x_0}$$\n",
"\n",
"Well, s knows that it was created as a sum of the tensor z. z knows that\n",
"it was the sum x + y. So\n",
"\n",
"$$s = \\overbrace{x_0 + y_0}^\\text{$z_0$} + \\overbrace{x_1 + y_1}^\\text{$z_1$} + \\overbrace{x_2 + y_2}^\\text{$z_2$}$$\n",
"\n",
"And so s contains enough information to determine that the derivative we\n",
"want is 1!\n",
"\n",
"Of course this glosses over the challenge of how to actually compute\n",
"that derivative. The point here is that s is carrying along enough\n",
"information that it is possible to compute it. In reality, the\n",
"developers of Pytorch program the sum() and + operations to know how to\n",
"compute their gradients, and run the back propagation algorithm. An\n",
"in-depth discussion of that algorithm is beyond the scope of this\n",
"tutorial.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let\\'s have Pytorch compute the gradient, and see that we were right:\n",
"(note if you run this block multiple times, the gradient will increment.\n",
"That is because Pytorch *accumulates* the gradient into the .grad\n",
"property, since for many models this is very convenient.)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# calling .backward() on any variable will run backprop, starting from it.\n",
"s.backward()\n",
"print(x.grad)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Understanding what is going on in the block below is crucial for being a\n",
"successful programmer in deep learning.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"x = torch.randn(2, 2)\n",
"y = torch.randn(2, 2)\n",
"# By default, user created Tensors have ``requires_grad=False``\n",
"print(x.requires_grad, y.requires_grad)\n",
"z = x + y\n",
"# So you can't backprop through z\n",
"print(z.grad_fn)\n",
"\n",
"# ``.requires_grad_( ... )`` changes an existing Tensor's ``requires_grad``\n",
"# flag in-place. The input flag defaults to ``True`` if not given.\n",
"x = x.requires_grad_()\n",
"y = y.requires_grad_()\n",
"# z contains enough information to compute gradients, as we saw above\n",
"z = x + y\n",
"print(z.grad_fn)\n",
"# If any input to an operation has ``requires_grad=True``, so will the output\n",
"print(z.requires_grad)\n",
"\n",
"# Now z has the computation history that relates itself to x and y\n",
"# Can we just take its values, and **detach** it from its history?\n",
"new_z = z.detach()\n",
"\n",
"# ... does new_z have information to backprop to x and y?\n",
"# NO!\n",
"print(new_z.grad_fn)\n",
"# And how could it? ``z.detach()`` returns a tensor that shares the same storage\n",
"# as ``z``, but with the computation history forgotten. It doesn't know anything\n",
"# about how it was computed.\n",
"# In essence, we have broken the Tensor away from its past history"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can also stop autograd from tracking history on Tensors with\n",
"`.requires_grad=True` by wrapping the code block in\n",
"`with torch.no_grad():`\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"print(x.requires_grad)\n",
"print((x ** 2).requires_grad)\n",
"\n",
"with torch.no_grad():\n",
"\tprint((x ** 2).requires_grad)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.14"
}
},
"nbformat": 4,
"nbformat_minor": 0
}