{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "8e54cd7b",
   "metadata": {
    "origin_pos": 0
   },
   "source": [
    "# 数据操作\n",
    ":label:`sec_ndarray`\n",
    "\n",
    "为了能够完成各种数据操作，我们需要某种方法来存储和操作数据。\n",
    "通常，我们需要做两件重要的事：（1）获取数据；（2）将数据读入计算机后对其进行处理。\n",
    "如果没有某种方法来存储数据，那么获取数据是没有意义的。\n",
    "\n",
    "首先，我们介绍$n$维数组，也称为*张量*（tensor）。\n",
    "使用过Python中NumPy计算包的读者会对本部分很熟悉。\n",
    "无论使用哪个深度学习框架，它的*张量类*（在MXNet中为`ndarray`，\n",
    "在PyTorch和TensorFlow中为`Tensor`）都与Numpy的`ndarray`类似。\n",
    "但深度学习框架又比Numpy的`ndarray`多一些重要功能：\n",
    "首先，GPU很好地支持加速计算，而NumPy仅支持CPU计算；\n",
    "其次，张量类支持自动微分。\n",
    "这些功能使得张量类更适合深度学习。\n",
    "如果没有特殊说明，本书中所说的张量均指的是张量类的实例。\n",
    "\n",
    "## 入门\n",
    "\n",
    "本节的目标是帮助读者了解并运行一些在阅读本书的过程中会用到的基本数值计算工具。\n",
    "如果你很难理解一些数学概念或库函数，请不要担心。\n",
    "后面的章节将通过一些实际的例子来回顾这些内容。\n",
    "如果你已经具有相关经验，想要深入学习数学内容，可以跳过本节。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a07b55fb",
   "metadata": {
    "origin_pos": 2,
    "tab": [
     "pytorch"
    ]
   },
   "source": [
    "(**首先，我们导入`torch`。请注意，虽然它被称为PyTorch，但是代码中使用`torch`而不是`pytorch`。**)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "278e6d3f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:05:01.545874Z",
     "iopub.status.busy": "2023-08-18T07:05:01.545147Z",
     "iopub.status.idle": "2023-08-18T07:05:02.992816Z",
     "shell.execute_reply": "2023-08-18T07:05:02.991719Z"
    },
    "origin_pos": 5,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "import torch"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ad15bff7",
   "metadata": {
    "origin_pos": 8
   },
   "source": [
    "[**张量表示一个由数值组成的数组，这个数组可能有多个维度**]。\n",
    "具有一个轴的张量对应数学上的*向量*（vector）；\n",
    "具有两个轴的张量对应数学上的*矩阵*（matrix）；\n",
    "具有两个轴以上的张量没有特殊的数学名称。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0723e844",
   "metadata": {
    "origin_pos": 10,
    "tab": [
     "pytorch"
    ]
   },
   "source": [
    "首先，我们可以使用 `arange` 创建一个行向量 `x`。这个行向量包含以0开始的前12个整数，它们默认创建为整数。也可指定创建类型为浮点数。张量中的每个值都称为张量的 *元素*（element）。例如，张量 `x` 中有 12 个元素。除非额外指定，新的张量将存储在内存中，并采用基于CPU的计算。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "b1700627",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:05:02.997386Z",
     "iopub.status.busy": "2023-08-18T07:05:02.996970Z",
     "iopub.status.idle": "2023-08-18T07:05:03.007632Z",
     "shell.execute_reply": "2023-08-18T07:05:03.006483Z"
    },
    "origin_pos": 13,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x = torch.arange(12)\n",
    "x"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6c8ebb1e",
   "metadata": {
    "origin_pos": 16
   },
   "source": [
    "[**可以通过张量的`shape`属性来访问张量（沿每个轴的长度）的*形状***]\n",
    "(~~和张量中元素的总数~~)。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "b86b6572",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:05:03.011628Z",
     "iopub.status.busy": "2023-08-18T07:05:03.011110Z",
     "iopub.status.idle": "2023-08-18T07:05:03.017191Z",
     "shell.execute_reply": "2023-08-18T07:05:03.016193Z"
    },
    "origin_pos": 17,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "torch.Size([12])"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x.shape"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "25cabae8",
   "metadata": {
    "origin_pos": 18
   },
   "source": [
    "如果只想知道张量中元素的总数，即形状的所有元素乘积，可以检查它的大小（size）。\n",
    "因为这里在处理的是一个向量，所以它的`shape`与它的`size`相同。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "b8b69ca9",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:05:03.020938Z",
     "iopub.status.busy": "2023-08-18T07:05:03.020483Z",
     "iopub.status.idle": "2023-08-18T07:05:03.026998Z",
     "shell.execute_reply": "2023-08-18T07:05:03.025752Z"
    },
    "origin_pos": 20,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "12"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x.numel()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "af15bcd6",
   "metadata": {
    "origin_pos": 23
   },
   "source": [
    "[**要想改变一个张量的形状而不改变元素数量和元素值，可以调用`reshape`函数。**]\n",
    "例如，可以把张量`x`从形状为（12,）的行向量转换为形状为（3,4）的矩阵。\n",
    "这个新的张量包含与转换前相同的值，但是它被看成一个3行4列的矩阵。\n",
    "要重点说明一下，虽然张量的形状发生了改变，但其元素值并没有变。\n",
    "注意，通过改变张量的形状，张量的大小不会改变。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "0f294243",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:05:03.031842Z",
     "iopub.status.busy": "2023-08-18T07:05:03.031448Z",
     "iopub.status.idle": "2023-08-18T07:05:03.039288Z",
     "shell.execute_reply": "2023-08-18T07:05:03.038227Z"
    },
    "origin_pos": 24,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[ 0,  1,  2,  3],\n",
       "        [ 4,  5,  6,  7],\n",
       "        [ 8,  9, 10, 11]])"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X = x.reshape(3, 4)\n",
    "X"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "eae533a0",
   "metadata": {
    "origin_pos": 27
   },
   "source": [
    "我们不需要通过手动指定每个维度来改变形状。\n",
    "也就是说，如果我们的目标形状是（高度,宽度），\n",
    "那么在知道宽度后，高度会被自动计算得出，不必我们自己做除法。\n",
    "在上面的例子中，为了获得一个3行的矩阵，我们手动指定了它有3行和4列。\n",
    "幸运的是，我们可以通过`-1`来调用此自动计算出维度的功能。\n",
    "即我们可以用`x.reshape(-1,4)`或`x.reshape(3,-1)`来取代`x.reshape(3,4)`。\n",
    "\n",
    "有时，我们希望[**使用全0、全1、其他常量，或者从特定分布中随机采样的数字**]来初始化矩阵。\n",
    "我们可以创建一个形状为（2,3,4）的张量，其中所有元素都设置为0。代码如下：\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "b23c3056",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:05:03.044733Z",
     "iopub.status.busy": "2023-08-18T07:05:03.043866Z",
     "iopub.status.idle": "2023-08-18T07:05:03.052195Z",
     "shell.execute_reply": "2023-08-18T07:05:03.051146Z"
    },
    "origin_pos": 29,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[[0., 0., 0., 0.],\n",
       "         [0., 0., 0., 0.],\n",
       "         [0., 0., 0., 0.]],\n",
       "\n",
       "        [[0., 0., 0., 0.],\n",
       "         [0., 0., 0., 0.],\n",
       "         [0., 0., 0., 0.]]])"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "torch.zeros((2, 3, 4))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6a180a12",
   "metadata": {
    "origin_pos": 32
   },
   "source": [
    "同样，我们可以创建一个形状为`(2,3,4)`的张量，其中所有元素都设置为1。代码如下：\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "25981960",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:05:03.057264Z",
     "iopub.status.busy": "2023-08-18T07:05:03.056578Z",
     "iopub.status.idle": "2023-08-18T07:05:03.064973Z",
     "shell.execute_reply": "2023-08-18T07:05:03.063853Z"
    },
    "origin_pos": 34,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[[1., 1., 1., 1.],\n",
       "         [1., 1., 1., 1.],\n",
       "         [1., 1., 1., 1.]],\n",
       "\n",
       "        [[1., 1., 1., 1.],\n",
       "         [1., 1., 1., 1.],\n",
       "         [1., 1., 1., 1.]]])"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "torch.ones((2, 3, 4))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "672f1257",
   "metadata": {
    "origin_pos": 37
   },
   "source": [
    "有时我们想通过从某个特定的概率分布中随机采样来得到张量中每个元素的值。\n",
    "例如，当我们构造数组来作为神经网络中的参数时，我们通常会随机初始化参数的值。\n",
    "以下代码创建一个形状为（3,4）的张量。\n",
    "其中的每个元素都从均值为0、标准差为1的标准高斯分布（正态分布）中随机采样。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "2493f09a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:05:03.069946Z",
     "iopub.status.busy": "2023-08-18T07:05:03.069231Z",
     "iopub.status.idle": "2023-08-18T07:05:03.077304Z",
     "shell.execute_reply": "2023-08-18T07:05:03.076139Z"
    },
    "origin_pos": 39,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[-0.0135,  0.0665,  0.0912,  0.3212],\n",
       "        [ 1.4653,  0.1843, -1.6995, -0.3036],\n",
       "        [ 1.7646,  1.0450,  0.2457, -0.7732]])"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "torch.randn(3, 4)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cc2299f0",
   "metadata": {
    "origin_pos": 42
   },
   "source": [
    "我们还可以[**通过提供包含数值的Python列表（或嵌套列表），来为所需张量中的每个元素赋予确定值**]。\n",
    "在这里，最外层的列表对应于轴0，内层的列表对应于轴1。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "708be494",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:05:03.082360Z",
     "iopub.status.busy": "2023-08-18T07:05:03.081424Z",
     "iopub.status.idle": "2023-08-18T07:05:03.090148Z",
     "shell.execute_reply": "2023-08-18T07:05:03.088973Z"
    },
    "origin_pos": 44,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[2, 1, 4, 3],\n",
       "        [1, 2, 3, 4],\n",
       "        [4, 3, 2, 1]])"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "torch.tensor([[2, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "561a2ec6",
   "metadata": {
    "origin_pos": 47
   },
   "source": [
    "## 运算符\n",
    "\n",
    "我们的兴趣不仅限于读取数据和写入数据。\n",
    "我们想在这些数据上执行数学运算，其中最简单且最有用的操作是*按元素*（elementwise）运算。\n",
    "它们将标准标量运算符应用于数组的每个元素。\n",
    "对于将两个数组作为输入的函数，按元素运算将二元运算符应用于两个数组中的每对位置对应的元素。\n",
    "我们可以基于任何从标量到标量的函数来创建按元素函数。\n",
    "\n",
    "在数学表示法中，我们将通过符号$f: \\mathbb{R} \\rightarrow \\mathbb{R}$\n",
    "来表示*一元*标量运算符（只接收一个输入）。\n",
    "这意味着该函数从任何实数（$\\mathbb{R}$）映射到另一个实数。\n",
    "同样，我们通过符号$f: \\mathbb{R}, \\mathbb{R} \\rightarrow \\mathbb{R}$\n",
    "表示*二元*标量运算符，这意味着该函数接收两个输入，并产生一个输出。\n",
    "给定同一形状的任意两个向量$\\mathbf{u}$和$\\mathbf{v}$和二元运算符$f$，\n",
    "我们可以得到向量$\\mathbf{c} = F(\\mathbf{u},\\mathbf{v})$。\n",
    "具体计算方法是$c_i \\gets f(u_i, v_i)$，\n",
    "其中$c_i$、$u_i$和$v_i$分别是向量$\\mathbf{c}$、$\\mathbf{u}$和$\\mathbf{v}$中的元素。\n",
    "在这里，我们通过将标量函数升级为按元素向量运算来生成向量值\n",
    "$F: \\mathbb{R}^d, \\mathbb{R}^d \\rightarrow \\mathbb{R}^d$。\n",
    "\n",
    "对于任意具有相同形状的张量，\n",
    "[**常见的标准算术运算符（`+`、`-`、`*`、`/`和`**`）都可以被升级为按元素运算**]。\n",
    "我们可以在同一形状的任意两个张量上调用按元素操作。\n",
    "在下面的例子中，我们使用逗号来表示一个具有5个元素的元组，其中每个元素都是按元素操作的结果。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "99b28553",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:05:03.095504Z",
     "iopub.status.busy": "2023-08-18T07:05:03.094688Z",
     "iopub.status.idle": "2023-08-18T07:05:03.106084Z",
     "shell.execute_reply": "2023-08-18T07:05:03.104976Z"
    },
    "origin_pos": 49,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(tensor([ 3.,  4.,  6., 10.]),\n",
       " tensor([-1.,  0.,  2.,  6.]),\n",
       " tensor([ 2.,  4.,  8., 16.]),\n",
       " tensor([0.5000, 1.0000, 2.0000, 4.0000]),\n",
       " tensor([ 1.,  4., 16., 64.]))"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x = torch.tensor([1.0, 2, 4, 8])\n",
    "y = torch.tensor([2, 2, 2, 2])\n",
    "x + y, x - y, x * y, x / y, x ** y  # **运算符是求幂运算"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1d37bed5",
   "metadata": {
    "origin_pos": 52
   },
   "source": [
    "(**“按元素”方式可以应用更多的计算**)，包括像求幂这样的一元运算符。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "ef07c995",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:05:03.110973Z",
     "iopub.status.busy": "2023-08-18T07:05:03.110221Z",
     "iopub.status.idle": "2023-08-18T07:05:03.120389Z",
     "shell.execute_reply": "2023-08-18T07:05:03.119471Z"
    },
    "origin_pos": 54,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([2.7183e+00, 7.3891e+00, 5.4598e+01, 2.9810e+03])"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "torch.exp(x)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cc76ca21",
   "metadata": {
    "origin_pos": 57
   },
   "source": [
    "除了按元素计算外，我们还可以执行线性代数运算，包括向量点积和矩阵乘法。\n",
    "我们将在 :numref:`sec_linear-algebra`中解释线性代数的重点内容。\n",
    "\n",
    "[**我们也可以把多个张量*连结*（concatenate）在一起**]，\n",
    "把它们端对端地叠起来形成一个更大的张量。\n",
    "我们只需要提供张量列表，并给出沿哪个轴连结。\n",
    "下面的例子分别演示了当我们沿行（轴-0，形状的第一个元素）\n",
    "和按列（轴-1，形状的第二个元素）连结两个矩阵时，会发生什么情况。\n",
    "我们可以看到，第一个输出张量的轴-0长度（$6$）是两个输入张量轴-0长度的总和（$3 + 3$）；\n",
    "第二个输出张量的轴-1长度（$8$）是两个输入张量轴-1长度的总和（$4 + 4$）。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "a583b891",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:05:03.125263Z",
     "iopub.status.busy": "2023-08-18T07:05:03.124477Z",
     "iopub.status.idle": "2023-08-18T07:05:03.136328Z",
     "shell.execute_reply": "2023-08-18T07:05:03.135199Z"
    },
    "origin_pos": 59,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(tensor([[ 0.,  1.,  2.,  3.],\n",
       "         [ 4.,  5.,  6.,  7.],\n",
       "         [ 8.,  9., 10., 11.],\n",
       "         [ 2.,  1.,  4.,  3.],\n",
       "         [ 1.,  2.,  3.,  4.],\n",
       "         [ 4.,  3.,  2.,  1.]]),\n",
       " tensor([[ 0.,  1.,  2.,  3.,  2.,  1.,  4.,  3.],\n",
       "         [ 4.,  5.,  6.,  7.,  1.,  2.,  3.,  4.],\n",
       "         [ 8.,  9., 10., 11.,  4.,  3.,  2.,  1.]]))"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X = torch.arange(12, dtype=torch.float32).reshape((3,4))\n",
    "Y = torch.tensor([[2.0, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])\n",
    "torch.cat((X, Y), dim=0), torch.cat((X, Y), dim=1)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "44965a95",
   "metadata": {
    "origin_pos": 62
   },
   "source": [
    "有时，我们想[**通过*逻辑运算符*构建二元张量**]。\n",
    "以`X == Y`为例：\n",
    "对于每个位置，如果`X`和`Y`在该位置相等，则新张量中相应项的值为1。\n",
    "这意味着逻辑语句`X == Y`在该位置处为真，否则该位置为0。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "6405ec63",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:05:03.141449Z",
     "iopub.status.busy": "2023-08-18T07:05:03.140776Z",
     "iopub.status.idle": "2023-08-18T07:05:03.148692Z",
     "shell.execute_reply": "2023-08-18T07:05:03.147491Z"
    },
    "origin_pos": 63,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[False,  True, False,  True],\n",
       "        [False, False, False, False],\n",
       "        [False, False, False, False]])"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X == Y"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ffab6a71",
   "metadata": {
    "origin_pos": 64
   },
   "source": [
    "[**对张量中的所有元素进行求和，会产生一个单元素张量。**]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "a13cb291",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:05:03.153907Z",
     "iopub.status.busy": "2023-08-18T07:05:03.152814Z",
     "iopub.status.idle": "2023-08-18T07:05:03.160277Z",
     "shell.execute_reply": "2023-08-18T07:05:03.159188Z"
    },
    "origin_pos": 65,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor(66.)"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X.sum()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e4420b99",
   "metadata": {
    "origin_pos": 67
   },
   "source": [
    "## 广播机制\n",
    ":label:`subsec_broadcasting`\n",
    "\n",
    "在上面的部分中，我们看到了如何在相同形状的两个张量上执行按元素操作。\n",
    "在某些情况下，[**即使形状不同，我们仍然可以通过调用\n",
    "*广播机制*（broadcasting mechanism）来执行按元素操作**]。\n",
    "这种机制的工作方式如下：\n",
    "\n",
    "1. 通过适当复制元素来扩展一个或两个数组，以便在转换之后，两个张量具有相同的形状；\n",
    "2. 对生成的数组执行按元素操作。\n",
    "\n",
    "在大多数情况下，我们将沿着数组中长度为1的轴进行广播，如下例子：\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "a1de79a2",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:05:03.165305Z",
     "iopub.status.busy": "2023-08-18T07:05:03.164274Z",
     "iopub.status.idle": "2023-08-18T07:05:03.172771Z",
     "shell.execute_reply": "2023-08-18T07:05:03.171692Z"
    },
    "origin_pos": 69,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(tensor([[0],\n",
       "         [1],\n",
       "         [2]]),\n",
       " tensor([[0, 1]]))"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = torch.arange(3).reshape((3, 1))\n",
    "b = torch.arange(2).reshape((1, 2))\n",
    "a, b"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e4f53984",
   "metadata": {
    "origin_pos": 72
   },
   "source": [
    "由于`a`和`b`分别是$3\\times1$和$1\\times2$矩阵，如果让它们相加，它们的形状不匹配。\n",
    "我们将两个矩阵*广播*为一个更大的$3\\times2$矩阵，如下所示：矩阵`a`将复制列，\n",
    "矩阵`b`将复制行，然后再按元素相加。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "4d8904b1",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:05:03.177900Z",
     "iopub.status.busy": "2023-08-18T07:05:03.176935Z",
     "iopub.status.idle": "2023-08-18T07:05:03.184212Z",
     "shell.execute_reply": "2023-08-18T07:05:03.183156Z"
    },
    "origin_pos": 73,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[0, 1],\n",
       "        [1, 2],\n",
       "        [2, 3]])"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a + b"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "68b62722",
   "metadata": {
    "origin_pos": 74
   },
   "source": [
    "## 索引和切片\n",
    "\n",
    "就像在任何其他Python数组中一样，张量中的元素可以通过索引访问。\n",
    "与任何Python数组一样：第一个元素的索引是0，最后一个元素索引是-1；\n",
    "可以指定范围以包含第一个元素和最后一个之前的元素。\n",
    "\n",
    "如下所示，我们[**可以用`[-1]`选择最后一个元素，可以用`[1:3]`选择第二个和第三个元素**]：\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "b62b00c7",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:05:03.189786Z",
     "iopub.status.busy": "2023-08-18T07:05:03.188961Z",
     "iopub.status.idle": "2023-08-18T07:05:03.197712Z",
     "shell.execute_reply": "2023-08-18T07:05:03.196559Z"
    },
    "origin_pos": 75,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(tensor([ 8.,  9., 10., 11.]),\n",
       " tensor([[ 4.,  5.,  6.,  7.],\n",
       "         [ 8.,  9., 10., 11.]]))"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X[-1], X[1:3]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "49b18803",
   "metadata": {
    "origin_pos": 76,
    "tab": [
     "pytorch"
    ]
   },
   "source": [
    "[**除读取外，我们还可以通过指定索引来将元素写入矩阵。**]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "56a8261a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:05:03.203157Z",
     "iopub.status.busy": "2023-08-18T07:05:03.202390Z",
     "iopub.status.idle": "2023-08-18T07:05:03.210176Z",
     "shell.execute_reply": "2023-08-18T07:05:03.209097Z"
    },
    "origin_pos": 78,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[ 0.,  1.,  2.,  3.],\n",
       "        [ 4.,  5.,  9.,  7.],\n",
       "        [ 8.,  9., 10., 11.]])"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X[1, 2] = 9\n",
    "X"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fdec2856",
   "metadata": {
    "origin_pos": 80
   },
   "source": [
    "如果我们想[**为多个元素赋值相同的值，我们只需要索引所有元素，然后为它们赋值。**]\n",
    "例如，`[0:2, :]`访问第1行和第2行，其中“:”代表沿轴1（列）的所有元素。\n",
    "虽然我们讨论的是矩阵的索引，但这也适用于向量和超过2个维度的张量。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "bd48bae9",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:05:03.214118Z",
     "iopub.status.busy": "2023-08-18T07:05:03.213430Z",
     "iopub.status.idle": "2023-08-18T07:05:03.221215Z",
     "shell.execute_reply": "2023-08-18T07:05:03.220084Z"
    },
    "origin_pos": 81,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[12., 12., 12., 12.],\n",
       "        [12., 12., 12., 12.],\n",
       "        [ 8.,  9., 10., 11.]])"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X[0:2, :] = 12\n",
    "X"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "79660f82",
   "metadata": {
    "origin_pos": 83
   },
   "source": [
    "## 节省内存\n",
    "\n",
    "[**运行一些操作可能会导致为新结果分配内存**]。\n",
    "例如，如果我们用`Y = X + Y`，我们将取消引用`Y`指向的张量，而是指向新分配的内存处的张量。\n",
    "\n",
    "在下面的例子中，我们用Python的`id()`函数演示了这一点，\n",
    "它给我们提供了内存中引用对象的确切地址。\n",
    "运行`Y = Y + X`后，我们会发现`id(Y)`指向另一个位置。\n",
    "这是因为Python首先计算`Y + X`，为结果分配新的内存，然后使`Y`指向内存中的这个新位置。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "6bcd6d07",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:05:03.225106Z",
     "iopub.status.busy": "2023-08-18T07:05:03.224353Z",
     "iopub.status.idle": "2023-08-18T07:05:03.231715Z",
     "shell.execute_reply": "2023-08-18T07:05:03.230626Z"
    },
    "origin_pos": 84,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "before = id(Y)\n",
    "Y = Y + X\n",
    "id(Y) == before"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fdb5a8e4",
   "metadata": {
    "origin_pos": 85
   },
   "source": [
    "这可能是不可取的，原因有两个：\n",
    "\n",
    "1. 首先，我们不想总是不必要地分配内存。在机器学习中，我们可能有数百兆的参数，并且在一秒内多次更新所有参数。通常情况下，我们希望原地执行这些更新；\n",
    "2. 如果我们不原地更新，其他引用仍然会指向旧的内存位置，这样我们的某些代码可能会无意中引用旧的参数。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "47e2e97c",
   "metadata": {
    "origin_pos": 86,
    "tab": [
     "pytorch"
    ]
   },
   "source": [
    "幸运的是，(**执行原地操作**)非常简单。\n",
    "我们可以使用切片表示法将操作的结果分配给先前分配的数组，例如`Y[:] = <expression>`。\n",
    "为了说明这一点，我们首先创建一个新的矩阵`Z`，其形状与另一个`Y`相同，\n",
    "使用`zeros_like`来分配一个全$0$的块。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "13b7fdf6",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:05:03.236933Z",
     "iopub.status.busy": "2023-08-18T07:05:03.236016Z",
     "iopub.status.idle": "2023-08-18T07:05:03.243252Z",
     "shell.execute_reply": "2023-08-18T07:05:03.242153Z"
    },
    "origin_pos": 89,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "id(Z): 140327634811696\n",
      "id(Z): 140327634811696\n"
     ]
    }
   ],
   "source": [
    "Z = torch.zeros_like(Y)\n",
    "print('id(Z):', id(Z))\n",
    "Z[:] = X + Y\n",
    "print('id(Z):', id(Z))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "36a38425",
   "metadata": {
    "origin_pos": 92,
    "tab": [
     "pytorch"
    ]
   },
   "source": [
    "[**如果在后续计算中没有重复使用`X`，\n",
    "我们也可以使用`X[:] = X + Y`或`X += Y`来减少操作的内存开销。**]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "c8a97d75",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:05:03.248290Z",
     "iopub.status.busy": "2023-08-18T07:05:03.247521Z",
     "iopub.status.idle": "2023-08-18T07:05:03.255046Z",
     "shell.execute_reply": "2023-08-18T07:05:03.253935Z"
    },
    "origin_pos": 94,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "before = id(X)\n",
    "X += Y\n",
    "id(X) == before"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3185bd60",
   "metadata": {
    "origin_pos": 96
   },
   "source": [
    "## 转换为其他Python对象\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d871a6fa",
   "metadata": {
    "origin_pos": 98,
    "tab": [
     "pytorch"
    ]
   },
   "source": [
    "将深度学习框架定义的张量[**转换为NumPy张量（`ndarray`）**]很容易，反之也同样容易。\n",
    "torch张量和numpy数组将共享它们的底层内存，就地操作更改一个张量也会同时更改另一个张量。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "7386f580",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:05:03.259655Z",
     "iopub.status.busy": "2023-08-18T07:05:03.259273Z",
     "iopub.status.idle": "2023-08-18T07:05:03.266501Z",
     "shell.execute_reply": "2023-08-18T07:05:03.265738Z"
    },
    "origin_pos": 100,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(numpy.ndarray, torch.Tensor)"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "A = X.numpy()\n",
    "B = torch.tensor(A)\n",
    "type(A), type(B)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "74f0ae4e",
   "metadata": {
    "origin_pos": 103
   },
   "source": [
    "要(**将大小为1的张量转换为Python标量**)，我们可以调用`item`函数或Python的内置函数。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "10a429bd",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:05:03.270566Z",
     "iopub.status.busy": "2023-08-18T07:05:03.270102Z",
     "iopub.status.idle": "2023-08-18T07:05:03.276982Z",
     "shell.execute_reply": "2023-08-18T07:05:03.276051Z"
    },
    "origin_pos": 105,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(tensor([3.5000]), 3.5, 3.5, 3)"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = torch.tensor([3.5])\n",
    "a, a.item(), float(a), int(a)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ed98db5b",
   "metadata": {
    "origin_pos": 108
   },
   "source": [
    "## 小结\n",
    "\n",
    "* 深度学习存储和操作数据的主要接口是张量（$n$维数组）。它提供了各种功能，包括基本数学运算、广播、索引、切片、内存节省和转换其他Python对象。\n",
    "\n",
    "## 练习\n",
    "\n",
    "1. 运行本节中的代码。将本节中的条件语句`X == Y`更改为`X < Y`或`X > Y`，然后看看你可以得到什么样的张量。\n",
    "1. 用其他形状（例如三维张量）替换广播机制中按元素操作的两个张量。结果是否与预期相同？\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "161ce063",
   "metadata": {
    "origin_pos": 110,
    "tab": [
     "pytorch"
    ]
   },
   "source": [
    "[Discussions](https://discuss.d2l.ai/t/1747)\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  },
  "required_libs": []
 },
 "nbformat": 4,
 "nbformat_minor": 5
}