{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "f66f7a20",
   "metadata": {
    "origin_pos": 0
   },
   "source": [
    "# 自定义层\n",
    "\n",
    "深度学习成功背后的一个因素是神经网络的灵活性：\n",
    "我们可以用创造性的方式组合不同的层，从而设计出适用于各种任务的架构。\n",
    "例如，研究人员发明了专门用于处理图像、文本、序列数据和执行动态规划的层。\n",
    "有时我们会遇到或要自己发明一个现在在深度学习框架中还不存在的层。\n",
    "在这些情况下，必须构建自定义层。本节将展示如何构建自定义层。\n",
    "\n",
    "## 不带参数的层\n",
    "\n",
    "首先，我们(**构造一个没有任何参数的自定义层**)。\n",
    "回忆一下在 :numref:`sec_model_construction`对块的介绍，\n",
    "这应该看起来很眼熟。\n",
    "下面的`CenteredLayer`类要从其输入中减去均值。\n",
    "要构建它，我们只需继承基础层类并实现前向传播功能。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "cc3b353a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:07:16.604374Z",
     "iopub.status.busy": "2023-08-18T07:07:16.603752Z",
     "iopub.status.idle": "2023-08-18T07:07:17.492480Z",
     "shell.execute_reply": "2023-08-18T07:07:17.491482Z"
    },
    "origin_pos": 2,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "import torch\n",
    "import torch.nn.functional as F\n",
    "from torch import nn\n",
    "\n",
    "\n",
    "class CenteredLayer(nn.Module):\n",
    "    def __init__(self):\n",
    "        super().__init__()\n",
    "\n",
    "    def forward(self, X):\n",
    "        return X - X.mean()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a3c321cf",
   "metadata": {
    "origin_pos": 5
   },
   "source": [
    "让我们向该层提供一些数据，验证它是否能按预期工作。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "dec68045",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:07:17.497408Z",
     "iopub.status.busy": "2023-08-18T07:07:17.497077Z",
     "iopub.status.idle": "2023-08-18T07:07:17.508357Z",
     "shell.execute_reply": "2023-08-18T07:07:17.507175Z"
    },
    "origin_pos": 7,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([-2., -1.,  0.,  1.,  2.])"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "layer = CenteredLayer()\n",
    "layer(torch.FloatTensor([1, 2, 3, 4, 5]))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9d38600d",
   "metadata": {
    "origin_pos": 10
   },
   "source": [
    "现在，我们可以[**将层作为组件合并到更复杂的模型中**]。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "1b903c3c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:07:17.513247Z",
     "iopub.status.busy": "2023-08-18T07:07:17.512547Z",
     "iopub.status.idle": "2023-08-18T07:07:17.518968Z",
     "shell.execute_reply": "2023-08-18T07:07:17.517886Z"
    },
    "origin_pos": 12,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "net = nn.Sequential(nn.Linear(8, 128), CenteredLayer())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4c48076d",
   "metadata": {
    "origin_pos": 14
   },
   "source": [
    "作为额外的健全性检查，我们可以在向该网络发送随机数据后，检查均值是否为0。\n",
    "由于我们处理的是浮点数，因为存储精度的原因，我们仍然可能会看到一个非常小的非零数。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "6ab302a0",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:07:17.523517Z",
     "iopub.status.busy": "2023-08-18T07:07:17.523140Z",
     "iopub.status.idle": "2023-08-18T07:07:17.534718Z",
     "shell.execute_reply": "2023-08-18T07:07:17.533593Z"
    },
    "origin_pos": 16,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor(7.4506e-09, grad_fn=<MeanBackward0>)"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "Y = net(torch.rand(4, 8))\n",
    "Y.mean()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ca107571",
   "metadata": {
    "origin_pos": 19
   },
   "source": [
    "## [**带参数的层**]\n",
    "\n",
    "以上我们知道了如何定义简单的层，下面我们继续定义具有参数的层，\n",
    "这些参数可以通过训练进行调整。\n",
    "我们可以使用内置函数来创建参数，这些函数提供一些基本的管理功能。\n",
    "比如管理访问、初始化、共享、保存和加载模型参数。\n",
    "这样做的好处之一是：我们不需要为每个自定义层编写自定义的序列化程序。\n",
    "\n",
    "现在，让我们实现自定义版本的全连接层。\n",
    "回想一下，该层需要两个参数，一个用于表示权重，另一个用于表示偏置项。\n",
    "在此实现中，我们使用修正线性单元作为激活函数。\n",
    "该层需要输入参数：`in_units`和`units`，分别表示输入数和输出数。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "8c4a7999",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:07:17.539101Z",
     "iopub.status.busy": "2023-08-18T07:07:17.538729Z",
     "iopub.status.idle": "2023-08-18T07:07:17.546162Z",
     "shell.execute_reply": "2023-08-18T07:07:17.545105Z"
    },
    "origin_pos": 21,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "class MyLinear(nn.Module):\n",
    "    def __init__(self, in_units, units):\n",
    "        super().__init__()\n",
    "        self.weight = nn.Parameter(torch.randn(in_units, units))\n",
    "        self.bias = nn.Parameter(torch.randn(units,))\n",
    "    def forward(self, X):\n",
    "        linear = torch.matmul(X, self.weight.data) + self.bias.data\n",
    "        return F.relu(linear)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "442183c6",
   "metadata": {
    "origin_pos": 25,
    "tab": [
     "pytorch"
    ]
   },
   "source": [
    "接下来，我们实例化`MyLinear`类并访问其模型参数。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "4490005a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:07:17.550522Z",
     "iopub.status.busy": "2023-08-18T07:07:17.550152Z",
     "iopub.status.idle": "2023-08-18T07:07:17.558364Z",
     "shell.execute_reply": "2023-08-18T07:07:17.557338Z"
    },
    "origin_pos": 28,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Parameter containing:\n",
       "tensor([[ 0.1775, -1.4539,  0.3972],\n",
       "        [-0.1339,  0.5273,  1.3041],\n",
       "        [-0.3327, -0.2337, -0.6334],\n",
       "        [ 1.2076, -0.3937,  0.6851],\n",
       "        [-0.4716,  0.0894, -0.9195]], requires_grad=True)"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "linear = MyLinear(5, 3)\n",
    "linear.weight"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7dcc8fd9",
   "metadata": {
    "origin_pos": 30
   },
   "source": [
    "我们可以[**使用自定义层直接执行前向传播计算**]。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "25f2aabf",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:07:17.562706Z",
     "iopub.status.busy": "2023-08-18T07:07:17.562337Z",
     "iopub.status.idle": "2023-08-18T07:07:17.570015Z",
     "shell.execute_reply": "2023-08-18T07:07:17.568916Z"
    },
    "origin_pos": 32,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[0., 0., 0.],\n",
       "        [0., 0., 0.]])"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "linear(torch.rand(2, 5))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c92ac1e0",
   "metadata": {
    "origin_pos": 35
   },
   "source": [
    "我们还可以(**使用自定义层构建模型**)，就像使用内置的全连接层一样使用自定义层。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "fb2953e8",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:07:17.574378Z",
     "iopub.status.busy": "2023-08-18T07:07:17.574000Z",
     "iopub.status.idle": "2023-08-18T07:07:17.582792Z",
     "shell.execute_reply": "2023-08-18T07:07:17.581735Z"
    },
    "origin_pos": 37,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[0.],\n",
       "        [0.]])"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "net = nn.Sequential(MyLinear(64, 8), MyLinear(8, 1))\n",
    "net(torch.rand(2, 64))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5a23d1ab",
   "metadata": {
    "origin_pos": 40
   },
   "source": [
    "## 小结\n",
    "\n",
    "* 我们可以通过基本层类设计自定义层。这允许我们定义灵活的新层，其行为与深度学习框架中的任何现有层不同。\n",
    "* 在自定义层定义完成后，我们就可以在任意环境和网络架构中调用该自定义层。\n",
    "* 层可以有局部参数，这些参数可以通过内置函数创建。\n",
    "\n",
    "## 练习\n",
    "\n",
    "1. 设计一个接受输入并计算张量降维的层，它返回$y_k = \\sum_{i, j} W_{ijk} x_i x_j$。\n",
    "1. 设计一个返回输入数据的傅立叶系数前半部分的层。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2d5d22c2",
   "metadata": {
    "origin_pos": 42,
    "tab": [
     "pytorch"
    ]
   },
   "source": [
    "[Discussions](https://discuss.d2l.ai/t/1835)\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  },
  "required_libs": []
 },
 "nbformat": 4,
 "nbformat_minor": 5
}