{ "cells": [ { "cell_type": "markdown", "id": "a622c08e", "metadata": { "origin_pos": 1 }, "source": [ "# Linear Algebra\n", ":label:`sec_linear-algebra`\n", "\n", "By now, we can load datasets into tensors\n", "and manipulate these tensors \n", "with basic mathematical operations.\n", "To start building sophisticated models,\n", "we will also need a few tools from linear algebra. \n", "This section offers a gentle introduction \n", "to the most essential concepts,\n", "starting from scalar arithmetic\n", "and ramping up to matrix multiplication.\n" ] }, { "cell_type": "code", "execution_count": 1, "id": "dc36b473", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T19:41:51.529162Z", "iopub.status.busy": "2023-08-18T19:41:51.528467Z", "iopub.status.idle": "2023-08-18T19:41:53.438267Z", "shell.execute_reply": "2023-08-18T19:41:53.437059Z" }, "origin_pos": 3, "tab": [ "pytorch" ] }, "outputs": [], "source": [ "import torch" ] }, { "cell_type": "markdown", "id": "e4a38674", "metadata": { "origin_pos": 6 }, "source": [ "## Scalars\n", "\n", "\n", "Most everyday mathematics\n", "consists of manipulating \n", "numbers one at a time.\n", "Formally, we call these values *scalars*.\n", "For example, the temperature in Palo Alto \n", "is a balmy $72$ degrees Fahrenheit.\n", "If you wanted to convert the temperature to Celsius\n", "you would evaluate the expression \n", "$c = \\frac{5}{9}(f - 32)$, setting $f$ to $72$.\n", "In this equation, the values \n", "$5$, $9$, and $32$ are constant scalars.\n", "The variables $c$ and $f$ \n", "in general represent unknown scalars.\n", "\n", "We denote scalars\n", "by ordinary lower-cased letters \n", "(e.g., $x$, $y$, and $z$)\n", "and the space of all (continuous) \n", "*real-valued* scalars by $\\mathbb{R}$.\n", "For expedience, we will skip past\n", "rigorous definitions of *spaces*:\n", "just remember that the expression $x \\in \\mathbb{R}$\n", "is a formal way to say that $x$ is a real-valued scalar.\n", "The symbol $\\in$ (pronounced \"in\")\n", "denotes membership in a set.\n", "For example, $x, y \\in \\{0, 1\\}$\n", "indicates that $x$ and $y$ are variables\n", "that can only take values $0$ or $1$.\n", "\n", "(**Scalars are implemented as tensors \n", "that contain only one element.**)\n", "Below, we assign two scalars\n", "and perform the familiar addition, multiplication,\n", "division, and exponentiation operations.\n" ] }, { "cell_type": "code", "execution_count": 2, "id": "4fc9ba1d", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T19:41:53.442690Z", "iopub.status.busy": "2023-08-18T19:41:53.442040Z", "iopub.status.idle": "2023-08-18T19:41:53.472277Z", "shell.execute_reply": "2023-08-18T19:41:53.471491Z" }, "origin_pos": 8, "tab": [ "pytorch" ] }, "outputs": [ { "data": { "text/plain": [ "(tensor(5.), tensor(6.), tensor(1.5000), tensor(9.))" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x = torch.tensor(3.0)\n", "y = torch.tensor(2.0)\n", "\n", "x + y, x * y, x / y, x**y" ] }, { "cell_type": "markdown", "id": "0b20517b", "metadata": { "origin_pos": 11 }, "source": [ "## Vectors\n", "\n", "For current purposes, [**you can think of a vector as a fixed-length array of scalars.**]\n", "As with their code counterparts,\n", "we call these scalars the *elements* of the vector\n", "(synonyms include *entries* and *components*).\n", "When vectors represent examples from real-world datasets,\n", "their values hold some real-world significance.\n", "For example, if we were training a model to predict\n", "the risk of a loan defaulting,\n", "we might associate each applicant with a vector\n", "whose components correspond to quantities\n", "like their income, length of employment, \n", "or number of previous defaults.\n", "If we were studying the risk of heart attack,\n", "each vector might represent a patient\n", "and its components might correspond to\n", "their most recent vital signs, cholesterol levels, \n", "minutes of exercise per day, etc.\n", "We denote vectors by bold lowercase letters, \n", "(e.g., $\\mathbf{x}$, $\\mathbf{y}$, and $\\mathbf{z}$).\n", "\n", "Vectors are implemented as $1^{\\textrm{st}}$-order tensors.\n", "In general, such tensors can have arbitrary lengths,\n", "subject to memory limitations. Caution: in Python, as in most programming languages, vector indices start at $0$, also known as *zero-based indexing*, whereas in linear algebra subscripts begin at $1$ (one-based indexing).\n" ] }, { "cell_type": "code", "execution_count": 3, "id": "91cd966f", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T19:41:53.475759Z", "iopub.status.busy": "2023-08-18T19:41:53.475141Z", "iopub.status.idle": "2023-08-18T19:41:53.481106Z", "shell.execute_reply": "2023-08-18T19:41:53.479872Z" }, "origin_pos": 13, "tab": [ "pytorch" ] }, "outputs": [ { "data": { "text/plain": [ "tensor([0, 1, 2])" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x = torch.arange(3)\n", "x" ] }, { "cell_type": "markdown", "id": "7a603956", "metadata": { "origin_pos": 16 }, "source": [ "We can refer to an element of a vector by using a subscript.\n", "For example, $x_2$ denotes the second element of $\\mathbf{x}$. \n", "Since $x_2$ is a scalar, we do not bold it.\n", "By default, we visualize vectors \n", "by stacking their elements vertically.\n", "\n", "$$\\mathbf{x} =\\begin{bmatrix}x_{1} \\\\ \\vdots \\\\x_{n}\\end{bmatrix},$$\n", ":eqlabel:`eq_vec_def`\n", "\n", "Here $x_1, \\ldots, x_n$ are elements of the vector.\n", "Later on, we will distinguish between such *column vectors*\n", "and *row vectors* whose elements are stacked horizontally.\n", "Recall that [**we access a tensor's elements via indexing.**]\n" ] }, { "cell_type": "code", "execution_count": 4, "id": "ba15a197", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T19:41:53.485066Z", "iopub.status.busy": "2023-08-18T19:41:53.484260Z", "iopub.status.idle": "2023-08-18T19:41:53.492710Z", "shell.execute_reply": "2023-08-18T19:41:53.491415Z" }, "origin_pos": 17, "tab": [ "pytorch" ] }, "outputs": [ { "data": { "text/plain": [ "tensor(2)" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x[2]" ] }, { "cell_type": "markdown", "id": "02a04823", "metadata": { "origin_pos": 18 }, "source": [ "To indicate that a vector contains $n$ elements,\n", "we write $\\mathbf{x} \\in \\mathbb{R}^n$.\n", "Formally, we call $n$ the *dimensionality* of the vector.\n", "[**In code, this corresponds to the tensor's length**],\n", "accessible via Python's built-in `len` function.\n" ] }, { "cell_type": "code", "execution_count": 5, "id": "871cd7e6", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T19:41:53.497529Z", "iopub.status.busy": "2023-08-18T19:41:53.496794Z", "iopub.status.idle": "2023-08-18T19:41:53.502332Z", "shell.execute_reply": "2023-08-18T19:41:53.501510Z" }, "origin_pos": 19, "tab": [ "pytorch" ] }, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len(x)" ] }, { "cell_type": "markdown", "id": "4e190d69", "metadata": { "origin_pos": 20 }, "source": [ "We can also access the length via the `shape` attribute.\n", "The shape is a tuple that indicates a tensor's length along each axis.\n", "(**Tensors with just one axis have shapes with just one element.**)\n" ] }, { "cell_type": "code", "execution_count": 6, "id": "34ea04c3", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T19:41:53.505748Z", "iopub.status.busy": "2023-08-18T19:41:53.505180Z", "iopub.status.idle": "2023-08-18T19:41:53.510136Z", "shell.execute_reply": "2023-08-18T19:41:53.509337Z" }, "origin_pos": 21, "tab": [ "pytorch" ] }, "outputs": [ { "data": { "text/plain": [ "torch.Size([3])" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x.shape" ] }, { "cell_type": "markdown", "id": "e416733f", "metadata": { "origin_pos": 22 }, "source": [ "Oftentimes, the word \"dimension\" gets overloaded\n", "to mean both the number of axes \n", "and the length along a particular axis.\n", "To avoid this confusion, \n", "we use *order* to refer to the number of axes\n", "and *dimensionality* exclusively to refer \n", "to the number of components.\n", "\n", "\n", "## Matrices\n", "\n", "Just as scalars are $0^{\\textrm{th}}$-order tensors\n", "and vectors are $1^{\\textrm{st}}$-order tensors,\n", "matrices are $2^{\\textrm{nd}}$-order tensors.\n", "We denote matrices by bold capital letters\n", "(e.g., $\\mathbf{X}$, $\\mathbf{Y}$, and $\\mathbf{Z}$),\n", "and represent them in code by tensors with two axes.\n", "The expression $\\mathbf{A} \\in \\mathbb{R}^{m \\times n}$\n", "indicates that a matrix $\\mathbf{A}$ \n", "contains $m \\times n$ real-valued scalars,\n", "arranged as $m$ rows and $n$ columns.\n", "When $m = n$, we say that a matrix is *square*.\n", "Visually, we can illustrate any matrix as a table.\n", "To refer to an individual element,\n", "we subscript both the row and column indices, e.g.,\n", "$a_{ij}$ is the value that belongs to $\\mathbf{A}$'s\n", "$i^{\\textrm{th}}$ row and $j^{\\textrm{th}}$ column:\n", "\n", "$$\\mathbf{A}=\\begin{bmatrix} a_{11} & a_{12} & \\cdots & a_{1n} \\\\ a_{21} & a_{22} & \\cdots & a_{2n} \\\\ \\vdots & \\vdots & \\ddots & \\vdots \\\\ a_{m1} & a_{m2} & \\cdots & a_{mn} \\\\ \\end{bmatrix}.$$\n", ":eqlabel:`eq_matrix_def`\n", "\n", "\n", "In code, we represent a matrix $\\mathbf{A} \\in \\mathbb{R}^{m \\times n}$\n", "by a $2^{\\textrm{nd}}$-order tensor with shape ($m$, $n$).\n", "[**We can convert any appropriately sized $m \\times n$ tensor \n", "into an $m \\times n$ matrix**] \n", "by passing the desired shape to `reshape`:\n" ] }, { "cell_type": "code", "execution_count": 7, "id": "80c49751", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T19:41:53.513569Z", "iopub.status.busy": "2023-08-18T19:41:53.512931Z", "iopub.status.idle": "2023-08-18T19:41:53.518545Z", "shell.execute_reply": "2023-08-18T19:41:53.517740Z" }, "origin_pos": 24, "tab": [ "pytorch" ] }, "outputs": [ { "data": { "text/plain": [ "tensor([[0, 1],\n", " [2, 3],\n", " [4, 5]])" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "A = torch.arange(6).reshape(3, 2)\n", "A" ] }, { "cell_type": "markdown", "id": "0d90da51", "metadata": { "origin_pos": 27 }, "source": [ "Sometimes we want to flip the axes.\n", "When we exchange a matrix's rows and columns,\n", "the result is called its *transpose*.\n", "Formally, we signify a matrix $\\mathbf{A}$'s transpose \n", "by $\\mathbf{A}^\\top$ and if $\\mathbf{B} = \\mathbf{A}^\\top$, \n", "then $b_{ij} = a_{ji}$ for all $i$ and $j$.\n", "Thus, the transpose of an $m \\times n$ matrix \n", "is an $n \\times m$ matrix:\n", "\n", "$$\n", "\\mathbf{A}^\\top =\n", "\\begin{bmatrix}\n", " a_{11} & a_{21} & \\dots & a_{m1} \\\\\n", " a_{12} & a_{22} & \\dots & a_{m2} \\\\\n", " \\vdots & \\vdots & \\ddots & \\vdots \\\\\n", " a_{1n} & a_{2n} & \\dots & a_{mn}\n", "\\end{bmatrix}.\n", "$$\n", "\n", "In code, we can access any (**matrix's transpose**) as follows:\n" ] }, { "cell_type": "code", "execution_count": 8, "id": "7ef1e23b", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T19:41:53.521874Z", "iopub.status.busy": "2023-08-18T19:41:53.521332Z", "iopub.status.idle": "2023-08-18T19:41:53.526566Z", "shell.execute_reply": "2023-08-18T19:41:53.525812Z" }, "origin_pos": 28, "tab": [ "pytorch" ] }, "outputs": [ { "data": { "text/plain": [ "tensor([[0, 2, 4],\n", " [1, 3, 5]])" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "A.T" ] }, { "cell_type": "markdown", "id": "ce337753", "metadata": { "origin_pos": 30 }, "source": [ "[**Symmetric matrices are the subset of square matrices\n", "that are equal to their own transposes:\n", "$\\mathbf{A} = \\mathbf{A}^\\top$.**]\n", "The following matrix is symmetric:\n" ] }, { "cell_type": "code", "execution_count": 9, "id": "028e06ed", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T19:41:53.529939Z", "iopub.status.busy": "2023-08-18T19:41:53.529400Z", "iopub.status.idle": "2023-08-18T19:41:53.535337Z", "shell.execute_reply": "2023-08-18T19:41:53.534568Z" }, "origin_pos": 32, "tab": [ "pytorch" ] }, "outputs": [ { "data": { "text/plain": [ "tensor([[True, True, True],\n", " [True, True, True],\n", " [True, True, True]])" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "A = torch.tensor([[1, 2, 3], [2, 0, 4], [3, 4, 5]])\n", "A == A.T" ] }, { "cell_type": "markdown", "id": "2f945d82", "metadata": { "origin_pos": 35 }, "source": [ "Matrices are useful for representing datasets. \n", "Typically, rows correspond to individual records\n", "and columns correspond to distinct attributes.\n", "\n", "\n", "\n", "## Tensors\n", "\n", "While you can go far in your machine learning journey\n", "with only scalars, vectors, and matrices,\n", "eventually you may need to work with \n", "higher-order [**tensors**].\n", "Tensors (**give us a generic way of describing \n", "extensions to $n^{\\textrm{th}}$-order arrays.**)\n", "We call software objects of the *tensor class* \"tensors\"\n", "precisely because they too can have arbitrary numbers of axes.\n", "While it may be confusing to use the word\n", "*tensor* for both the mathematical object\n", "and its realization in code,\n", "our meaning should usually be clear from context.\n", "We denote general tensors by capital letters \n", "with a special font face\n", "(e.g., $\\mathsf{X}$, $\\mathsf{Y}$, and $\\mathsf{Z}$)\n", "and their indexing mechanism \n", "(e.g., $x_{ijk}$ and $[\\mathsf{X}]_{1, 2i-1, 3}$) \n", "follows naturally from that of matrices.\n", "\n", "Tensors will become more important \n", "when we start working with images.\n", "Each image arrives as a $3^{\\textrm{rd}}$-order tensor\n", "with axes corresponding to the height, width, and *channel*.\n", "At each spatial location, the intensities \n", "of each color (red, green, and blue)\n", "are stacked along the channel. \n", "Furthermore, a collection of images is represented \n", "in code by a $4^{\\textrm{th}}$-order tensor,\n", "where distinct images are indexed\n", "along the first axis.\n", "Higher-order tensors are constructed, as were vectors and matrices,\n", "by growing the number of shape components.\n" ] }, { "cell_type": "code", "execution_count": 10, "id": "306d610e", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T19:41:53.538891Z", "iopub.status.busy": "2023-08-18T19:41:53.538210Z", "iopub.status.idle": "2023-08-18T19:41:53.546164Z", "shell.execute_reply": "2023-08-18T19:41:53.545027Z" }, "origin_pos": 37, "tab": [ "pytorch" ] }, "outputs": [ { "data": { "text/plain": [ "tensor([[[ 0, 1, 2, 3],\n", " [ 4, 5, 6, 7],\n", " [ 8, 9, 10, 11]],\n", "\n", " [[12, 13, 14, 15],\n", " [16, 17, 18, 19],\n", " [20, 21, 22, 23]]])" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "torch.arange(24).reshape(2, 3, 4)" ] }, { "cell_type": "markdown", "id": "3113bae4", "metadata": { "origin_pos": 40 }, "source": [ "## Basic Properties of Tensor Arithmetic\n", "\n", "Scalars, vectors, matrices, \n", "and higher-order tensors\n", "all have some handy properties. \n", "For example, elementwise operations\n", "produce outputs that have the \n", "same shape as their operands.\n" ] }, { "cell_type": "code", "execution_count": 11, "id": "53a34bc0", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T19:41:53.550917Z", "iopub.status.busy": "2023-08-18T19:41:53.550017Z", "iopub.status.idle": "2023-08-18T19:41:53.558241Z", "shell.execute_reply": "2023-08-18T19:41:53.557366Z" }, "origin_pos": 42, "tab": [ "pytorch" ] }, "outputs": [ { "data": { "text/plain": [ "(tensor([[0., 1., 2.],\n", " [3., 4., 5.]]),\n", " tensor([[ 0., 2., 4.],\n", " [ 6., 8., 10.]]))" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "A = torch.arange(6, dtype=torch.float32).reshape(2, 3)\n", "B = A.clone() # Assign a copy of A to B by allocating new memory\n", "A, A + B" ] }, { "cell_type": "markdown", "id": "eb7d4d8e", "metadata": { "origin_pos": 45 }, "source": [ "The [**elementwise product of two matrices\n", "is called their *Hadamard product***] (denoted $\\odot$).\n", "We can spell out the entries \n", "of the Hadamard product of two matrices \n", "$\\mathbf{A}, \\mathbf{B} \\in \\mathbb{R}^{m \\times n}$:\n", "\n", "\n", "\n", "$$\n", "\\mathbf{A} \\odot \\mathbf{B} =\n", "\\begin{bmatrix}\n", " a_{11} b_{11} & a_{12} b_{12} & \\dots & a_{1n} b_{1n} \\\\\n", " a_{21} b_{21} & a_{22} b_{22} & \\dots & a_{2n} b_{2n} \\\\\n", " \\vdots & \\vdots & \\ddots & \\vdots \\\\\n", " a_{m1} b_{m1} & a_{m2} b_{m2} & \\dots & a_{mn} b_{mn}\n", "\\end{bmatrix}.\n", "$$\n" ] }, { "cell_type": "code", "execution_count": 12, "id": "1e2c0645", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T19:41:53.561758Z", "iopub.status.busy": "2023-08-18T19:41:53.561198Z", "iopub.status.idle": "2023-08-18T19:41:53.567597Z", "shell.execute_reply": "2023-08-18T19:41:53.566714Z" }, "origin_pos": 46, "tab": [ "pytorch" ] }, "outputs": [ { "data": { "text/plain": [ "tensor([[ 0., 1., 4.],\n", " [ 9., 16., 25.]])" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "A * B" ] }, { "cell_type": "markdown", "id": "e782293c", "metadata": { "origin_pos": 47 }, "source": [ "[**Adding or multiplying a scalar and a tensor**] produces a result\n", "with the same shape as the original tensor.\n", "Here, each element of the tensor is added to (or multiplied by) the scalar.\n" ] }, { "cell_type": "code", "execution_count": 13, "id": "c5c86fb1", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T19:41:53.571034Z", "iopub.status.busy": "2023-08-18T19:41:53.570428Z", "iopub.status.idle": "2023-08-18T19:41:53.577301Z", "shell.execute_reply": "2023-08-18T19:41:53.576396Z" }, "origin_pos": 49, "tab": [ "pytorch" ] }, "outputs": [ { "data": { "text/plain": [ "(tensor([[[ 2, 3, 4, 5],\n", " [ 6, 7, 8, 9],\n", " [10, 11, 12, 13]],\n", " \n", " [[14, 15, 16, 17],\n", " [18, 19, 20, 21],\n", " [22, 23, 24, 25]]]),\n", " torch.Size([2, 3, 4]))" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = 2\n", "X = torch.arange(24).reshape(2, 3, 4)\n", "a + X, (a * X).shape" ] }, { "cell_type": "markdown", "id": "03bc0c1b", "metadata": { "origin_pos": 52 }, "source": [ "## Reduction\n", ":label:`subsec_lin-alg-reduction`\n", "\n", "Often, we wish to calculate [**the sum of a tensor's elements.**]\n", "To express the sum of the elements in a vector $\\mathbf{x}$ of length $n$,\n", "we write $\\sum_{i=1}^n x_i$. There is a simple function for it:\n" ] }, { "cell_type": "code", "execution_count": 14, "id": "5a3c4cbd", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T19:41:53.580908Z", "iopub.status.busy": "2023-08-18T19:41:53.580306Z", "iopub.status.idle": "2023-08-18T19:41:53.588497Z", "shell.execute_reply": "2023-08-18T19:41:53.587623Z" }, "origin_pos": 54, "tab": [ "pytorch" ] }, "outputs": [ { "data": { "text/plain": [ "(tensor([0., 1., 2.]), tensor(3.))" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x = torch.arange(3, dtype=torch.float32)\n", "x, x.sum()" ] }, { "cell_type": "markdown", "id": "c4e031e9", "metadata": { "origin_pos": 57 }, "source": [ "To express [**sums over the elements of tensors of arbitrary shape**],\n", "we simply sum over all its axes. \n", "For example, the sum of the elements \n", "of an $m \\times n$ matrix $\\mathbf{A}$ \n", "could be written $\\sum_{i=1}^{m} \\sum_{j=1}^{n} a_{ij}$.\n" ] }, { "cell_type": "code", "execution_count": 15, "id": "7594e574", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T19:41:53.593587Z", "iopub.status.busy": "2023-08-18T19:41:53.592920Z", "iopub.status.idle": "2023-08-18T19:41:53.602105Z", "shell.execute_reply": "2023-08-18T19:41:53.600812Z" }, "origin_pos": 58, "tab": [ "pytorch" ] }, "outputs": [ { "data": { "text/plain": [ "(torch.Size([2, 3]), tensor(15.))" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "A.shape, A.sum()" ] }, { "cell_type": "markdown", "id": "2d9a0995", "metadata": { "origin_pos": 60 }, "source": [ "By default, invoking the sum function\n", "*reduces* a tensor along all of its axes,\n", "eventually producing a scalar.\n", "Our libraries also allow us to [**specify the axes \n", "along which the tensor should be reduced.**]\n", "To sum over all elements along the rows (axis 0),\n", "we specify `axis=0` in `sum`.\n", "Since the input matrix reduces along axis 0\n", "to generate the output vector,\n", "this axis is missing from the shape of the output.\n" ] }, { "cell_type": "code", "execution_count": 16, "id": "14d191be", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T19:41:53.606330Z", "iopub.status.busy": "2023-08-18T19:41:53.605594Z", "iopub.status.idle": "2023-08-18T19:41:53.612393Z", "shell.execute_reply": "2023-08-18T19:41:53.611227Z" }, "origin_pos": 61, "tab": [ "pytorch" ] }, "outputs": [ { "data": { "text/plain": [ "(torch.Size([2, 3]), torch.Size([3]))" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "A.shape, A.sum(axis=0).shape" ] }, { "cell_type": "markdown", "id": "22f9f461", "metadata": { "origin_pos": 63 }, "source": [ "Specifying `axis=1` will reduce the column dimension (axis 1) by summing up elements of all the columns.\n" ] }, { "cell_type": "code", "execution_count": 17, "id": "ee3c0559", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T19:41:53.615938Z", "iopub.status.busy": "2023-08-18T19:41:53.615181Z", "iopub.status.idle": "2023-08-18T19:41:53.621919Z", "shell.execute_reply": "2023-08-18T19:41:53.620799Z" }, "origin_pos": 64, "tab": [ "pytorch" ] }, "outputs": [ { "data": { "text/plain": [ "(torch.Size([2, 3]), torch.Size([2]))" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "A.shape, A.sum(axis=1).shape" ] }, { "cell_type": "markdown", "id": "a40d7419", "metadata": { "origin_pos": 66 }, "source": [ "Reducing a matrix along both rows and columns via summation\n", "is equivalent to summing up all the elements of the matrix.\n" ] }, { "cell_type": "code", "execution_count": 18, "id": "25b99ea4", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T19:41:53.625271Z", "iopub.status.busy": "2023-08-18T19:41:53.624779Z", "iopub.status.idle": "2023-08-18T19:41:53.631897Z", "shell.execute_reply": "2023-08-18T19:41:53.630699Z" }, "origin_pos": 67, "tab": [ "pytorch" ] }, "outputs": [ { "data": { "text/plain": [ "tensor(True)" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "A.sum(axis=[0, 1]) == A.sum() # Same as A.sum()" ] }, { "cell_type": "markdown", "id": "46224eef", "metadata": { "origin_pos": 69 }, "source": [ "[**A related quantity is the *mean*, also called the *average*.**]\n", "We calculate the mean by dividing the sum \n", "by the total number of elements.\n", "Because computing the mean is so common,\n", "it gets a dedicated library function \n", "that works analogously to `sum`.\n" ] }, { "cell_type": "code", "execution_count": 19, "id": "9f41e037", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T19:41:53.635407Z", "iopub.status.busy": "2023-08-18T19:41:53.634799Z", "iopub.status.idle": "2023-08-18T19:41:53.642980Z", "shell.execute_reply": "2023-08-18T19:41:53.641833Z" }, "origin_pos": 71, "tab": [ "pytorch" ] }, "outputs": [ { "data": { "text/plain": [ "(tensor(2.5000), tensor(2.5000))" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "A.mean(), A.sum() / A.numel()" ] }, { "cell_type": "markdown", "id": "1c73c2c9", "metadata": { "origin_pos": 73 }, "source": [ "Likewise, the function for calculating the mean \n", "can also reduce a tensor along specific axes.\n" ] }, { "cell_type": "code", "execution_count": 20, "id": "f268d8be", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T19:41:53.646514Z", "iopub.status.busy": "2023-08-18T19:41:53.645792Z", "iopub.status.idle": "2023-08-18T19:41:53.653946Z", "shell.execute_reply": "2023-08-18T19:41:53.652643Z" }, "origin_pos": 74, "tab": [ "pytorch" ] }, "outputs": [ { "data": { "text/plain": [ "(tensor([1.5000, 2.5000, 3.5000]), tensor([1.5000, 2.5000, 3.5000]))" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "A.mean(axis=0), A.sum(axis=0) / A.shape[0]" ] }, { "cell_type": "markdown", "id": "272a70c1", "metadata": { "origin_pos": 76 }, "source": [ "## Non-Reduction Sum\n", ":label:`subsec_lin-alg-non-reduction`\n", "\n", "Sometimes it can be useful to [**keep the number of axes unchanged**]\n", "when invoking the function for calculating the sum or mean. \n", "This matters when we want to use the broadcast mechanism.\n" ] }, { "cell_type": "code", "execution_count": 21, "id": "863c5aca", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T19:41:53.658423Z", "iopub.status.busy": "2023-08-18T19:41:53.658026Z", "iopub.status.idle": "2023-08-18T19:41:53.666522Z", "shell.execute_reply": "2023-08-18T19:41:53.665397Z" }, "origin_pos": 77, "tab": [ "pytorch" ] }, "outputs": [ { "data": { "text/plain": [ "(tensor([[ 3.],\n", " [12.]]),\n", " torch.Size([2, 1]))" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sum_A = A.sum(axis=1, keepdims=True)\n", "sum_A, sum_A.shape" ] }, { "cell_type": "markdown", "id": "db7e1c95", "metadata": { "origin_pos": 79 }, "source": [ "For instance, since `sum_A` keeps its two axes after summing each row,\n", "we can (**divide `A` by `sum_A` with broadcasting**) \n", "to create a matrix where each row sums up to $1$.\n" ] }, { "cell_type": "code", "execution_count": 22, "id": "93d20f26", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T19:41:53.669896Z", "iopub.status.busy": "2023-08-18T19:41:53.669623Z", "iopub.status.idle": "2023-08-18T19:41:53.675548Z", "shell.execute_reply": "2023-08-18T19:41:53.674706Z" }, "origin_pos": 80, "tab": [ "pytorch" ] }, "outputs": [ { "data": { "text/plain": [ "tensor([[0.0000, 0.3333, 0.6667],\n", " [0.2500, 0.3333, 0.4167]])" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "A / sum_A" ] }, { "cell_type": "markdown", "id": "d208f582", "metadata": { "origin_pos": 81 }, "source": [ "If we want to calculate [**the cumulative sum of elements of `A` along some axis**],\n", "say `axis=0` (row by row), we can call the `cumsum` function.\n", "By design, this function does not reduce the input tensor along any axis.\n" ] }, { "cell_type": "code", "execution_count": 23, "id": "e2de0ae7", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T19:41:53.678804Z", "iopub.status.busy": "2023-08-18T19:41:53.678536Z", "iopub.status.idle": "2023-08-18T19:41:53.684437Z", "shell.execute_reply": "2023-08-18T19:41:53.683619Z" }, "origin_pos": 82, "tab": [ "pytorch" ] }, "outputs": [ { "data": { "text/plain": [ "tensor([[0., 1., 2.],\n", " [3., 5., 7.]])" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "A.cumsum(axis=0)" ] }, { "cell_type": "markdown", "id": "a3f6a397", "metadata": { "origin_pos": 84 }, "source": [ "## Dot Products\n", "\n", "So far, we have only performed elementwise operations, sums, and averages. \n", "And if this was all we could do, linear algebra \n", "would not deserve its own section.\n", "Fortunately, this is where things get more interesting.\n", "One of the most fundamental operations is the dot product.\n", "Given two vectors $\\mathbf{x}, \\mathbf{y} \\in \\mathbb{R}^d$,\n", "their *dot product* $\\mathbf{x}^\\top \\mathbf{y}$ (also known as *inner product*, $\\langle \\mathbf{x}, \\mathbf{y} \\rangle$) \n", "is a sum over the products of the elements at the same position: \n", "$\\mathbf{x}^\\top \\mathbf{y} = \\sum_{i=1}^{d} x_i y_i$.\n", "\n", "[~~The *dot product* of two vectors is a sum over the products of the elements at the same position~~]\n" ] }, { "cell_type": "code", "execution_count": 24, "id": "5575e11a", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T19:41:53.687734Z", "iopub.status.busy": "2023-08-18T19:41:53.687178Z", "iopub.status.idle": "2023-08-18T19:41:53.696147Z", "shell.execute_reply": "2023-08-18T19:41:53.695369Z" }, "origin_pos": 86, "tab": [ "pytorch" ] }, "outputs": [ { "data": { "text/plain": [ "(tensor([0., 1., 2.]), tensor([1., 1., 1.]), tensor(3.))" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "y = torch.ones(3, dtype = torch.float32)\n", "x, y, torch.dot(x, y)" ] }, { "cell_type": "markdown", "id": "ba9329e0", "metadata": { "origin_pos": 89 }, "source": [ "Equivalently, (**we can calculate the dot product of two vectors \n", "by performing an elementwise multiplication followed by a sum:**)\n" ] }, { "cell_type": "code", "execution_count": 25, "id": "b5186254", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T19:41:53.699396Z", "iopub.status.busy": "2023-08-18T19:41:53.698843Z", "iopub.status.idle": "2023-08-18T19:41:53.704931Z", "shell.execute_reply": "2023-08-18T19:41:53.703664Z" }, "origin_pos": 91, "tab": [ "pytorch" ] }, "outputs": [ { "data": { "text/plain": [ "tensor(3.)" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "torch.sum(x * y)" ] }, { "cell_type": "markdown", "id": "ebe8aff3", "metadata": { "origin_pos": 94 }, "source": [ "Dot products are useful in a wide range of contexts.\n", "For example, given some set of values,\n", "denoted by a vector $\\mathbf{x} \\in \\mathbb{R}^n$,\n", "and a set of weights, denoted by $\\mathbf{w} \\in \\mathbb{R}^n$,\n", "the weighted sum of the values in $\\mathbf{x}$\n", "according to the weights $\\mathbf{w}$\n", "could be expressed as the dot product $\\mathbf{x}^\\top \\mathbf{w}$.\n", "When the weights are nonnegative\n", "and sum to $1$, i.e., $\\left(\\sum_{i=1}^{n} {w_i} = 1\\right)$,\n", "the dot product expresses a *weighted average*.\n", "After normalizing two vectors to have unit length,\n", "the dot products express the cosine of the angle between them.\n", "Later in this section, we will formally introduce this notion of *length*.\n", "\n", "\n", "## Matrix--Vector Products\n", "\n", "Now that we know how to calculate dot products,\n", "we can begin to understand the *product*\n", "between an $m \\times n$ matrix $\\mathbf{A}$ \n", "and an $n$-dimensional vector $\\mathbf{x}$.\n", "To start off, we visualize our matrix\n", "in terms of its row vectors\n", "\n", "$$\\mathbf{A}=\n", "\\begin{bmatrix}\n", "\\mathbf{a}^\\top_{1} \\\\\n", "\\mathbf{a}^\\top_{2} \\\\\n", "\\vdots \\\\\n", "\\mathbf{a}^\\top_m \\\\\n", "\\end{bmatrix},$$\n", "\n", "where each $\\mathbf{a}^\\top_{i} \\in \\mathbb{R}^n$\n", "is a row vector representing the $i^\\textrm{th}$ row \n", "of the matrix $\\mathbf{A}$.\n", "\n", "[**The matrix--vector product $\\mathbf{A}\\mathbf{x}$\n", "is simply a column vector of length $m$,\n", "whose $i^\\textrm{th}$ element is the dot product \n", "$\\mathbf{a}^\\top_i \\mathbf{x}$:**]\n", "\n", "$$\n", "\\mathbf{A}\\mathbf{x}\n", "= \\begin{bmatrix}\n", "\\mathbf{a}^\\top_{1} \\\\\n", "\\mathbf{a}^\\top_{2} \\\\\n", "\\vdots \\\\\n", "\\mathbf{a}^\\top_m \\\\\n", "\\end{bmatrix}\\mathbf{x}\n", "= \\begin{bmatrix}\n", " \\mathbf{a}^\\top_{1} \\mathbf{x} \\\\\n", " \\mathbf{a}^\\top_{2} \\mathbf{x} \\\\\n", "\\vdots\\\\\n", " \\mathbf{a}^\\top_{m} \\mathbf{x}\\\\\n", "\\end{bmatrix}.\n", "$$\n", "\n", "We can think of multiplication with a matrix\n", "$\\mathbf{A}\\in \\mathbb{R}^{m \\times n}$\n", "as a transformation that projects vectors\n", "from $\\mathbb{R}^{n}$ to $\\mathbb{R}^{m}$.\n", "These transformations are remarkably useful.\n", "For example, we can represent rotations\n", "as multiplications by certain square matrices.\n", "Matrix--vector products also describe \n", "the key calculation involved in computing\n", "the outputs of each layer in a neural network\n", "given the outputs from the previous layer.\n" ] }, { "cell_type": "markdown", "id": "b3769117", "metadata": { "origin_pos": 96, "tab": [ "pytorch" ] }, "source": [ "To express a matrix--vector product in code,\n", "we use the `mv` function. \n", "Note that the column dimension of `A` \n", "(its length along axis 1)\n", "must be the same as the dimension of `x` (its length). \n", "Python has a convenience operator `@` \n", "that can execute both matrix--vector\n", "and matrix--matrix products\n", "(depending on its arguments). \n", "Thus we can write `A@x`.\n" ] }, { "cell_type": "code", "execution_count": 26, "id": "1a99c29a", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T19:41:53.710181Z", "iopub.status.busy": "2023-08-18T19:41:53.709041Z", "iopub.status.idle": "2023-08-18T19:41:53.719479Z", "shell.execute_reply": "2023-08-18T19:41:53.718068Z" }, "origin_pos": 99, "tab": [ "pytorch" ] }, "outputs": [ { "data": { "text/plain": [ "(torch.Size([2, 3]), torch.Size([3]), tensor([ 5., 14.]), tensor([ 5., 14.]))" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "A.shape, x.shape, torch.mv(A, x), A@x" ] }, { "cell_type": "markdown", "id": "00e00436", "metadata": { "origin_pos": 102 }, "source": [ "## Matrix--Matrix Multiplication\n", "\n", "Once you have gotten the hang of dot products and matrix--vector products,\n", "then *matrix--matrix multiplication* should be straightforward.\n", "\n", "Say that we have two matrices \n", "$\\mathbf{A} \\in \\mathbb{R}^{n \\times k}$ \n", "and $\\mathbf{B} \\in \\mathbb{R}^{k \\times m}$:\n", "\n", "$$\\mathbf{A}=\\begin{bmatrix}\n", " a_{11} & a_{12} & \\cdots & a_{1k} \\\\\n", " a_{21} & a_{22} & \\cdots & a_{2k} \\\\\n", "\\vdots & \\vdots & \\ddots & \\vdots \\\\\n", " a_{n1} & a_{n2} & \\cdots & a_{nk} \\\\\n", "\\end{bmatrix},\\quad\n", "\\mathbf{B}=\\begin{bmatrix}\n", " b_{11} & b_{12} & \\cdots & b_{1m} \\\\\n", " b_{21} & b_{22} & \\cdots & b_{2m} \\\\\n", "\\vdots & \\vdots & \\ddots & \\vdots \\\\\n", " b_{k1} & b_{k2} & \\cdots & b_{km} \\\\\n", "\\end{bmatrix}.$$\n", "\n", "\n", "Let $\\mathbf{a}^\\top_{i} \\in \\mathbb{R}^k$ denote \n", "the row vector representing the $i^\\textrm{th}$ row \n", "of the matrix $\\mathbf{A}$\n", "and let $\\mathbf{b}_{j} \\in \\mathbb{R}^k$ denote \n", "the column vector from the $j^\\textrm{th}$ column \n", "of the matrix $\\mathbf{B}$:\n", "\n", "$$\\mathbf{A}=\n", "\\begin{bmatrix}\n", "\\mathbf{a}^\\top_{1} \\\\\n", "\\mathbf{a}^\\top_{2} \\\\\n", "\\vdots \\\\\n", "\\mathbf{a}^\\top_n \\\\\n", "\\end{bmatrix},\n", "\\quad \\mathbf{B}=\\begin{bmatrix}\n", " \\mathbf{b}_{1} & \\mathbf{b}_{2} & \\cdots & \\mathbf{b}_{m} \\\\\n", "\\end{bmatrix}.\n", "$$\n", "\n", "\n", "To form the matrix product $\\mathbf{C} \\in \\mathbb{R}^{n \\times m}$,\n", "we simply compute each element $c_{ij}$\n", "as the dot product between \n", "the $i^{\\textrm{th}}$ row of $\\mathbf{A}$\n", "and the $j^{\\textrm{th}}$ column of $\\mathbf{B}$,\n", "i.e., $\\mathbf{a}^\\top_i \\mathbf{b}_j$:\n", "\n", "$$\\mathbf{C} = \\mathbf{AB} = \\begin{bmatrix}\n", "\\mathbf{a}^\\top_{1} \\\\\n", "\\mathbf{a}^\\top_{2} \\\\\n", "\\vdots \\\\\n", "\\mathbf{a}^\\top_n \\\\\n", "\\end{bmatrix}\n", "\\begin{bmatrix}\n", " \\mathbf{b}_{1} & \\mathbf{b}_{2} & \\cdots & \\mathbf{b}_{m} \\\\\n", "\\end{bmatrix}\n", "= \\begin{bmatrix}\n", "\\mathbf{a}^\\top_{1} \\mathbf{b}_1 & \\mathbf{a}^\\top_{1}\\mathbf{b}_2& \\cdots & \\mathbf{a}^\\top_{1} \\mathbf{b}_m \\\\\n", " \\mathbf{a}^\\top_{2}\\mathbf{b}_1 & \\mathbf{a}^\\top_{2} \\mathbf{b}_2 & \\cdots & \\mathbf{a}^\\top_{2} \\mathbf{b}_m \\\\\n", " \\vdots & \\vdots & \\ddots &\\vdots\\\\\n", "\\mathbf{a}^\\top_{n} \\mathbf{b}_1 & \\mathbf{a}^\\top_{n}\\mathbf{b}_2& \\cdots& \\mathbf{a}^\\top_{n} \\mathbf{b}_m\n", "\\end{bmatrix}.\n", "$$\n", "\n", "[**We can think of the matrix--matrix multiplication $\\mathbf{AB}$\n", "as performing $m$ matrix--vector products \n", "or $m \\times n$ dot products \n", "and stitching the results together \n", "to form an $n \\times m$ matrix.**]\n", "In the following snippet, \n", "we perform matrix multiplication on `A` and `B`.\n", "Here, `A` is a matrix with two rows and three columns,\n", "and `B` is a matrix with three rows and four columns.\n", "After multiplication, we obtain a matrix with two rows and four columns.\n" ] }, { "cell_type": "code", "execution_count": 27, "id": "99535047", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T19:41:53.723651Z", "iopub.status.busy": "2023-08-18T19:41:53.722762Z", "iopub.status.idle": "2023-08-18T19:41:53.732227Z", "shell.execute_reply": "2023-08-18T19:41:53.731088Z" }, "origin_pos": 104, "tab": [ "pytorch" ] }, "outputs": [ { "data": { "text/plain": [ "(tensor([[ 3., 3., 3., 3.],\n", " [12., 12., 12., 12.]]),\n", " tensor([[ 3., 3., 3., 3.],\n", " [12., 12., 12., 12.]]))" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "B = torch.ones(3, 4)\n", "torch.mm(A, B), A@B" ] }, { "cell_type": "markdown", "id": "28a86db3", "metadata": { "origin_pos": 107 }, "source": [ "The term *matrix--matrix multiplication* is \n", "often simplified to *matrix multiplication*,\n", "and should not be confused with the Hadamard product.\n", "\n", "\n", "## Norms\n", ":label:`subsec_lin-algebra-norms`\n", "\n", "Some of the most useful operators in linear algebra are *norms*.\n", "Informally, the norm of a vector tells us how *big* it is. \n", "For instance, the $\\ell_2$ norm measures\n", "the (Euclidean) length of a vector.\n", "Here, we are employing a notion of *size* that concerns the magnitude of a vector's components\n", "(not its dimensionality). \n", "\n", "A norm is a function $\\| \\cdot \\|$ that maps a vector\n", "to a scalar and satisfies the following three properties:\n", "\n", "1. Given any vector $\\mathbf{x}$, if we scale (all elements of) the vector \n", " by a scalar $\\alpha \\in \\mathbb{R}$, its norm scales accordingly:\n", " $$\\|\\alpha \\mathbf{x}\\| = |\\alpha| \\|\\mathbf{x}\\|.$$\n", "2. For any vectors $\\mathbf{x}$ and $\\mathbf{y}$:\n", " norms satisfy the triangle inequality:\n", " $$\\|\\mathbf{x} + \\mathbf{y}\\| \\leq \\|\\mathbf{x}\\| + \\|\\mathbf{y}\\|.$$\n", "3. The norm of a vector is nonnegative and it only vanishes if the vector is zero:\n", " $$\\|\\mathbf{x}\\| > 0 \\textrm{ for all } \\mathbf{x} \\neq 0.$$\n", "\n", "Many functions are valid norms and different norms \n", "encode different notions of size. \n", "The Euclidean norm that we all learned in elementary school geometry\n", "when calculating the hypotenuse of a right triangle\n", "is the square root of the sum of squares of a vector's elements.\n", "Formally, this is called [**the $\\ell_2$ *norm***] and expressed as\n", "\n", "(**$$\\|\\mathbf{x}\\|_2 = \\sqrt{\\sum_{i=1}^n x_i^2}.$$**)\n", "\n", "The method `norm` calculates the $\\ell_2$ norm.\n" ] }, { "cell_type": "code", "execution_count": 28, "id": "e215c544", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T19:41:53.735890Z", "iopub.status.busy": "2023-08-18T19:41:53.735108Z", "iopub.status.idle": "2023-08-18T19:41:53.742412Z", "shell.execute_reply": "2023-08-18T19:41:53.741311Z" }, "origin_pos": 109, "tab": [ "pytorch" ] }, "outputs": [ { "data": { "text/plain": [ "tensor(5.)" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "u = torch.tensor([3.0, -4.0])\n", "torch.norm(u)" ] }, { "cell_type": "markdown", "id": "d80835a0", "metadata": { "origin_pos": 112 }, "source": [ "[**The $\\ell_1$ norm**] is also common \n", "and the associated measure is called the Manhattan distance. \n", "By definition, the $\\ell_1$ norm sums \n", "the absolute values of a vector's elements:\n", "\n", "(**$$\\|\\mathbf{x}\\|_1 = \\sum_{i=1}^n \\left|x_i \\right|.$$**)\n", "\n", "Compared to the $\\ell_2$ norm, it is less sensitive to outliers.\n", "To compute the $\\ell_1$ norm, \n", "we compose the absolute value\n", "with the sum operation.\n" ] }, { "cell_type": "code", "execution_count": 29, "id": "8a3e0562", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T19:41:53.746107Z", "iopub.status.busy": "2023-08-18T19:41:53.745359Z", "iopub.status.idle": "2023-08-18T19:41:53.752438Z", "shell.execute_reply": "2023-08-18T19:41:53.751302Z" }, "origin_pos": 114, "tab": [ "pytorch" ] }, "outputs": [ { "data": { "text/plain": [ "tensor(7.)" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "torch.abs(u).sum()" ] }, { "cell_type": "markdown", "id": "727b4843", "metadata": { "origin_pos": 117 }, "source": [ "Both the $\\ell_2$ and $\\ell_1$ norms are special cases\n", "of the more general $\\ell_p$ *norms*:\n", "\n", "$$\\|\\mathbf{x}\\|_p = \\left(\\sum_{i=1}^n \\left|x_i \\right|^p \\right)^{1/p}.$$\n", "\n", "In the case of matrices, matters are more complicated. \n", "After all, matrices can be viewed both as collections of individual entries \n", "*and* as objects that operate on vectors and transform them into other vectors. \n", "For instance, we can ask by how much longer \n", "the matrix--vector product $\\mathbf{X} \\mathbf{v}$ \n", "could be relative to $\\mathbf{v}$. \n", "This line of thought leads to what is called the *spectral* norm. \n", "For now, we introduce [**the *Frobenius norm*, \n", "which is much easier to compute**] and defined as\n", "the square root of the sum of the squares \n", "of a matrix's elements:\n", "\n", "[**$$\\|\\mathbf{X}\\|_\\textrm{F} = \\sqrt{\\sum_{i=1}^m \\sum_{j=1}^n x_{ij}^2}.$$**]\n", "\n", "The Frobenius norm behaves as if it were \n", "an $\\ell_2$ norm of a matrix-shaped vector.\n", "Invoking the following function will calculate \n", "the Frobenius norm of a matrix.\n" ] }, { "cell_type": "code", "execution_count": 30, "id": "3e00a124", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T19:41:53.756072Z", "iopub.status.busy": "2023-08-18T19:41:53.755281Z", "iopub.status.idle": "2023-08-18T19:41:53.762237Z", "shell.execute_reply": "2023-08-18T19:41:53.761172Z" }, "origin_pos": 119, "tab": [ "pytorch" ] }, "outputs": [ { "data": { "text/plain": [ "tensor(6.)" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "torch.norm(torch.ones((4, 9)))" ] }, { "cell_type": "markdown", "id": "b8478a55", "metadata": { "origin_pos": 122 }, "source": [ "While we do not want to get too far ahead of ourselves,\n", "we already can plant some intuition about why these concepts are useful.\n", "In deep learning, we are often trying to solve optimization problems:\n", "*maximize* the probability assigned to observed data;\n", "*maximize* the revenue associated with a recommender model; \n", "*minimize* the distance between predictions\n", "and the ground truth observations; \n", "*minimize* the distance between representations \n", "of photos of the same person \n", "while *maximizing* the distance between representations \n", "of photos of different people. \n", "These distances, which constitute \n", "the objectives of deep learning algorithms, \n", "are often expressed as norms. \n", "\n", "\n", "## Discussion\n", "\n", "In this section, we have reviewed all the linear algebra\n", "that you will need to understand\n", "a significant chunk of modern deep learning.\n", "There is a lot more to linear algebra, though,\n", "and much of it is useful for machine learning.\n", "For example, matrices can be decomposed into factors,\n", "and these decompositions can reveal\n", "low-dimensional structure in real-world datasets.\n", "There are entire subfields of machine learning\n", "that focus on using matrix decompositions\n", "and their generalizations to high-order tensors\n", "to discover structure in datasets \n", "and solve prediction problems.\n", "But this book focuses on deep learning.\n", "And we believe you will be more inclined \n", "to learn more mathematics\n", "once you have gotten your hands dirty\n", "applying machine learning to real datasets.\n", "So while we reserve the right \n", "to introduce more mathematics later on,\n", "we wrap up this section here.\n", "\n", "If you are eager to learn more linear algebra,\n", "there are many excellent books and online resources.\n", "For a more advanced crash course, consider checking out\n", ":citet:`Strang.1993`, :citet:`Kolter.2008`, and :citet:`Petersen.Pedersen.ea.2008`.\n", "\n", "To recap:\n", "\n", "* Scalars, vectors, matrices, and tensors are \n", " the basic mathematical objects used in linear algebra \n", " and have zero, one, two, and an arbitrary number of axes, respectively.\n", "* Tensors can be sliced or reduced along specified axes \n", " via indexing, or operations such as `sum` and `mean`, respectively.\n", "* Elementwise products are called Hadamard products. \n", " By contrast, dot products, matrix--vector products, and matrix--matrix products \n", " are not elementwise operations and in general return objects \n", " having shapes that are different from the the operands. \n", "* Compared to Hadamard products, matrix--matrix products \n", " take considerably longer to compute (cubic rather than quadratic time).\n", "* Norms capture various notions of the magnitude of a vector (or matrix), \n", " and are commonly applied to the difference of two vectors \n", " to measure their distance apart.\n", "* Common vector norms include the $\\ell_1$ and $\\ell_2$ norms, \n", " and common matrix norms include the *spectral* and *Frobenius* norms.\n", "\n", "\n", "## Exercises\n", "\n", "1. Prove that the transpose of the transpose of a matrix is the matrix itself: $(\\mathbf{A}^\\top)^\\top = \\mathbf{A}$.\n", "1. Given two matrices $\\mathbf{A}$ and $\\mathbf{B}$, show that sum and transposition commute: $\\mathbf{A}^\\top + \\mathbf{B}^\\top = (\\mathbf{A} + \\mathbf{B})^\\top$.\n", "1. Given any square matrix $\\mathbf{A}$, is $\\mathbf{A} + \\mathbf{A}^\\top$ always symmetric? Can you prove the result by using only the results of the previous two exercises?\n", "1. We defined the tensor `X` of shape (2, 3, 4) in this section. What is the output of `len(X)`? Write your answer without implementing any code, then check your answer using code. \n", "1. For a tensor `X` of arbitrary shape, does `len(X)` always correspond to the length of a certain axis of `X`? What is that axis?\n", "1. Run `A / A.sum(axis=1)` and see what happens. Can you analyze the results?\n", "1. When traveling between two points in downtown Manhattan, what is the distance that you need to cover in terms of the coordinates, i.e., in terms of avenues and streets? Can you travel diagonally?\n", "1. Consider a tensor of shape (2, 3, 4). What are the shapes of the summation outputs along axes 0, 1, and 2?\n", "1. Feed a tensor with three or more axes to the `linalg.norm` function and observe its output. What does this function compute for tensors of arbitrary shape?\n", "1. Consider three large matrices, say $\\mathbf{A} \\in \\mathbb{R}^{2^{10} \\times 2^{16}}$, $\\mathbf{B} \\in \\mathbb{R}^{2^{16} \\times 2^{5}}$ and $\\mathbf{C} \\in \\mathbb{R}^{2^{5} \\times 2^{14}}$, initialized with Gaussian random variables. You want to compute the product $\\mathbf{A} \\mathbf{B} \\mathbf{C}$. Is there any difference in memory footprint and speed, depending on whether you compute $(\\mathbf{A} \\mathbf{B}) \\mathbf{C}$ or $\\mathbf{A} (\\mathbf{B} \\mathbf{C})$. Why?\n", "1. Consider three large matrices, say $\\mathbf{A} \\in \\mathbb{R}^{2^{10} \\times 2^{16}}$, $\\mathbf{B} \\in \\mathbb{R}^{2^{16} \\times 2^{5}}$ and $\\mathbf{C} \\in \\mathbb{R}^{2^{5} \\times 2^{16}}$. Is there any difference in speed depending on whether you compute $\\mathbf{A} \\mathbf{B}$ or $\\mathbf{A} \\mathbf{C}^\\top$? Why? What changes if you initialize $\\mathbf{C} = \\mathbf{B}^\\top$ without cloning memory? Why?\n", "1. Consider three matrices, say $\\mathbf{A}, \\mathbf{B}, \\mathbf{C} \\in \\mathbb{R}^{100 \\times 200}$. Construct a tensor with three axes by stacking $[\\mathbf{A}, \\mathbf{B}, \\mathbf{C}]$. What is the dimensionality? Slice out the second coordinate of the third axis to recover $\\mathbf{B}$. Check that your answer is correct.\n" ] }, { "cell_type": "markdown", "id": "9f0b33af", "metadata": { "origin_pos": 124, "tab": [ "pytorch" ] }, "source": [ "[Discussions](https://discuss.d2l.ai/t/31)\n" ] } ], "metadata": { "language_info": { "name": "python" }, "required_libs": [] }, "nbformat": 4, "nbformat_minor": 5 }