{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "6af409a8",
   "metadata": {
    "origin_pos": 0
   },
   "source": [
    "# 线性代数\n",
    ":label:`sec_linear-algebra`\n",
    "\n",
    "在介绍完如何存储和操作数据后，接下来将简要地回顾一下部分基本线性代数内容。\n",
    "这些内容有助于读者了解和实现本书中介绍的大多数模型。\n",
    "本节将介绍线性代数中的基本数学对象、算术和运算，并用数学符号和相应的代码实现来表示它们。\n",
    "\n",
    "## 标量\n",
    "\n",
    "\n",
    "如果你曾经在餐厅支付餐费，那么应该已经知道一些基本的线性代数，比如在数字间相加或相乘。\n",
    "例如，北京的温度为$52^{\\circ}F$（华氏度，除摄氏度外的另一种温度计量单位）。\n",
    "严格来说，仅包含一个数值被称为*标量*（scalar）。\n",
    "如果要将此华氏度值转换为更常用的摄氏度，\n",
    "则可以计算表达式$c=\\frac{5}{9}(f-32)$，并将$f$赋为$52$。\n",
    "在此等式中，每一项（$5$、$9$和$32$）都是标量值。\n",
    "符号$c$和$f$称为*变量*（variable），它们表示未知的标量值。\n",
    "\n",
    "本书采用了数学表示法，其中标量变量由普通小写字母表示（例如，$x$、$y$和$z$）。\n",
    "本书用$\\mathbb{R}$表示所有（连续）*实数*标量的空间，之后将严格定义*空间*（space）是什么，\n",
    "但现在只要记住表达式$x\\in\\mathbb{R}$是表示$x$是一个实值标量的正式形式。\n",
    "符号$\\in$称为“属于”，它表示“是集合中的成员”。\n",
    "例如$x, y \\in \\{0,1\\}$可以用来表明$x$和$y$是值只能为$0$或$1$的数字。\n",
    "\n",
    "(**标量由只有一个元素的张量表示**)。\n",
    "下面的代码将实例化两个标量，并执行一些熟悉的算术运算，即加法、乘法、除法和指数。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "44889577",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:01:42.354657Z",
     "iopub.status.busy": "2023-08-18T07:01:42.353844Z",
     "iopub.status.idle": "2023-08-18T07:01:43.769394Z",
     "shell.execute_reply": "2023-08-18T07:01:43.768177Z"
    },
    "origin_pos": 2,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(tensor(5.), tensor(6.), tensor(1.5000), tensor(9.))"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import torch\n",
    "\n",
    "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": "018bf250",
   "metadata": {
    "origin_pos": 5
   },
   "source": [
    "## 向量\n",
    "\n",
    "[**向量可以被视为标量值组成的列表**]。\n",
    "这些标量值被称为向量的*元素*（element）或*分量*（component）。\n",
    "当向量表示数据集中的样本时，它们的值具有一定的现实意义。\n",
    "例如，如果我们正在训练一个模型来预测贷款违约风险，可能会将每个申请人与一个向量相关联，\n",
    "其分量与其收入、工作年限、过往违约次数和其他因素相对应。\n",
    "如果我们正在研究医院患者可能面临的心脏病发作风险，可能会用一个向量来表示每个患者，\n",
    "其分量为最近的生命体征、胆固醇水平、每天运动时间等。\n",
    "在数学表示法中，向量通常记为粗体、小写的符号\n",
    "（例如，$\\mathbf{x}$、$\\mathbf{y}$和$\\mathbf{z})$）。\n",
    "\n",
    "人们通过一维张量表示向量。一般来说，张量可以具有任意长度，取决于机器的内存限制。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "e5163ab8",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:01:43.774490Z",
     "iopub.status.busy": "2023-08-18T07:01:43.773987Z",
     "iopub.status.idle": "2023-08-18T07:01:43.781757Z",
     "shell.execute_reply": "2023-08-18T07:01:43.780603Z"
    },
    "origin_pos": 7,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([0, 1, 2, 3])"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x = torch.arange(4)\n",
    "x"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7fc8cd94",
   "metadata": {
    "origin_pos": 10
   },
   "source": [
    "我们可以使用下标来引用向量的任一元素，例如可以通过$x_i$来引用第$i$个元素。\n",
    "注意，元素$x_i$是一个标量，所以我们在引用它时不会加粗。\n",
    "大量文献认为列向量是向量的默认方向，在本书中也是如此。\n",
    "在数学中，向量$\\mathbf{x}$可以写为：\n",
    "\n",
    "$$\\mathbf{x} =\\begin{bmatrix}x_{1}  \\\\x_{2}  \\\\ \\vdots  \\\\x_{n}\\end{bmatrix},$$\n",
    ":eqlabel:`eq_vec_def`\n",
    "\n",
    "其中$x_1,\\ldots,x_n$是向量的元素。在代码中，我们(**通过张量的索引来访问任一元素**)。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "34dd7630",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:01:43.786346Z",
     "iopub.status.busy": "2023-08-18T07:01:43.785939Z",
     "iopub.status.idle": "2023-08-18T07:01:43.793065Z",
     "shell.execute_reply": "2023-08-18T07:01:43.791986Z"
    },
    "origin_pos": 12,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor(3)"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x[3]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "59e98e89",
   "metadata": {
    "origin_pos": 15
   },
   "source": [
    "### 长度、维度和形状\n",
    "\n",
    "向量只是一个数字数组，就像每个数组都有一个长度一样，每个向量也是如此。\n",
    "在数学表示法中，如果我们想说一个向量$\\mathbf{x}$由$n$个实值标量组成，\n",
    "可以将其表示为$\\mathbf{x}\\in\\mathbb{R}^n$。\n",
    "向量的长度通常称为向量的*维度*（dimension）。\n",
    "\n",
    "与普通的Python数组一样，我们可以通过调用Python的内置`len()`函数来[**访问张量的长度**]。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "d469059b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:01:43.798087Z",
     "iopub.status.busy": "2023-08-18T07:01:43.797197Z",
     "iopub.status.idle": "2023-08-18T07:01:43.804049Z",
     "shell.execute_reply": "2023-08-18T07:01:43.802867Z"
    },
    "origin_pos": 17,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "4"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(x)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "32d0ccc4",
   "metadata": {
    "origin_pos": 20
   },
   "source": [
    "当用张量表示一个向量（只有一个轴）时，我们也可以通过`.shape`属性访问向量的长度。\n",
    "形状（shape）是一个元素组，列出了张量沿每个轴的长度（维数）。\n",
    "对于(**只有一个轴的张量，形状只有一个元素。**)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "bf9bf15e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:01:43.809543Z",
     "iopub.status.busy": "2023-08-18T07:01:43.808709Z",
     "iopub.status.idle": "2023-08-18T07:01:43.815762Z",
     "shell.execute_reply": "2023-08-18T07:01:43.814675Z"
    },
    "origin_pos": 22,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "torch.Size([4])"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x.shape"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1237aeca",
   "metadata": {
    "origin_pos": 25
   },
   "source": [
    "请注意，*维度*（dimension）这个词在不同上下文时往往会有不同的含义，这经常会使人感到困惑。\n",
    "为了清楚起见，我们在此明确一下：\n",
    "*向量*或*轴*的维度被用来表示*向量*或*轴*的长度，即向量或轴的元素数量。\n",
    "然而，张量的维度用来表示张量具有的轴数。\n",
    "在这个意义上，张量的某个轴的维数就是这个轴的长度。\n",
    "\n",
    "## 矩阵\n",
    "\n",
    "正如向量将标量从零阶推广到一阶，矩阵将向量从一阶推广到二阶。\n",
    "矩阵，我们通常用粗体、大写字母来表示\n",
    "（例如，$\\mathbf{X}$、$\\mathbf{Y}$和$\\mathbf{Z}$），\n",
    "在代码中表示为具有两个轴的张量。\n",
    "\n",
    "数学表示法使用$\\mathbf{A} \\in \\mathbb{R}^{m \\times n}$\n",
    "来表示矩阵$\\mathbf{A}$，其由$m$行和$n$列的实值标量组成。\n",
    "我们可以将任意矩阵$\\mathbf{A} \\in \\mathbb{R}^{m \\times n}$视为一个表格，\n",
    "其中每个元素$a_{ij}$属于第$i$行第$j$列：\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",
    "对于任意$\\mathbf{A} \\in \\mathbb{R}^{m \\times n}$，\n",
    "$\\mathbf{A}$的形状是（$m$,$n$）或$m \\times n$。\n",
    "当矩阵具有相同数量的行和列时，其形状将变为正方形；\n",
    "因此，它被称为*方阵*（square matrix）。\n",
    "\n",
    "当调用函数来实例化张量时，\n",
    "我们可以[**通过指定两个分量$m$和$n$来创建一个形状为$m \\times n$的矩阵**]。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "b1eac085",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:01:43.820985Z",
     "iopub.status.busy": "2023-08-18T07:01:43.820088Z",
     "iopub.status.idle": "2023-08-18T07:01:43.828057Z",
     "shell.execute_reply": "2023-08-18T07:01:43.826957Z"
    },
    "origin_pos": 27,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[ 0,  1,  2,  3],\n",
       "        [ 4,  5,  6,  7],\n",
       "        [ 8,  9, 10, 11],\n",
       "        [12, 13, 14, 15],\n",
       "        [16, 17, 18, 19]])"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "A = torch.arange(20).reshape(5, 4)\n",
    "A"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "15b5181b",
   "metadata": {
    "origin_pos": 30
   },
   "source": [
    "我们可以通过行索引（$i$）和列索引（$j$）来访问矩阵中的标量元素$a_{ij}$，\n",
    "例如$[\\mathbf{A}]_{ij}$。\n",
    "如果没有给出矩阵$\\mathbf{A}$的标量元素，如在 :eqref:`eq_matrix_def`那样，\n",
    "我们可以简单地使用矩阵$\\mathbf{A}$的小写字母索引下标$a_{ij}$\n",
    "来引用$[\\mathbf{A}]_{ij}$。\n",
    "为了表示起来简单，只有在必要时才会将逗号插入到单独的索引中，\n",
    "例如$a_{2,3j}$和$[\\mathbf{A}]_{2i-1,3}$。\n",
    "\n",
    "当我们交换矩阵的行和列时，结果称为矩阵的*转置*（transpose）。\n",
    "通常用$\\mathbf{a}^\\top$来表示矩阵的转置，如果$\\mathbf{B}=\\mathbf{A}^\\top$，\n",
    "则对于任意$i$和$j$，都有$b_{ij}=a_{ji}$。\n",
    "因此，在 :eqref:`eq_matrix_def`中的转置是一个形状为$n \\times m$的矩阵：\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",
    "现在在代码中访问(**矩阵的转置**)。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "289523ed",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:01:43.833285Z",
     "iopub.status.busy": "2023-08-18T07:01:43.832377Z",
     "iopub.status.idle": "2023-08-18T07:01:43.839757Z",
     "shell.execute_reply": "2023-08-18T07:01:43.838656Z"
    },
    "origin_pos": 32,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[ 0,  4,  8, 12, 16],\n",
       "        [ 1,  5,  9, 13, 17],\n",
       "        [ 2,  6, 10, 14, 18],\n",
       "        [ 3,  7, 11, 15, 19]])"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "A.T"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "18ce004f",
   "metadata": {
    "origin_pos": 35
   },
   "source": [
    "作为方阵的一种特殊类型，[***对称矩阵*（symmetric matrix）$\\mathbf{A}$等于其转置：$\\mathbf{A} = \\mathbf{A}^\\top$**]。\n",
    "这里定义一个对称矩阵$\\mathbf{B}$：\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "f0eb414b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:01:43.845394Z",
     "iopub.status.busy": "2023-08-18T07:01:43.844475Z",
     "iopub.status.idle": "2023-08-18T07:01:43.852725Z",
     "shell.execute_reply": "2023-08-18T07:01:43.851678Z"
    },
    "origin_pos": 37,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[1, 2, 3],\n",
       "        [2, 0, 4],\n",
       "        [3, 4, 5]])"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "B = torch.tensor([[1, 2, 3], [2, 0, 4], [3, 4, 5]])\n",
    "B"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9d810164",
   "metadata": {
    "origin_pos": 40
   },
   "source": [
    "现在我们将`B`与它的转置进行比较。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "44cc700c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:01:43.857930Z",
     "iopub.status.busy": "2023-08-18T07:01:43.856978Z",
     "iopub.status.idle": "2023-08-18T07:01:43.864388Z",
     "shell.execute_reply": "2023-08-18T07:01:43.863329Z"
    },
    "origin_pos": 42,
    "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": [
    "B == B.T"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "faa5d327",
   "metadata": {
    "origin_pos": 45
   },
   "source": [
    "矩阵是有用的数据结构：它们允许我们组织具有不同模式的数据。\n",
    "例如，我们矩阵中的行可能对应于不同的房屋（数据样本），而列可能对应于不同的属性。\n",
    "曾经使用过电子表格软件或已阅读过 :numref:`sec_pandas`的人，应该对此很熟悉。\n",
    "因此，尽管单个向量的默认方向是列向量，但在表示表格数据集的矩阵中，\n",
    "将每个数据样本作为矩阵中的行向量更为常见。\n",
    "后面的章节将讲到这点，这种约定将支持常见的深度学习实践。\n",
    "例如，沿着张量的最外轴，我们可以访问或遍历小批量的数据样本。\n",
    "\n",
    "\n",
    "## 张量\n",
    "\n",
    "[**就像向量是标量的推广，矩阵是向量的推广一样，我们可以构建具有更多轴的数据结构**]。\n",
    "张量（本小节中的“张量”指代数对象）是描述具有任意数量轴的$n$维数组的通用方法。\n",
    "例如，向量是一阶张量，矩阵是二阶张量。\n",
    "张量用特殊字体的大写字母表示（例如，$\\mathsf{X}$、$\\mathsf{Y}$和$\\mathsf{Z}$），\n",
    "它们的索引机制（例如$x_{ijk}$和$[\\mathsf{X}]_{1,2i-1,3}$）与矩阵类似。\n",
    "\n",
    "当我们开始处理图像时，张量将变得更加重要，图像以$n$维数组形式出现，\n",
    "其中3个轴对应于高度、宽度，以及一个*通道*（channel）轴，\n",
    "用于表示颜色通道（红色、绿色和蓝色）。\n",
    "现在先将高阶张量暂放一边，而是专注学习其基础知识。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "8f7227a9",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:01:43.869592Z",
     "iopub.status.busy": "2023-08-18T07:01:43.868624Z",
     "iopub.status.idle": "2023-08-18T07:01:43.876563Z",
     "shell.execute_reply": "2023-08-18T07:01:43.875497Z"
    },
    "origin_pos": 47,
    "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": [
    "X = torch.arange(24).reshape(2, 3, 4)\n",
    "X"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e003e028",
   "metadata": {
    "origin_pos": 50
   },
   "source": [
    "## 张量算法的基本性质\n",
    "\n",
    "标量、向量、矩阵和任意数量轴的张量（本小节中的“张量”指代数对象）有一些实用的属性。\n",
    "例如，从按元素操作的定义中可以注意到，任何按元素的一元运算都不会改变其操作数的形状。\n",
    "同样，[**给定具有相同形状的任意两个张量，任何按元素二元运算的结果都将是相同形状的张量**]。\n",
    "例如，将两个相同形状的矩阵相加，会在这两个矩阵上执行元素加法。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "d6c89bd2",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:01:43.881686Z",
     "iopub.status.busy": "2023-08-18T07:01:43.880912Z",
     "iopub.status.idle": "2023-08-18T07:01:43.891206Z",
     "shell.execute_reply": "2023-08-18T07:01:43.890082Z"
    },
    "origin_pos": 52,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(tensor([[ 0.,  1.,  2.,  3.],\n",
       "         [ 4.,  5.,  6.,  7.],\n",
       "         [ 8.,  9., 10., 11.],\n",
       "         [12., 13., 14., 15.],\n",
       "         [16., 17., 18., 19.]]),\n",
       " tensor([[ 0.,  2.,  4.,  6.],\n",
       "         [ 8., 10., 12., 14.],\n",
       "         [16., 18., 20., 22.],\n",
       "         [24., 26., 28., 30.],\n",
       "         [32., 34., 36., 38.]]))"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "A = torch.arange(20, dtype=torch.float32).reshape(5, 4)\n",
    "B = A.clone()  # 通过分配新内存，将A的一个副本分配给B\n",
    "A, A + B"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5f634ff0",
   "metadata": {
    "origin_pos": 55
   },
   "source": [
    "具体而言，[**两个矩阵的按元素乘法称为*Hadamard积*（Hadamard product）（数学符号$\\odot$）**]。\n",
    "对于矩阵$\\mathbf{B} \\in \\mathbb{R}^{m \\times n}$，\n",
    "其中第$i$行和第$j$列的元素是$b_{ij}$。\n",
    "矩阵$\\mathbf{A}$（在 :eqref:`eq_matrix_def`中定义）和$\\mathbf{B}$的Hadamard积为：\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": "1efe4855",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:01:43.896102Z",
     "iopub.status.busy": "2023-08-18T07:01:43.895401Z",
     "iopub.status.idle": "2023-08-18T07:01:43.903331Z",
     "shell.execute_reply": "2023-08-18T07:01:43.902251Z"
    },
    "origin_pos": 57,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[  0.,   1.,   4.,   9.],\n",
       "        [ 16.,  25.,  36.,  49.],\n",
       "        [ 64.,  81., 100., 121.],\n",
       "        [144., 169., 196., 225.],\n",
       "        [256., 289., 324., 361.]])"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "A * B"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dcd1666f",
   "metadata": {
    "origin_pos": 60
   },
   "source": [
    "将张量乘以或加上一个标量不会改变张量的形状，其中张量的每个元素都将与标量相加或相乘。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "587335a3",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:01:43.908593Z",
     "iopub.status.busy": "2023-08-18T07:01:43.907694Z",
     "iopub.status.idle": "2023-08-18T07:01:43.916299Z",
     "shell.execute_reply": "2023-08-18T07:01:43.915117Z"
    },
    "origin_pos": 62,
    "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": "30fee7fa",
   "metadata": {
    "origin_pos": 65
   },
   "source": [
    "## 降维\n",
    "\n",
    ":label:`subseq_lin-alg-reduction`\n",
    "\n",
    "我们可以对任意张量进行的一个有用的操作是[**计算其元素的和**]。\n",
    "数学表示法使用$\\sum$符号表示求和。\n",
    "为了表示长度为$d$的向量中元素的总和，可以记为$\\sum_{i=1}^dx_i$。\n",
    "在代码中可以调用计算求和的函数：\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "32507943",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:01:43.921298Z",
     "iopub.status.busy": "2023-08-18T07:01:43.920499Z",
     "iopub.status.idle": "2023-08-18T07:01:43.929213Z",
     "shell.execute_reply": "2023-08-18T07:01:43.928096Z"
    },
    "origin_pos": 67,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(tensor([0., 1., 2., 3.]), tensor(6.))"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x = torch.arange(4, dtype=torch.float32)\n",
    "x, x.sum()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ae2f651b",
   "metadata": {
    "origin_pos": 70
   },
   "source": [
    "我们可以(**表示任意形状张量的元素和**)。\n",
    "例如，矩阵$\\mathbf{A}$中元素的和可以记为$\\sum_{i=1}^{m} \\sum_{j=1}^{n} a_{ij}$。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "3e0cd60f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:01:43.934058Z",
     "iopub.status.busy": "2023-08-18T07:01:43.933342Z",
     "iopub.status.idle": "2023-08-18T07:01:43.940936Z",
     "shell.execute_reply": "2023-08-18T07:01:43.939832Z"
    },
    "origin_pos": 72,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(torch.Size([5, 4]), tensor(190.))"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "A.shape, A.sum()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d62dab82",
   "metadata": {
    "origin_pos": 75
   },
   "source": [
    "默认情况下，调用求和函数会沿所有的轴降低张量的维度，使它变为一个标量。\n",
    "我们还可以[**指定张量沿哪一个轴来通过求和降低维度**]。\n",
    "以矩阵为例，为了通过求和所有行的元素来降维（轴0），可以在调用函数时指定`axis=0`。\n",
    "由于输入矩阵沿0轴降维以生成输出向量，因此输入轴0的维数在输出形状中消失。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "9420cc92",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:01:43.946290Z",
     "iopub.status.busy": "2023-08-18T07:01:43.945345Z",
     "iopub.status.idle": "2023-08-18T07:01:43.953195Z",
     "shell.execute_reply": "2023-08-18T07:01:43.952092Z"
    },
    "origin_pos": 77,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(tensor([40., 45., 50., 55.]), torch.Size([4]))"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "A_sum_axis0 = A.sum(axis=0)\n",
    "A_sum_axis0, A_sum_axis0.shape"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f166972e",
   "metadata": {
    "origin_pos": 80
   },
   "source": [
    "指定`axis=1`将通过汇总所有列的元素降维（轴1）。因此，输入轴1的维数在输出形状中消失。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "50e59a41",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:01:43.958180Z",
     "iopub.status.busy": "2023-08-18T07:01:43.957431Z",
     "iopub.status.idle": "2023-08-18T07:01:43.965338Z",
     "shell.execute_reply": "2023-08-18T07:01:43.964267Z"
    },
    "origin_pos": 82,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(tensor([ 6., 22., 38., 54., 70.]), torch.Size([5]))"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "A_sum_axis1 = A.sum(axis=1)\n",
    "A_sum_axis1, A_sum_axis1.shape"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1c6fac47",
   "metadata": {
    "origin_pos": 85
   },
   "source": [
    "沿着行和列对矩阵求和，等价于对矩阵的所有元素进行求和。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "e1ba976a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:01:43.970587Z",
     "iopub.status.busy": "2023-08-18T07:01:43.969706Z",
     "iopub.status.idle": "2023-08-18T07:01:43.977405Z",
     "shell.execute_reply": "2023-08-18T07:01:43.976340Z"
    },
    "origin_pos": 87,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor(190.)"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "A.sum(axis=[0, 1])  # 结果和A.sum()相同"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "38057dab",
   "metadata": {
    "origin_pos": 90
   },
   "source": [
    "[**一个与求和相关的量是*平均值*（mean或average）**]。\n",
    "我们通过将总和除以元素总数来计算平均值。\n",
    "在代码中，我们可以调用函数来计算任意形状张量的平均值。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "1d901892",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:01:43.982674Z",
     "iopub.status.busy": "2023-08-18T07:01:43.981742Z",
     "iopub.status.idle": "2023-08-18T07:01:43.990067Z",
     "shell.execute_reply": "2023-08-18T07:01:43.988981Z"
    },
    "origin_pos": 92,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(tensor(9.5000), tensor(9.5000))"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "A.mean(), A.sum() / A.numel()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2d311917",
   "metadata": {
    "origin_pos": 95
   },
   "source": [
    "同样，计算平均值的函数也可以沿指定轴降低张量的维度。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "65c39834",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:01:43.995223Z",
     "iopub.status.busy": "2023-08-18T07:01:43.994254Z",
     "iopub.status.idle": "2023-08-18T07:01:44.003242Z",
     "shell.execute_reply": "2023-08-18T07:01:44.002162Z"
    },
    "origin_pos": 97,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(tensor([ 8.,  9., 10., 11.]), tensor([ 8.,  9., 10., 11.]))"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "A.mean(axis=0), A.sum(axis=0) / A.shape[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7d24d4e3",
   "metadata": {
    "origin_pos": 100
   },
   "source": [
    "### 非降维求和\n",
    "\n",
    ":label:`subseq_lin-alg-non-reduction`\n",
    "\n",
    "但是，有时在调用函数来[**计算总和或均值时保持轴数不变**]会很有用。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "2cc17274",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:01:44.008471Z",
     "iopub.status.busy": "2023-08-18T07:01:44.007568Z",
     "iopub.status.idle": "2023-08-18T07:01:44.016007Z",
     "shell.execute_reply": "2023-08-18T07:01:44.014845Z"
    },
    "origin_pos": 102,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[ 6.],\n",
       "        [22.],\n",
       "        [38.],\n",
       "        [54.],\n",
       "        [70.]])"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sum_A = A.sum(axis=1, keepdims=True)\n",
    "sum_A"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "eae08c05",
   "metadata": {
    "origin_pos": 105
   },
   "source": [
    "例如，由于`sum_A`在对每行进行求和后仍保持两个轴，我们可以(**通过广播将`A`除以`sum_A`**)。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "63a5b49d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:01:44.020992Z",
     "iopub.status.busy": "2023-08-18T07:01:44.020591Z",
     "iopub.status.idle": "2023-08-18T07:01:44.028726Z",
     "shell.execute_reply": "2023-08-18T07:01:44.027663Z"
    },
    "origin_pos": 107,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[0.0000, 0.1667, 0.3333, 0.5000],\n",
       "        [0.1818, 0.2273, 0.2727, 0.3182],\n",
       "        [0.2105, 0.2368, 0.2632, 0.2895],\n",
       "        [0.2222, 0.2407, 0.2593, 0.2778],\n",
       "        [0.2286, 0.2429, 0.2571, 0.2714]])"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "A / sum_A"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fcb2a480",
   "metadata": {
    "origin_pos": 110
   },
   "source": [
    "如果我们想沿[**某个轴计算`A`元素的累积总和**]，\n",
    "比如`axis=0`（按行计算），可以调用`cumsum`函数。\n",
    "此函数不会沿任何轴降低输入张量的维度。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "27eb9655",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:01:44.033849Z",
     "iopub.status.busy": "2023-08-18T07:01:44.033115Z",
     "iopub.status.idle": "2023-08-18T07:01:44.041281Z",
     "shell.execute_reply": "2023-08-18T07:01:44.040150Z"
    },
    "origin_pos": 112,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[ 0.,  1.,  2.,  3.],\n",
       "        [ 4.,  6.,  8., 10.],\n",
       "        [12., 15., 18., 21.],\n",
       "        [24., 28., 32., 36.],\n",
       "        [40., 45., 50., 55.]])"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "A.cumsum(axis=0)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f4dec732",
   "metadata": {
    "origin_pos": 115
   },
   "source": [
    "## 点积（Dot Product）\n",
    "\n",
    "我们已经学习了按元素操作、求和及平均值。\n",
    "另一个最基本的操作之一是点积。\n",
    "给定两个向量$\\mathbf{x},\\mathbf{y}\\in\\mathbb{R}^d$，\n",
    "它们的*点积*（dot product）$\\mathbf{x}^\\top\\mathbf{y}$\n",
    "（或$\\langle\\mathbf{x},\\mathbf{y}\\rangle$）\n",
    "是相同位置的按元素乘积的和：$\\mathbf{x}^\\top \\mathbf{y} = \\sum_{i=1}^{d} x_i y_i$。\n",
    "\n",
    "[~~点积是相同位置的按元素乘积的和~~]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "7840d740",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:01:44.045914Z",
     "iopub.status.busy": "2023-08-18T07:01:44.045514Z",
     "iopub.status.idle": "2023-08-18T07:01:44.058183Z",
     "shell.execute_reply": "2023-08-18T07:01:44.057040Z"
    },
    "origin_pos": 117,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(tensor([0., 1., 2., 3.]), tensor([1., 1., 1., 1.]), tensor(6.))"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "y = torch.ones(4, dtype = torch.float32)\n",
    "x, y, torch.dot(x, y)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "18953e09",
   "metadata": {
    "origin_pos": 120
   },
   "source": [
    "注意，(**我们可以通过执行按元素乘法，然后进行求和来表示两个向量的点积**)：\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "dadc2a45",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:01:44.062812Z",
     "iopub.status.busy": "2023-08-18T07:01:44.062422Z",
     "iopub.status.idle": "2023-08-18T07:01:44.070070Z",
     "shell.execute_reply": "2023-08-18T07:01:44.068907Z"
    },
    "origin_pos": 122,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor(6.)"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "torch.sum(x * y)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "92f4b767",
   "metadata": {
    "origin_pos": 125
   },
   "source": [
    "点积在很多场合都很有用。\n",
    "例如，给定一组由向量$\\mathbf{x} \\in \\mathbb{R}^d$表示的值，\n",
    "和一组由$\\mathbf{w} \\in \\mathbb{R}^d$表示的权重。\n",
    "$\\mathbf{x}$中的值根据权重$\\mathbf{w}$的加权和，\n",
    "可以表示为点积$\\mathbf{x}^\\top \\mathbf{w}$。\n",
    "当权重为非负数且和为1（即$\\left(\\sum_{i=1}^{d}{w_i}=1\\right)$）时，\n",
    "点积表示*加权平均*（weighted average）。\n",
    "将两个向量规范化得到单位长度后，点积表示它们夹角的余弦。\n",
    "本节后面的内容将正式介绍*长度*（length）的概念。\n",
    "\n",
    "## 矩阵-向量积\n",
    "\n",
    "现在我们知道如何计算点积，可以开始理解*矩阵-向量积*（matrix-vector product）。\n",
    "回顾分别在 :eqref:`eq_matrix_def`和 :eqref:`eq_vec_def`中定义的矩阵$\\mathbf{A} \\in \\mathbb{R}^{m \\times n}$和向量$\\mathbf{x} \\in \\mathbb{R}^n$。\n",
    "让我们将矩阵$\\mathbf{A}$用它的行向量表示：\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",
    "其中每个$\\mathbf{a}^\\top_{i} \\in \\mathbb{R}^n$都是行向量，表示矩阵的第$i$行。\n",
    "[**矩阵向量积$\\mathbf{A}\\mathbf{x}$是一个长度为$m$的列向量，\n",
    "其第$i$个元素是点积$\\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",
    "我们可以把一个矩阵$\\mathbf{A} \\in \\mathbb{R}^{m \\times n}$乘法看作一个从$\\mathbb{R}^{n}$到$\\mathbb{R}^{m}$向量的转换。\n",
    "这些转换是非常有用的，例如可以用方阵的乘法来表示旋转。\n",
    "后续章节将讲到，我们也可以使用矩阵-向量积来描述在给定前一层的值时，\n",
    "求解神经网络每一层所需的复杂计算。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2bff356a",
   "metadata": {
    "origin_pos": 127,
    "tab": [
     "pytorch"
    ]
   },
   "source": [
    "在代码中使用张量表示矩阵-向量积，我们使用`mv`函数。\n",
    "当我们为矩阵`A`和向量`x`调用`torch.mv(A, x)`时，会执行矩阵-向量积。\n",
    "注意，`A`的列维数（沿轴1的长度）必须与`x`的维数（其长度）相同。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "62c6809c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:01:44.075294Z",
     "iopub.status.busy": "2023-08-18T07:01:44.074579Z",
     "iopub.status.idle": "2023-08-18T07:01:44.082607Z",
     "shell.execute_reply": "2023-08-18T07:01:44.081496Z"
    },
    "origin_pos": 130,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(torch.Size([5, 4]), torch.Size([4]), tensor([ 14.,  38.,  62.,  86., 110.]))"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "A.shape, x.shape, torch.mv(A, x)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "363d1be1",
   "metadata": {
    "origin_pos": 133
   },
   "source": [
    "## 矩阵-矩阵乘法\n",
    "\n",
    "在掌握点积和矩阵-向量积的知识后，\n",
    "那么**矩阵-矩阵乘法**（matrix-matrix multiplication）应该很简单。\n",
    "\n",
    "假设有两个矩阵$\\mathbf{A} \\in \\mathbb{R}^{n \\times k}$和$\\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",
    "用行向量$\\mathbf{a}^\\top_{i} \\in \\mathbb{R}^k$表示矩阵$\\mathbf{A}$的第$i$行，并让列向量$\\mathbf{b}_{j} \\in \\mathbb{R}^k$作为矩阵$\\mathbf{B}$的第$j$列。要生成矩阵积$\\mathbf{C} = \\mathbf{A}\\mathbf{B}$，最简单的方法是考虑$\\mathbf{A}$的行向量和$\\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",
    "当我们简单地将每个元素$c_{ij}$计算为点积$\\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",
    "[**我们可以将矩阵-矩阵乘法$\\mathbf{AB}$看作简单地执行$m$次矩阵-向量积，并将结果拼接在一起，形成一个$n \\times m$矩阵**]。\n",
    "在下面的代码中，我们在`A`和`B`上执行矩阵乘法。\n",
    "这里的`A`是一个5行4列的矩阵，`B`是一个4行3列的矩阵。\n",
    "两者相乘后，我们得到了一个5行3列的矩阵。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "1e3efc16",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:01:44.087651Z",
     "iopub.status.busy": "2023-08-18T07:01:44.086870Z",
     "iopub.status.idle": "2023-08-18T07:01:44.095375Z",
     "shell.execute_reply": "2023-08-18T07:01:44.094329Z"
    },
    "origin_pos": 135,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[ 6.,  6.,  6.],\n",
       "        [22., 22., 22.],\n",
       "        [38., 38., 38.],\n",
       "        [54., 54., 54.],\n",
       "        [70., 70., 70.]])"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "B = torch.ones(4, 3)\n",
    "torch.mm(A, B)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2fab0ddd",
   "metadata": {
    "origin_pos": 138
   },
   "source": [
    "矩阵-矩阵乘法可以简单地称为**矩阵乘法**，不应与\"Hadamard积\"混淆。\n",
    "\n",
    "## 范数\n",
    ":label:`subsec_lin-algebra-norms`\n",
    "\n",
    "线性代数中最有用的一些运算符是*范数*（norm）。\n",
    "非正式地说，向量的*范数*是表示一个向量有多大。\n",
    "这里考虑的*大小*（size）概念不涉及维度，而是分量的大小。\n",
    "\n",
    "在线性代数中，向量范数是将向量映射到标量的函数$f$。\n",
    "给定任意向量$\\mathbf{x}$，向量范数要满足一些属性。\n",
    "第一个性质是：如果我们按常数因子$\\alpha$缩放向量的所有元素，\n",
    "其范数也会按相同常数因子的*绝对值*缩放：\n",
    "\n",
    "$$f(\\alpha \\mathbf{x}) = |\\alpha| f(\\mathbf{x}).$$\n",
    "\n",
    "第二个性质是熟悉的三角不等式:\n",
    "\n",
    "$$f(\\mathbf{x} + \\mathbf{y}) \\leq f(\\mathbf{x}) + f(\\mathbf{y}).$$\n",
    "\n",
    "第三个性质简单地说范数必须是非负的:\n",
    "\n",
    "$$f(\\mathbf{x}) \\geq 0.$$\n",
    "\n",
    "这是有道理的。因为在大多数情况下，任何东西的最小的*大小*是0。\n",
    "最后一个性质要求范数最小为0，当且仅当向量全由0组成。\n",
    "\n",
    "$$\\forall i, [\\mathbf{x}]_i = 0 \\Leftrightarrow f(\\mathbf{x})=0.$$\n",
    "\n",
    "范数听起来很像距离的度量。\n",
    "欧几里得距离和毕达哥拉斯定理中的非负性概念和三角不等式可能会给出一些启发。\n",
    "事实上，欧几里得距离是一个$L_2$范数：\n",
    "假设$n$维向量$\\mathbf{x}$中的元素是$x_1,\\ldots,x_n$，其[**$L_2$*范数*是向量元素平方和的平方根：**]\n",
    "\n",
    "(**$$\\|\\mathbf{x}\\|_2 = \\sqrt{\\sum_{i=1}^n x_i^2},$$**)\n",
    "\n",
    "其中，在$L_2$范数中常常省略下标$2$，也就是说$\\|\\mathbf{x}\\|$等同于$\\|\\mathbf{x}\\|_2$。\n",
    "在代码中，我们可以按如下方式计算向量的$L_2$范数。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "f829c100",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:01:44.100377Z",
     "iopub.status.busy": "2023-08-18T07:01:44.099628Z",
     "iopub.status.idle": "2023-08-18T07:01:44.107745Z",
     "shell.execute_reply": "2023-08-18T07:01:44.106642Z"
    },
    "origin_pos": 140,
    "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": "c9608c4c",
   "metadata": {
    "origin_pos": 143
   },
   "source": [
    "深度学习中更经常地使用$L_2$范数的平方，也会经常遇到[**$L_1$范数，它表示为向量元素的绝对值之和：**]\n",
    "\n",
    "(**$$\\|\\mathbf{x}\\|_1 = \\sum_{i=1}^n \\left|x_i \\right|.$$**)\n",
    "\n",
    "与$L_2$范数相比，$L_1$范数受异常值的影响较小。\n",
    "为了计算$L_1$范数，我们将绝对值函数和按元素求和组合起来。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "01356584",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:01:44.143775Z",
     "iopub.status.busy": "2023-08-18T07:01:44.142900Z",
     "iopub.status.idle": "2023-08-18T07:01:44.151418Z",
     "shell.execute_reply": "2023-08-18T07:01:44.150335Z"
    },
    "origin_pos": 145,
    "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": "a9454ae0",
   "metadata": {
    "origin_pos": 148
   },
   "source": [
    "$L_2$范数和$L_1$范数都是更一般的$L_p$范数的特例：\n",
    "\n",
    "$$\\|\\mathbf{x}\\|_p = \\left(\\sum_{i=1}^n \\left|x_i \\right|^p \\right)^{1/p}.$$\n",
    "\n",
    "类似于向量的$L_2$范数，[**矩阵**]$\\mathbf{X} \\in \\mathbb{R}^{m \\times n}$(**的*Frobenius范数*（Frobenius norm）是矩阵元素平方和的平方根：**)\n",
    "\n",
    "(**$$\\|\\mathbf{X}\\|_F = \\sqrt{\\sum_{i=1}^m \\sum_{j=1}^n x_{ij}^2}.$$**)\n",
    "\n",
    "Frobenius范数满足向量范数的所有性质，它就像是矩阵形向量的$L_2$范数。\n",
    "调用以下函数将计算矩阵的Frobenius范数。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "0a8792ee",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:01:44.156452Z",
     "iopub.status.busy": "2023-08-18T07:01:44.155694Z",
     "iopub.status.idle": "2023-08-18T07:01:44.163608Z",
     "shell.execute_reply": "2023-08-18T07:01:44.162540Z"
    },
    "origin_pos": 150,
    "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": "4b7470df",
   "metadata": {
    "origin_pos": 153
   },
   "source": [
    "### 范数和目标\n",
    "\n",
    ":label:`subsec_norms_and_objectives`\n",
    "\n",
    "在深度学习中，我们经常试图解决优化问题：\n",
    "*最大化*分配给观测数据的概率;\n",
    "*最小化*预测和真实观测之间的距离。\n",
    "用向量表示物品（如单词、产品或新闻文章），以便最小化相似项目之间的距离，最大化不同项目之间的距离。\n",
    "目标，或许是深度学习算法最重要的组成部分（除了数据），通常被表达为范数。\n",
    "\n",
    "## 关于线性代数的更多信息\n",
    "\n",
    "仅用一节，我们就教会了阅读本书所需的、用以理解现代深度学习的线性代数。\n",
    "线性代数还有很多，其中很多数学对于机器学习非常有用。\n",
    "例如，矩阵可以分解为因子，这些分解可以显示真实世界数据集中的低维结构。\n",
    "机器学习的整个子领域都侧重于使用矩阵分解及其向高阶张量的泛化，来发现数据集中的结构并解决预测问题。\n",
    "当开始动手尝试并在真实数据集上应用了有效的机器学习模型，你会更倾向于学习更多数学。\n",
    "因此，这一节到此结束，本书将在后面介绍更多数学知识。\n",
    "\n",
    "如果渴望了解有关线性代数的更多信息，可以参考[线性代数运算的在线附录](https://d2l.ai/chapter_appendix-mathematics-for-deep-learning/geometry-linear-algebraic-ops.html)或其他优秀资源 :cite:`Strang.1993,Kolter.2008,Petersen.Pedersen.ea.2008`。\n",
    "\n",
    "## 小结\n",
    "\n",
    "* 标量、向量、矩阵和张量是线性代数中的基本数学对象。\n",
    "* 向量泛化自标量，矩阵泛化自向量。\n",
    "* 标量、向量、矩阵和张量分别具有零、一、二和任意数量的轴。\n",
    "* 一个张量可以通过`sum`和`mean`沿指定的轴降低维度。\n",
    "* 两个矩阵的按元素乘法被称为他们的Hadamard积。它与矩阵乘法不同。\n",
    "* 在深度学习中，我们经常使用范数，如$L_1$范数、$L_2$范数和Frobenius范数。\n",
    "* 我们可以对标量、向量、矩阵和张量执行各种操作。\n",
    "\n",
    "## 练习\n",
    "\n",
    "1. 证明一个矩阵$\\mathbf{A}$的转置的转置是$\\mathbf{A}$，即$(\\mathbf{A}^\\top)^\\top = \\mathbf{A}$。\n",
    "1. 给出两个矩阵$\\mathbf{A}$和$\\mathbf{B}$，证明“它们转置的和”等于“它们和的转置”，即$\\mathbf{A}^\\top + \\mathbf{B}^\\top = (\\mathbf{A} + \\mathbf{B})^\\top$。\n",
    "1. 给定任意方阵$\\mathbf{A}$，$\\mathbf{A} + \\mathbf{A}^\\top$总是对称的吗?为什么?\n",
    "1. 本节中定义了形状$(2,3,4)$的张量`X`。`len(X)`的输出结果是什么？\n",
    "1. 对于任意形状的张量`X`,`len(X)`是否总是对应于`X`特定轴的长度?这个轴是什么?\n",
    "1. 运行`A/A.sum(axis=1)`，看看会发生什么。请分析一下原因？\n",
    "1. 考虑一个具有形状$(2,3,4)$的张量，在轴0、1、2上的求和输出是什么形状?\n",
    "1. 为`linalg.norm`函数提供3个或更多轴的张量，并观察其输出。对于任意形状的张量这个函数计算得到什么?\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1ca6f271",
   "metadata": {
    "origin_pos": 155,
    "tab": [
     "pytorch"
    ]
   },
   "source": [
    "[Discussions](https://discuss.d2l.ai/t/1751)\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  },
  "required_libs": []
 },
 "nbformat": 4,
 "nbformat_minor": 5
}