{ "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": [ "Tensors\n", "=======\n", "\n", "Tensors are a specialized data structure that are very similar to arrays\n", "and matrices. In PyTorch, we use tensors to encode the inputs and\n", "outputs of a model, as well as the model's parameters.\n", "\n", "Tensors are similar to NumPy's ndarrays, except that tensors can run on\n", "GPUs or other specialized hardware to accelerate computing. If you're\n", "familiar with ndarrays, you'll be right at home with the Tensor API. If\n", "not, follow along in this quick API walkthrough.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import torch\n", "import numpy as np" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Tensor Initialization\n", "=====================\n", "\n", "Tensors can be initialized in various ways. Take a look at the following\n", "examples:\n", "\n", "**Directly from data**\n", "\n", "Tensors can be created directly from data. The data type is\n", "automatically inferred.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "data = [[1, 2], [3, 4]]\n", "x_data = torch.tensor(data)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**From a NumPy array**\n", "\n", "Tensors can be created from NumPy arrays (and vice versa - see\n", "`bridge-to-np-label`{.interpreted-text role=\"ref\"}).\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "np_array = np.array(data)\n", "x_np = torch.from_numpy(np_array)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**From another tensor:**\n", "\n", "The new tensor retains the properties (shape, datatype) of the argument\n", "tensor, unless explicitly overridden.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "x_ones = torch.ones_like(x_data) # retains the properties of x_data\n", "print(f\"Ones Tensor: \\n {x_ones} \\n\")\n", "\n", "x_rand = torch.rand_like(x_data, dtype=torch.float) # overrides the datatype of x_data\n", "print(f\"Random Tensor: \\n {x_rand} \\n\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**With random or constant values:**\n", "\n", "`shape` is a tuple of tensor dimensions. In the functions below, it\n", "determines the dimensionality of the output tensor.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "shape = (2, 3,)\n", "rand_tensor = torch.rand(shape)\n", "ones_tensor = torch.ones(shape)\n", "zeros_tensor = torch.zeros(shape)\n", "\n", "print(f\"Random Tensor: \\n {rand_tensor} \\n\")\n", "print(f\"Ones Tensor: \\n {ones_tensor} \\n\")\n", "print(f\"Zeros Tensor: \\n {zeros_tensor}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "------------------------------------------------------------------------\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Tensor Attributes\n", "=================\n", "\n", "Tensor attributes describe their shape, datatype, and the device on\n", "which they are stored.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "tensor = torch.rand(3, 4)\n", "\n", "print(f\"Shape of tensor: {tensor.shape}\")\n", "print(f\"Datatype of tensor: {tensor.dtype}\")\n", "print(f\"Device tensor is stored on: {tensor.device}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "------------------------------------------------------------------------\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Tensor Operations\n", "=================\n", "\n", "Over 100 tensor operations, including transposing, indexing, slicing,\n", "mathematical operations, linear algebra, random sampling, and more are\n", "comprehensively described\n", "[here](https://pytorch.org/docs/stable/torch.html).\n", "\n", "Each of them can be run on the GPU (at typically higher speeds than on a\n", "CPU). If you're using Colab, allocate a GPU by going to Edit \\> Notebook\n", "Settings.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# We move our tensor to the GPU if available\n", "if torch.cuda.is_available():\n", " tensor = tensor.to('cuda')\n", " print(f\"Device tensor is stored on: {tensor.device}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Try out some of the operations from the list. If you\\'re familiar with\n", "the NumPy API, you\\'ll find the Tensor API a breeze to use.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Standard numpy-like indexing and slicing:**\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "tensor = torch.ones(4, 4)\n", "tensor[:,1] = 0\n", "print(tensor)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Joining tensors** You can use `torch.cat` to concatenate a sequence of\n", "tensors along a given dimension. See also\n", "[torch.stack](https://pytorch.org/docs/stable/generated/torch.stack.html),\n", "another tensor joining op that is subtly different from `torch.cat`.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "t1 = torch.cat([tensor, tensor, tensor], dim=1)\n", "print(t1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Multiplying tensors**\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# This computes the element-wise product\n", "print(f\"tensor.mul(tensor) \\n {tensor.mul(tensor)} \\n\")\n", "# Alternative syntax:\n", "print(f\"tensor * tensor \\n {tensor * tensor}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This computes the matrix multiplication between two tensors\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "print(f\"tensor.matmul(tensor.T) \\n {tensor.matmul(tensor.T)} \\n\")\n", "# Alternative syntax:\n", "print(f\"tensor @ tensor.T \\n {tensor @ tensor.T}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**In-place operations** Operations that have a `_` suffix are in-place.\n", "For example: `x.copy_(y)`, `x.t_()`, will change `x`.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "print(tensor, \"\\n\")\n", "tensor.add_(5)\n", "print(tensor)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
In-place operations save some memory, but can be problematic when computing derivatives because of an immediate lossof history. Hence, their use is discouraged.
\n", "