You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

tutorial_8_modules_models.rst 8.6 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. ======================================
  2. 使用Modules和Models快速搭建自定义模型
  3. ======================================
  4. :mod:`~fastNLP.modules` 和 :mod:`~fastNLP.models` 用于构建 fastNLP 所需的神经网络模型,它可以和 torch.nn 中的模型一起使用。
  5. 下面我们会分三节介绍编写构建模型的具体方法。
  6. 使用 models 中的模型
  7. ----------------------
  8. fastNLP 在 :mod:`~fastNLP.models` 模块中内置了如 :class:`~fastNLP.models.CNNText` 、
  9. :class:`~fastNLP.models.SeqLabeling` 等完整的模型,以供用户直接使用。
  10. 以文本分类的任务为例,我们从 models 中导入 :class:`~fastNLP.models.CNNText` 模型,用它进行训练。
  11. .. code-block:: python
  12. from fastNLP.models import CNNText
  13. model_cnn = CNNText((len(vocab),100), num_classes=2, dropout=0.1)
  14. trainer = Trainer(train_data=train_data, dev_data=dev_data, metrics=metric,
  15. loss=loss, device=device, model=model_cnn)
  16. trainer.train()
  17. 在 iPython 环境输入 `model_cnn` ,我们可以看到 ``model_cnn`` 的网络结构
  18. .. parsed-literal::
  19. CNNText(
  20. (embed): Embedding(
  21. (embed): Embedding(16292, 100)
  22. (dropout): Dropout(p=0.0, inplace=False)
  23. )
  24. (conv_pool): ConvMaxpool(
  25. (convs): ModuleList(
  26. (0): Conv1d(100, 30, kernel_size=(1,), stride=(1,), bias=False)
  27. (1): Conv1d(100, 40, kernel_size=(3,), stride=(1,), padding=(1,), bias=False)
  28. (2): Conv1d(100, 50, kernel_size=(5,), stride=(1,), padding=(2,), bias=False)
  29. )
  30. )
  31. (dropout): Dropout(p=0.1, inplace=False)
  32. (fc): Linear(in_features=120, out_features=2, bias=True)
  33. )
  34. FastNLP 中内置的 models 如下表所示,您可以点击具体的名称查看详细的 API:
  35. .. csv-table::
  36. :header: 名称, 介绍
  37. :class:`~fastNLP.models.CNNText` , 使用 CNN 进行文本分类的模型
  38. :class:`~fastNLP.models.SeqLabeling` , 简单的序列标注模型
  39. :class:`~fastNLP.models.AdvSeqLabel` , 更大网络结构的序列标注模型
  40. :class:`~fastNLP.models.ESIM` , ESIM 模型的实现
  41. :class:`~fastNLP.models.StarTransEnc` , 带 word-embedding的Star-Transformer模 型
  42. :class:`~fastNLP.models.STSeqLabel` , 用于序列标注的 Star-Transformer 模型
  43. :class:`~fastNLP.models.STNLICls` ,用于自然语言推断 (NLI) 的 Star-Transformer 模型
  44. :class:`~fastNLP.models.STSeqCls` , 用于分类任务的 Star-Transformer 模型
  45. :class:`~fastNLP.models.BiaffineParser` , Biaffine 依存句法分析网络的实现
  46. :class:`~fastNLP.models.BiLSTMCRF`, 使用BiLSTM与CRF进行序列标注
  47. 使用 nn.torch 编写模型
  48. ----------------------------
  49. FastNLP 完全支持使用 pyTorch 编写的模型,但与 pyTorch 中编写模型的常见方法不同,
  50. 用于 fastNLP 的模型中 forward 函数需要返回一个字典,字典中至少需要包含 ``pred`` 这个字段。
  51. 下面是使用 pyTorch 中的 torch.nn 模块编写的文本分类,注意观察代码中标注的向量维度。
  52. 由于 pyTorch 使用了约定俗成的维度设置,使得 forward 中需要多次处理维度顺序
  53. .. code-block:: python
  54. import torch
  55. import torch.nn as nn
  56. class LSTMText(nn.Module):
  57. def __init__(self, vocab_size, embedding_dim, output_dim, hidden_dim=64, num_layers=2, dropout=0.5):
  58. super().__init__()
  59. self.embedding = nn.Embedding(vocab_size, embedding_dim)
  60. self.lstm = nn.LSTM(embedding_dim, hidden_dim, num_layers=num_layers, bidirectional=True, dropout=dropout)
  61. self.fc = nn.Linear(hidden_dim * 2, output_dim)
  62. self.dropout = nn.Dropout(dropout)
  63. def forward(self, words):
  64. # (input) words : (batch_size, seq_len)
  65. words = words.permute(1,0)
  66. # words : (seq_len, batch_size)
  67. embedded = self.dropout(self.embedding(words))
  68. # embedded : (seq_len, batch_size, embedding_dim)
  69. output, (hidden, cell) = self.lstm(embedded)
  70. # output: (seq_len, batch_size, hidden_dim * 2)
  71. # hidden: (num_layers * 2, batch_size, hidden_dim)
  72. # cell: (num_layers * 2, batch_size, hidden_dim)
  73. hidden = torch.cat((hidden[-2, :, :], hidden[-1, :, :]), dim=1)
  74. hidden = self.dropout(hidden)
  75. # hidden: (batch_size, hidden_dim * 2)
  76. pred = self.fc(hidden.squeeze(0))
  77. # result: (batch_size, output_dim)
  78. return {"pred":pred}
  79. 我们同样可以在 iPython 环境中查看这个模型的网络结构
  80. .. parsed-literal::
  81. LSTMText(
  82. (embedding): Embedding(16292, 100)
  83. (lstm): LSTM(100, 64, num_layers=2, dropout=0.5, bidirectional=True)
  84. (fc): Linear(in_features=128, out_features=2, bias=True)
  85. (dropout): Dropout(p=0.5, inplace=False)
  86. )
  87. 使用 modules 编写模型
  88. ----------------------------
  89. 下面我们使用 :mod:`fastNLP.modules` 中的组件来构建同样的网络。由于 fastNLP 统一把 ``batch_size`` 放在第一维,
  90. 在编写代码的过程中会有一定的便利。
  91. .. code-block:: python
  92. from fastNLP.modules import Embedding, LSTM, MLP
  93. class MyText(nn.Module):
  94. def __init__(self, vocab_size, embedding_dim, output_dim, hidden_dim=64, num_layers=2, dropout=0.5):
  95. super().__init__()
  96. self.embedding = Embedding((vocab_size, embedding_dim))
  97. self.lstm = LSTM(embedding_dim, hidden_dim, num_layers=num_layers, bidirectional=True)
  98. self.mlp = MLP([hidden_dim*2,output_dim], dropout=dropout)
  99. def forward(self, words):
  100. embedded = self.embedding(words)
  101. _,(hidden,_) = self.lstm(embedded)
  102. pred = self.mlp(torch.cat((hidden[-1],hidden[-2]),dim=1))
  103. return {"pred":pred}
  104. 我们自己编写模型的网络结构如下
  105. .. parsed-literal::
  106. MyText(
  107. (embedding): Embedding(
  108. (embed): Embedding(16292, 100)
  109. (dropout): Dropout(p=0.0, inplace=False)
  110. )
  111. (lstm): LSTM(
  112. (lstm): LSTM(100, 64, num_layers=2, batch_first=True, bidirectional=True)
  113. )
  114. (mlp): MLP(
  115. (hiddens): ModuleList()
  116. (output): Linear(in_features=128, out_features=2, bias=True)
  117. (dropout): Dropout(p=0.5, inplace=False)
  118. )
  119. )
  120. FastNLP 中包含的各种模块如下表,您可以点击具体的名称查看详细的 API,也可以通过 :doc:`/fastNLP.modules` 进行了解。
  121. .. csv-table::
  122. :header: 名称, 介绍
  123. :class:`~fastNLP.modules.ConvolutionCharEncoder` , char级别的卷积 encoder
  124. :class:`~fastNLP.modules.LSTMCharEncoder` , char级别基于LSTM的 encoder
  125. :class:`~fastNLP.modules.ConvMaxpool` , 结合了Convolution和Max-Pooling于一体的模块
  126. :class:`~fastNLP.modules.LSTM` , LSTM模块, 轻量封装了PyTorch的LSTM
  127. :class:`~fastNLP.modules.StarTransformer` , Star-Transformer 的encoder部分
  128. :class:`~fastNLP.modules.TransformerEncoder` , Transformer的encoder模块,不包含embedding层
  129. :class:`~fastNLP.modules.VarRNN` , Variational Dropout RNN 模块
  130. :class:`~fastNLP.modules.VarLSTM` , Variational Dropout LSTM 模块
  131. :class:`~fastNLP.modules.VarGRU` , Variational Dropout GRU 模块
  132. :class:`~fastNLP.modules.MaxPool` , Max-pooling模块
  133. :class:`~fastNLP.modules.MaxPoolWithMask` , 带mask矩阵的max pooling。在做 max-pooling的时候不会考虑mask值为0的位置。
  134. :class:`~fastNLP.modules.AvgPool` , Average-pooling模块
  135. :class:`~fastNLP.modules.AvgPoolWithMask` , 带mask矩阵的average pooling。在做 average-pooling的时候不会考虑mask值为0的位置。
  136. :class:`~fastNLP.modules.MultiHeadAttention` , MultiHead Attention 模块
  137. :class:`~fastNLP.modules.MLP` , 简单的多层感知器模块
  138. :class:`~fastNLP.modules.ConditionalRandomField` , 条件随机场模块
  139. :class:`~fastNLP.modules.viterbi_decode` , 给定一个特征矩阵以及转移分数矩阵,计算出最佳的路径以及对应的分数 (与 :class:`~fastNLP.modules.ConditionalRandomField` 配合使用)
  140. :class:`~fastNLP.modules.allowed_transitions` , 给定一个id到label的映射表,返回所有可以跳转的列表(与 :class:`~fastNLP.modules.ConditionalRandomField` 配合使用)
  141. :class:`~fastNLP.modules.TimestepDropout` , 简单包装过的Dropout 组件
  142. ----------------------------------
  143. 代码下载
  144. ----------------------------------
  145. `点击下载 IPython Notebook 文件 <https://sourcegraph.com/github.com/fastnlp/fastNLP@master/-/raw/tutorials/tutorial_8_modules_models.ipynb>`_)