@@ -36,9 +36,13 @@ pip install fastNLP | |||
python -m spacy download en | |||
``` | |||
目前使用pip安装fastNLP的版本是0.4.1,有较多功能仍未更新,最新内容以master分支为准。 | |||
fastNLP0.5.0版本将在近期推出,请密切关注。 | |||
## fastNLP教程 | |||
- [0. 快速入门](https://fastnlp.readthedocs.io/zh/latest/user/quickstart.html) | |||
- [1. 使用DataSet预处理文本](https://fastnlp.readthedocs.io/zh/latest/tutorials/tutorial_1_data_preprocess.html) | |||
- [2. 使用DataSetLoader加载数据集](https://fastnlp.readthedocs.io/zh/latest/tutorials/tutorial_2_load_dataset.html) | |||
- [3. 使用Embedding模块将文本转成向量](https://fastnlp.readthedocs.io/zh/latest/tutorials/tutorial_3_embedding.html) | |||
@@ -48,17 +52,23 @@ python -m spacy download en | |||
- [7. 使用Modules和Models快速搭建自定义模型](https://fastnlp.readthedocs.io/zh/latest/tutorials/tutorial_7_modules_models.html) | |||
- [8. 使用Metric快速评测你的模型](https://fastnlp.readthedocs.io/zh/latest/tutorials/tutorial_8_metrics.html) | |||
- [9. 使用Callback自定义你的训练过程](https://fastnlp.readthedocs.io/zh/latest/tutorials/tutorial_9_callback.html) | |||
- [10. 使用fitlog 辅助 fastNLP 进行科研](https://fastnlp.readthedocs.io/zh/latest/tutorials/tutorial_10_fitlog.html) | |||
## 内置组件 | |||
大部分用于的 NLP 任务神经网络都可以看做由编码器(encoder)、解码器(decoder)两种模块组成。 | |||
大部分用于的 NLP 任务神经网络都可以看做由词嵌入(embeddings)和两种模块:编码器(encoder)、解码器(decoder)组成。 | |||
以文本分类任务为例,下图展示了一个BiLSTM+Attention实现文本分类器的模型流程图: | |||
 | |||
fastNLP 在 modules 模块中内置了两种模块的诸多组件,可以帮助用户快速搭建自己所需的网络。 两种模块的功能和常见组件如下: | |||
fastNLP 在 embeddings 模块中内置了几种不同的embedding:静态embedding(GloVe、word2vec)、上下文相关embedding | |||
(ELMo、BERT)、字符embedding(基于CNN或者LSTM的CharEmbedding) | |||
与此同时,fastNLP 在 modules 模块中内置了两种模块的诸多组件,可以帮助用户快速搭建自己所需的网络。 两种模块的功能和常见组件如下: | |||
<table> | |||
<tr> | |||
@@ -102,6 +112,10 @@ fastNLP的大致工作流程如上图所示,而项目结构如下: | |||
<td><b> fastNLP.modules </b></td> | |||
<td> 实现了用于搭建神经网络模型的诸多组件 </td> | |||
</tr> | |||
<tr> | |||
<td><b> fastNLP.embeddings </b></td> | |||
<td> 实现了将序列index转为向量序列的功能,包括读取预训练embedding等 </td> | |||
</tr> | |||
<tr> | |||
<td><b> fastNLP.io </b></td> | |||
<td> 实现了读写功能,包括数据读入,模型读写等 </td> | |||
@@ -19,6 +19,9 @@ apidoc: | |||
server: | |||
cd build/html && python -m http.server | |||
dev: | |||
rm -rf build/html && make html && make server | |||
.PHONY: help Makefile | |||
# Catch-all target: route all unknown targets to Sphinx using the new | |||
@@ -0,0 +1,41 @@ | |||
# 快速入门 fastNLP 文档编写 | |||
本教程为 fastNLP 文档编写者创建,文档编写者包括合作开发人员和文档维护人员。您在一般情况下属于前者, | |||
只需要了解整个框架的部分内容即可。 | |||
## 合作开发人员 | |||
FastNLP的文档使用基于[reStructuredText标记语言](http://docutils.sourceforge.net/rst.html)的 | |||
[Sphinx](http://sphinx.pocoo.org/)工具生成,由[Read the Docs](https://readthedocs.org/)网站自动维护生成。 | |||
一般开发者只要编写符合reStructuredText语法规范的文档并通过[PR](https://help.github.com/en/articles/about-pull-requests), | |||
就可以为fastNLP的文档贡献一份力量。 | |||
如果你想在本地编译文档并进行大段文档的编写,您需要安装Sphinx工具以及sphinx-rtd-theme主题: | |||
```bash | |||
fastNLP/docs> pip install sphinx | |||
fastNLP/docs> pip install sphinx-rtd-theme | |||
``` | |||
然后在本目录下执行 `make dev` 命令。该命令只支持Linux和MacOS系统,期望看到如下输出: | |||
```bash | |||
fastNLP/docs> make dev | |||
rm -rf build/html && make html && make server | |||
Running Sphinx v1.5.6 | |||
making output directory... | |||
...... | |||
Build finished. The HTML pages are in build/html. | |||
cd build/html && python -m http.server | |||
Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ... | |||
``` | |||
现在您浏览器访问 http://localhost:8000/ 查看文档。如果你在远程服务器尚进行工作,则访问地址为 http://{服务器的ip地址}:8000/ 。 | |||
但您必须保证服务器的8000端口是开放的。如果您的电脑或远程服务器的8000端口被占用,程序会顺延使用8001、8002……等端口。 | |||
当你结束访问时,您可以使用Control(Ctrl) + C 来结束进程。 | |||
我们在[这里](./source/user/example.rst)列举了fastNLP文档经常用到的reStructuredText语法(网页查看请结合Raw模式), | |||
您可以通过阅读它进行快速上手。FastNLP大部分的文档都是写在代码中通过Sphinx工具进行抽取生成的, | |||
您还可以参考这篇[未完成的文章](./source/user/docs_in_code.rst)了解代码内文档编写的规范。 | |||
## 文档维护人员 | |||
文档维护人员需要了解 Makefile 中全部命令的含义,并了解到目前的文档结构 | |||
是在 sphinx-apidoc 自动抽取的基础上进行手动修改得到的。 | |||
文档维护人员应进一步提升整个框架的自动化程度,并监督合作开发人员不要破坏文档项目的整体结构。 |
@@ -1,36 +0,0 @@ | |||
@ECHO OFF | |||
pushd %~dp0 | |||
REM Command file for Sphinx documentation | |||
if "%SPHINXBUILD%" == "" ( | |||
set SPHINXBUILD=sphinx-build | |||
) | |||
set SOURCEDIR=source | |||
set BUILDDIR=build | |||
set SPHINXPROJ=fastNLP | |||
if "%1" == "" goto help | |||
%SPHINXBUILD% >NUL 2>NUL | |||
if errorlevel 9009 ( | |||
echo. | |||
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx | |||
echo.installed, then set the SPHINXBUILD environment variable to point | |||
echo.to the full path of the 'sphinx-build' executable. Alternatively you | |||
echo.may add the Sphinx directory to PATH. | |||
echo. | |||
echo.If you don't have Sphinx installed, grab it from | |||
echo.http://sphinx-doc.org/ | |||
exit /b 1 | |||
) | |||
%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% | |||
goto end | |||
:help | |||
%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% | |||
:end | |||
popd |
@@ -1,2 +0,0 @@ | |||
# FastNLP Quick Tutorial | |||
@@ -24,9 +24,9 @@ copyright = '2018, xpqiu' | |||
author = 'xpqiu' | |||
# The short X.Y version | |||
version = '0.4' | |||
version = '0.4.5' | |||
# The full version, including alpha/beta/rc tags | |||
release = '0.4' | |||
release = '0.4.5' | |||
# -- General configuration --------------------------------------------------- | |||
@@ -2,6 +2,6 @@ fastNLP.core.batch | |||
================== | |||
.. automodule:: fastNLP.core.batch | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: |
@@ -2,6 +2,6 @@ fastNLP.core.callback | |||
===================== | |||
.. automodule:: fastNLP.core.callback | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: |
@@ -2,6 +2,6 @@ fastNLP.core.const | |||
================== | |||
.. automodule:: fastNLP.core.const | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: |
@@ -2,6 +2,6 @@ fastNLP.core.dataset | |||
==================== | |||
.. automodule:: fastNLP.core.dataset | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: |
@@ -2,6 +2,6 @@ fastNLP.core.field | |||
================== | |||
.. automodule:: fastNLP.core.field | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: |
@@ -2,6 +2,6 @@ fastNLP.core.instance | |||
===================== | |||
.. automodule:: fastNLP.core.instance | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: |
@@ -2,6 +2,6 @@ fastNLP.core.losses | |||
=================== | |||
.. automodule:: fastNLP.core.losses | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: |
@@ -2,6 +2,6 @@ fastNLP.core.metrics | |||
==================== | |||
.. automodule:: fastNLP.core.metrics | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: |
@@ -2,6 +2,6 @@ fastNLP.core.optimizer | |||
====================== | |||
.. automodule:: fastNLP.core.optimizer | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: |
@@ -2,15 +2,15 @@ fastNLP.core | |||
============ | |||
.. automodule:: fastNLP.core | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: | |||
子模块 | |||
---------- | |||
.. toctree:: | |||
:titlesonly: | |||
:maxdepth: 1 | |||
fastNLP.core.batch | |||
fastNLP.core.callback | |||
@@ -26,4 +26,3 @@ fastNLP.core | |||
fastNLP.core.trainer | |||
fastNLP.core.utils | |||
fastNLP.core.vocabulary | |||
@@ -2,6 +2,6 @@ fastNLP.core.sampler | |||
==================== | |||
.. automodule:: fastNLP.core.sampler | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: |
@@ -2,6 +2,6 @@ fastNLP.core.tester | |||
=================== | |||
.. automodule:: fastNLP.core.tester | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: |
@@ -2,6 +2,6 @@ fastNLP.core.trainer | |||
==================== | |||
.. automodule:: fastNLP.core.trainer | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: |
@@ -2,6 +2,6 @@ fastNLP.core.utils | |||
================== | |||
.. automodule:: fastNLP.core.utils | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: |
@@ -2,6 +2,6 @@ fastNLP.core.vocabulary | |||
======================= | |||
.. automodule:: fastNLP.core.vocabulary | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: |
@@ -0,0 +1,7 @@ | |||
fastNLP.embeddings.bert\_embedding | |||
================================== | |||
.. automodule:: fastNLP.embeddings.bert_embedding | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: |
@@ -0,0 +1,7 @@ | |||
fastNLP.embeddings.char\_embedding | |||
================================== | |||
.. automodule:: fastNLP.embeddings.char_embedding | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: |
@@ -0,0 +1,7 @@ | |||
fastNLP.embeddings.elmo\_embedding | |||
================================== | |||
.. automodule:: fastNLP.embeddings.elmo_embedding | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: |
@@ -0,0 +1,7 @@ | |||
fastNLP.embeddings.embedding | |||
============================ | |||
.. automodule:: fastNLP.embeddings.embedding | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: |
@@ -0,0 +1,21 @@ | |||
fastNLP.embeddings | |||
================== | |||
.. automodule:: fastNLP.embeddings | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: | |||
子模块 | |||
---------- | |||
.. toctree:: | |||
:maxdepth: 1 | |||
fastNLP.embeddings.bert_embedding | |||
fastNLP.embeddings.char_embedding | |||
fastNLP.embeddings.elmo_embedding | |||
fastNLP.embeddings.embedding | |||
fastNLP.embeddings.stack_embedding | |||
fastNLP.embeddings.static_embedding | |||
fastNLP.embeddings.utils |
@@ -0,0 +1,7 @@ | |||
fastNLP.embeddings.stack\_embedding | |||
=================================== | |||
.. automodule:: fastNLP.embeddings.stack_embedding | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: |
@@ -0,0 +1,7 @@ | |||
fastNLP.embeddings.static\_embedding | |||
==================================== | |||
.. automodule:: fastNLP.embeddings.static_embedding | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: |
@@ -0,0 +1,7 @@ | |||
fastNLP.embeddings.utils | |||
======================== | |||
.. automodule:: fastNLP.embeddings.utils | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: |
@@ -2,6 +2,6 @@ fastNLP.io.base\_loader | |||
======================= | |||
.. automodule:: fastNLP.io.base_loader | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: |
@@ -0,0 +1,7 @@ | |||
fastNLP.io.data\_loader | |||
========================== | |||
.. automodule:: fastNLP.io.data_loader | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: |
@@ -2,6 +2,6 @@ fastNLP.io.dataset\_loader | |||
========================== | |||
.. automodule:: fastNLP.io.dataset_loader | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: |
@@ -2,6 +2,6 @@ fastNLP.io.embed\_loader | |||
======================== | |||
.. automodule:: fastNLP.io.embed_loader | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: |
@@ -2,6 +2,6 @@ fastNLP.io.model\_io | |||
==================== | |||
.. automodule:: fastNLP.io.model_io | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: |
@@ -2,18 +2,18 @@ fastNLP.io | |||
========== | |||
.. automodule:: fastNLP.io | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: | |||
子模块 | |||
---------- | |||
.. toctree:: | |||
:titlesonly: | |||
:maxdepth: 1 | |||
fastNLP.io.base_loader | |||
fastNLP.io.dataset_loader | |||
fastNLP.io.embed_loader | |||
fastNLP.io.dataset_loader | |||
fastNLP.io.data_loader | |||
fastNLP.io.model_io | |||
@@ -2,6 +2,6 @@ fastNLP.models.biaffine\_parser | |||
=============================== | |||
.. automodule:: fastNLP.models.biaffine_parser | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: |
@@ -2,6 +2,6 @@ fastNLP.models.cnn\_text\_classification | |||
======================================== | |||
.. automodule:: fastNLP.models.cnn_text_classification | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: |
@@ -2,19 +2,18 @@ fastNLP.models | |||
============== | |||
.. automodule:: fastNLP.models | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: | |||
子模块 | |||
---------- | |||
.. toctree:: | |||
:titlesonly: | |||
:maxdepth: 1 | |||
fastNLP.models.biaffine_parser | |||
fastNLP.models.cnn_text_classification | |||
fastNLP.models.sequence_labeling | |||
fastNLP.models.snli | |||
fastNLP.models.star_transformer | |||
@@ -2,6 +2,6 @@ fastNLP.models.sequence\_labeling | |||
================================= | |||
.. automodule:: fastNLP.models.sequence_labeling | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: |
@@ -2,6 +2,6 @@ fastNLP.models.snli | |||
=================== | |||
.. automodule:: fastNLP.models.snli | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: |
@@ -2,6 +2,6 @@ fastNLP.models.star\_transformer | |||
================================ | |||
.. automodule:: fastNLP.models.star_transformer | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: |
@@ -1,7 +0,0 @@ | |||
fastNLP.modules.aggregator.attention | |||
==================================== | |||
.. automodule:: fastNLP.modules.aggregator.attention | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: |
@@ -1,7 +0,0 @@ | |||
fastNLP.modules.aggregator.pooling | |||
================================== | |||
.. automodule:: fastNLP.modules.aggregator.pooling | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: |
@@ -1,17 +0,0 @@ | |||
fastNLP.modules.aggregator | |||
========================== | |||
.. automodule:: fastNLP.modules.aggregator | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: | |||
子模块 | |||
---------- | |||
.. toctree:: | |||
:titlesonly: | |||
fastNLP.modules.aggregator.attention | |||
fastNLP.modules.aggregator.pooling | |||
@@ -1,7 +0,0 @@ | |||
fastNLP.modules.decoder.CRF | |||
=========================== | |||
.. automodule:: fastNLP.modules.decoder.crf | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: |
@@ -1,7 +0,0 @@ | |||
fastNLP.modules.decoder.MLP | |||
=========================== | |||
.. automodule:: fastNLP.modules.decoder.mlp | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: |
@@ -2,17 +2,7 @@ fastNLP.modules.decoder | |||
======================= | |||
.. automodule:: fastNLP.modules.decoder | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: | |||
子模块 | |||
---------- | |||
.. toctree:: | |||
:titlesonly: | |||
fastNLP.modules.decoder.crf | |||
fastNLP.modules.decoder.mlp | |||
fastNLP.modules.decoder.utils | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: | |||
@@ -1,7 +0,0 @@ | |||
fastNLP.modules.decoder.utils | |||
============================= | |||
.. automodule:: fastNLP.modules.decoder.utils | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: |
@@ -1,7 +0,0 @@ | |||
fastNLP.modules.encoder.bert | |||
============================ | |||
.. automodule:: fastNLP.modules.encoder.bert | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: |
@@ -1,7 +0,0 @@ | |||
fastNLP.modules.encoder.char\_encoder | |||
===================================== | |||
.. automodule:: fastNLP.modules.encoder.char_encoder | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: |
@@ -1,7 +0,0 @@ | |||
fastNLP.modules.encoder.conv\_maxpool | |||
===================================== | |||
.. automodule:: fastNLP.modules.encoder.conv_maxpool | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: |
@@ -1,7 +0,0 @@ | |||
fastNLP.modules.encoder.embedding | |||
================================= | |||
.. automodule:: fastNLP.modules.encoder.embedding | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: |
@@ -1,7 +0,0 @@ | |||
fastNLP.modules.encoder.lstm | |||
============================ | |||
.. automodule:: fastNLP.modules.encoder.lstm | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: |
@@ -2,22 +2,6 @@ fastNLP.modules.encoder | |||
======================= | |||
.. automodule:: fastNLP.modules.encoder | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: | |||
子模块 | |||
---------- | |||
.. toctree:: | |||
:titlesonly: | |||
fastNLP.modules.encoder.bert | |||
fastNLP.modules.encoder.char_encoder | |||
fastNLP.modules.encoder.conv_maxpool | |||
fastNLP.modules.encoder.embedding | |||
fastNLP.modules.encoder.lstm | |||
fastNLP.modules.encoder.star_transformer | |||
fastNLP.modules.encoder.transformer | |||
fastNLP.modules.encoder.variational_rnn | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: |
@@ -1,7 +0,0 @@ | |||
fastNLP.modules.encoder.star\_transformer | |||
========================================= | |||
.. automodule:: fastNLP.modules.encoder.star_transformer | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: |
@@ -1,7 +0,0 @@ | |||
fastNLP.modules.encoder.transformer | |||
=================================== | |||
.. automodule:: fastNLP.modules.encoder.transformer | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: |
@@ -1,7 +0,0 @@ | |||
fastNLP.modules.encoder.variational\_rnn | |||
======================================== | |||
.. automodule:: fastNLP.modules.encoder.variational_rnn | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: |
@@ -2,16 +2,16 @@ fastNLP.modules | |||
=============== | |||
.. automodule:: fastNLP.modules | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: | |||
子模块 | |||
----------- | |||
.. toctree:: | |||
:titlesonly: | |||
:titlesonly: | |||
:maxdepth: 1 | |||
fastNLP.modules.aggregator | |||
fastNLP.modules.decoder | |||
fastNLP.modules.encoder | |||
fastNLP.modules.decoder | |||
fastNLP.modules.encoder |
@@ -2,19 +2,18 @@ API 文档 | |||
=============== | |||
.. automodule:: fastNLP | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: | |||
:members: | |||
:undoc-members: | |||
:show-inheritance: | |||
内部模块 | |||
----------- | |||
.. toctree:: | |||
:titlesonly: | |||
:maxdepth: 3 | |||
fastNLP.core | |||
fastNLP.io | |||
fastNLP.modules | |||
fastNLP.models | |||
:maxdepth: 1 | |||
fastNLP.core | |||
fastNLP.embeddings | |||
fastNLP.io | |||
fastNLP.models | |||
fastNLP.modules |
@@ -1,62 +1,28 @@ | |||
fastNLP 中文文档 | |||
===================== | |||
fastNLP 是一款轻量级的 NLP 处理套件。你既可以使用它快速地完成一个命名实体识别(NER)、中文分词或文本分类任务; | |||
也可以使用他构建许多复杂的网络模型,进行科研。它具有如下的特性: | |||
`fastNLP <https://github.com/fastnlp/fastNLP/>`_ 是一款轻量级的 NLP 处理套件。你既可以使用它快速地完成一个序列标注 | |||
(NER、POS-Tagging等)、中文分词、文本分类、Matching、指代消解、摘要等任务 | |||
(详见 `reproduction <https://github.com/fastnlp/fastNLP/tree/master/reproduction>`_ ); | |||
也可以使用它构建许多复杂的网络模型,进行科研。它具有如下的特性: | |||
- 统一的Tabular式数据容器,让数据预处理过程简洁明了。内置多种数据集的DataSet Loader,省去预处理代码。 | |||
- 各种方便的NLP工具,例如预处理embedding加载; 中间数据cache等; | |||
- 详尽的中文文档以供查阅; | |||
- 提供诸多高级模块,例如Variational LSTM, Transformer, CRF等; | |||
- 封装CNNText,Biaffine等模型可供直接使用; | |||
- 便捷且具有扩展性的训练器; 提供多种内置callback函数,方便实验记录、异常捕获等。 | |||
- 统一的Tabular式数据容器,让数据预处理过程简洁明了。内置多种数据集的 :mod:`~fastNLP.io.data_loader` ,省去预处理代码; | |||
- 多种训练、测试组件,例如训练器 :class:`~fastNLP.Trainer` ;测试器 :class:`~fastNLP.Tester` ;以及各种评测 :mod:`~fastNLP.core.metrics` 等等; | |||
- 各种方便的NLP工具,例如预处理 :mod:`embedding<fastNLP.embeddings>` 加载(包括ELMo和BERT); 中间数据存储 :func:`cache <fastNLP.cache_results>` 等; | |||
- 提供诸多高级模块 :mod:`~fastNLP.modules`,例如 :class:`~fastNLP.modules.VarLSTM` , :class:`Transformer<fastNLP.modules.TransformerEncoder>` , :class:`CRF<fastNLP.modules.ConditionalRandomField>` 等; | |||
- 在序列标注、中文分词、文本分类、Matching、指代消解、摘要等任务上封装了各种 :mod:`~fastNLP.models` 可供直接使用; | |||
- 训练器便捷且具有扩展性,提供多种内置 :mod:`~fastNLP.core.callback` 函数,方便实验记录、异常捕获等。 | |||
内置组件 | |||
------------ | |||
大部分用于的 NLP 任务神经网络都可以看做由编码(encoder)、聚合(aggregator)、解码(decoder)三种模块组成。 | |||
.. image:: figures/text_classification.png | |||
fastNLP 在 :mod:`~fastNLP.modules` 模块中内置了三种模块的诸多组件,可以帮助用户快速搭建自己所需的网络。 | |||
三种模块的功能和常见组件如下: | |||
+-----------------------+-----------------------+-----------------------+ | |||
| module type | functionality | example | | |||
+=======================+=======================+=======================+ | |||
| encoder | 将输入编码为具有具 | embedding, RNN, CNN, | | |||
| | 有表示能力的向量 | transformer | | |||
+-----------------------+-----------------------+-----------------------+ | |||
| aggregator | 从多个向量中聚合信息 | self-attention, | | |||
| | | max-pooling | | |||
+-----------------------+-----------------------+-----------------------+ | |||
| decoder | 将具有某种表示意义的 | MLP, CRF | | |||
| | 向量解码为需要的输出 | | | |||
| | 形式 | | | |||
+-----------------------+-----------------------+-----------------------+ | |||
内置模型 | |||
---------------- | |||
fastNLP 在 :mod:`~fastNLP.models` 模块中内置了如 :class:`~fastNLP.models.CNNText` 、 | |||
:class:`~fastNLP.models.SeqLabeling` 等完整的模型,以供用户直接使用。 | |||
.. todo:: | |||
这些模型的介绍如下表所示:(模型名称 + 介绍 + 任务上的结果) | |||
用户手册 | |||
---------------- | |||
.. toctree:: | |||
:maxdepth: 1 | |||
:maxdepth: 2 | |||
安装指南 <user/installation> | |||
快速入门 <user/quickstart> | |||
详细指南 <user/tutorial_one> | |||
科研指南 <user/with_fitlog> | |||
注释语法 <user/example> | |||
安装指南 </user/installation> | |||
快速入门 </user/quickstart> | |||
详细教程 </user/tutorials> | |||
API 文档 | |||
------------- | |||
@@ -69,11 +35,11 @@ API 文档 | |||
fastNLP | |||
fitlog | |||
------ | |||
fitlog文档 | |||
---------- | |||
用户可以 `点此 <https://fitlog.readthedocs.io/zh/latest/>`_ 查看fitlog的文档。 | |||
fitlog 是由我们团队开发,用于帮助用户记录日志并管理代码的工具 | |||
您可以 `点此 <https://fitlog.readthedocs.io/zh/latest/>`_ 查看fitlog的文档。 | |||
fitlog 是由我们团队开发的日志记录+代码管理的工具。 | |||
索引与搜索 | |||
================== | |||
@@ -1,6 +1,6 @@ | |||
================= | |||
科研向导 | |||
================= | |||
============================================ | |||
使用fitlog 辅助 fastNLP 进行科研 | |||
============================================ | |||
本文介绍结合使用 fastNLP 和 fitlog 进行科研的方法。 | |||
@@ -0,0 +1,156 @@ | |||
============================== | |||
使用DataSet预处理文本 | |||
============================== | |||
:class:`~fastNLP.DataSet` 是fastNLP中用于承载数据的容器。可以将DataSet看做是一个表格, | |||
每一行是一个sample (在fastNLP中被称为 :mod:`~fastNLP.core.instance` ), | |||
每一列是一个feature (在fastNLP中称为 :mod:`~fastNLP.core.field` )。 | |||
.. csv-table:: | |||
:header: "sentence", "words", "seq_len" | |||
"This is the first instance .", "[This, is, the, first, instance, .]", 6 | |||
"Second instance .", "[Second, instance, .]", 3 | |||
"Third instance .", "[Third, instance, .]", 3 | |||
"...", "[...]", "..." | |||
上面是一个样例数据中 DataSet 的存储结构。其中它的每一行是一个 :class:`~fastNLP.Instance` 对象; 每一列是一个 :class:`~fastNLP.FieldArray` 对象。 | |||
----------------------------- | |||
数据集构建和删除 | |||
----------------------------- | |||
我们使用传入字典的方式构建一个数据集,这是 :class:`~fastNLP.DataSet` 初始化的最基础的方式 | |||
.. code-block:: python | |||
from fastNLP import DataSet | |||
data = {'sentence':["This is the first instance .", "Second instance .", "Third instance ."], | |||
'words': [['this', 'is', 'the', 'first', 'instance', '.'], ['Second', 'instance', '.'], ['Third', 'instance', '.']], | |||
'seq_len': [6, 3, 3]} | |||
dataset = DataSet(data) | |||
# 传入的dict的每个key的value应该为具有相同长度的list | |||
我们还可以使用 :func:`~fastNLP.DataSet.append` 方法向数据集内增加数据 | |||
.. code-block:: python | |||
from fastNLP import DataSet | |||
from fastNLP import Instance | |||
dataset = DataSet() | |||
instance = Instance(sentence="This is the first instance", | |||
words=['this', 'is', 'the', 'first', 'instance', '.'], | |||
seq_len=6) | |||
dataset.append(instance) | |||
# 可以继续append更多内容,但是append的instance应该和前面的instance拥有完全相同的field | |||
另外,我们还可以用 :class:`~fastNLP.Instance` 数组的方式构建数据集 | |||
.. code-block:: python | |||
from fastNLP import DataSet | |||
from fastNLP import Instance | |||
dataset = DataSet([ | |||
Instance(sentence="This is the first instance", | |||
words=['this', 'is', 'the', 'first', 'instance', '.'], | |||
seq_len=6), | |||
Instance(sentence="Second instance .", | |||
words=['Second', 'instance', '.'], | |||
seq_len=3) | |||
]) | |||
在初步构建完数据集之后,我们可以通过 `for` 循环遍历 :class:`~fastNLP.DataSet` 中的内容。 | |||
.. code-block:: python | |||
for instance in dataset: | |||
# do something | |||
FastNLP 同样提供了多种删除数据的方法 :func:`~fastNLP.DataSet.drop` 、 :func:`~fastNLP.DataSet.delete_instance` 和 :func:`~fastNLP.DataSet.delete_field` | |||
.. code-block:: python | |||
from fastNLP import DataSet | |||
dataset = DataSet({'a': list(range(-5, 5))}) | |||
# 返回满足条件的instance,并放入DataSet中 | |||
dropped_dataset = dataset.drop(lambda ins:ins['a']<0, inplace=False) | |||
# 在dataset中删除满足条件的instance | |||
dataset.drop(lambda ins:ins['a']<0) # dataset的instance数量减少 | |||
# 删除第3个instance | |||
dataset.delete_instance(2) | |||
# 删除名为'a'的field | |||
dataset.delete_field('a') | |||
----------------------------- | |||
简单的数据预处理 | |||
----------------------------- | |||
因为 fastNLP 中的数据是按列存储的,所以大部分的数据预处理操作是以列( :mod:`~fastNLP.core.field` )为操作对象的。 | |||
首先,我们可以检查特定名称的 :mod:`~fastNLP.core.field` 是否存在,并对其进行改名。 | |||
.. code-block:: python | |||
# 检查是否存在名为'a'的field | |||
dataset.has_field('a') # 或 ('a' in dataset) | |||
# 将名为'a'的field改名为'b' | |||
dataset.rename_field('a', 'b') | |||
# DataSet的长度 | |||
len(dataset) | |||
其次,我们可以使用 :func:`~fastNLP.DataSet.apply` 或 :func:`~fastNLP.DataSet.apply_field` 进行数据预处理操作操作。 | |||
这两个方法通过传入一个对单一 :mod:`~fastNLP.core.instance` 操作的函数, | |||
自动地帮助你对一个 :mod:`~fastNLP.core.field` 中的每个 :mod:`~fastNLP.core.instance` 调用这个函数,完成整体的操作。 | |||
这个传入的函数可以是 lambda 匿名函数,也可以是完整定义的函数。同时,你还可以用 ``new_field_name`` 参数指定数据处理后存储的 :mod:`~fastNLP.core.field` 的名称。 | |||
.. code-block:: python | |||
from fastNLP import DataSet | |||
data = {'sentence':["This is the first instance .", "Second instance .", "Third instance ."]} | |||
dataset = DataSet(data) | |||
# 将句子分成单词形式, 详见DataSet.apply()方法 | |||
dataset.apply(lambda ins: ins['sentence'].split(), new_field_name='words') | |||
# 或使用DataSet.apply_field() | |||
dataset.apply_field(lambda sent:sent.split(), field_name='sentence', new_field_name='words') | |||
# 除了匿名函数,也可以定义函数传递进去 | |||
def get_words(instance): | |||
sentence = instance['sentence'] | |||
words = sentence.split() | |||
return words | |||
dataset.apply(get_words, new_field_name='words') | |||
除了手动处理数据集之外,你还可以使用 fastNLP 提供的各种 :class:`~fastNLP.io.base_loader.DataSetLoader` 来进行数据处理。 | |||
详细请参考这篇教程 :doc:`使用DataSetLoader加载数据集 </tutorials/tutorial_2_load_dataset>` 。 | |||
----------------------------- | |||
DataSet与pad | |||
----------------------------- | |||
在fastNLP里,pad是与一个 :mod:`~fastNLP.core.field` 绑定的。即不同的 :mod:`~fastNLP.core.field` 可以使用不同的pad方式,比如在英文任务中word需要的pad和 | |||
character的pad方式往往是不同的。fastNLP是通过一个叫做 :class:`~fastNLP.Padder` 的子类来完成的。 | |||
默认情况下,所有field使用 :class:`~fastNLP.AutoPadder` | |||
。可以通过使用以下方式设置Padder(如果将padder设置为None,则该field不会进行pad操作)。 | |||
大多数情况下直接使用 :class:`~fastNLP.AutoPadder` 就可以了。 | |||
如果 :class:`~fastNLP.AutoPadder` 或 :class:`~fastNLP.EngChar2DPadder` 无法满足需求, | |||
也可以自己写一个 :class:`~fastNLP.Padder` 。 | |||
.. code-block:: python | |||
from fastNLP import DataSet | |||
from fastNLP import EngChar2DPadder | |||
import random | |||
dataset = DataSet() | |||
max_chars, max_words, sent_num = 5, 10, 20 | |||
contents = [[ | |||
[random.randint(1, 27) for _ in range(random.randint(1, max_chars))] | |||
for _ in range(random.randint(1, max_words)) | |||
] for _ in range(sent_num)] | |||
# 初始化时传入 | |||
dataset.add_field('chars', contents, padder=EngChar2DPadder()) | |||
# 直接设置 | |||
dataset.set_padder('chars', EngChar2DPadder()) | |||
# 也可以设置pad的value | |||
dataset.set_pad_val('chars', -1) |
@@ -0,0 +1,224 @@ | |||
================================= | |||
使用DataSetLoader加载数据集 | |||
================================= | |||
这一部分是一个关于如何加载数据集的教程 | |||
教程目录: | |||
- `Part I: 数据集容器`_ | |||
- `Part II: 数据集的使用方式`_ | |||
- `Part III: 不同数据类型的DataSetLoader`_ | |||
- `Part IV: DataSetLoader举例`_ | |||
- `Part V: fastNLP封装好的数据集加载器`_ | |||
---------------------------- | |||
Part I: 数据集容器 | |||
---------------------------- | |||
在fastNLP中,我们使用 :class:`~fastNLP.io.base_loader.DataBundle` 来存储数据集信息。 | |||
:class:`~fastNLP.io.base_loader.DataBundle` 类包含了两个重要内容: `datasets` 和 `vocabs` 。 | |||
`datasets` 是一个 `key` 为数据集名称(如 `train` , `dev` ,和 `test` 等), `value` 为 :class:`~fastNLP.DataSet` 的字典。 | |||
`vocabs` 是一个 `key` 为词表名称(如 :attr:`fastNLP.Const.INPUT` 表示输入文本的词表名称, :attr:`fastNLP.Const.TARGET` 表示目标 | |||
的真实标签词表的名称,等等), `value` 为词表内容( :class:`~fastNLP.Vocabulary` )的字典。 | |||
---------------------------- | |||
Part II: 数据集的使用方式 | |||
---------------------------- | |||
在fastNLP中,我们采用 :class:`~fastNLP.io.base_loader.DataSetLoader` 来作为加载数据集的基类。 | |||
:class:`~fastNLP.io.base_loader.DataSetLoader` 定义了各种DataSetLoader所需的API接口,开发者应该继承它实现各种的DataSetLoader。 | |||
在各种数据集的DataSetLoader当中,至少应该编写如下内容: | |||
- _load 函数:从一个数据文件中读取数据到一个 :class:`~fastNLP.DataSet` | |||
- load 函数(可以使用基类的方法):从一个或多个数据文件中读取数据到一个或多个 :class:`~fastNLP.DataSet` | |||
- process 函数:一个或多个从数据文件中读取数据,并处理成可以训练的 :class:`~fastNLP.io.DataBundle` | |||
**\*process函数中可以调用load函数或_load函数** | |||
DataSetLoader的_load或者load函数返回的 :class:`~fastNLP.DataSet` 当中,内容为数据集的文本信息,process函数返回的 | |||
:class:`~fastNLP.io.DataBundle` 当中, `datasets` 的内容为已经index好的、可以直接被 :class:`~fastNLP.Trainer` | |||
接受的内容。 | |||
-------------------------------------------------------- | |||
Part III: 不同数据类型的DataSetLoader | |||
-------------------------------------------------------- | |||
:class:`~fastNLP.io.dataset_loader.CSVLoader` | |||
读取CSV类型的数据集文件。例子如下: | |||
.. code-block:: python | |||
data_set_loader = CSVLoader( | |||
headers=('words', 'target'), sep='\t' | |||
) | |||
# 表示将CSV文件中每一行的第一项填入'words' field,第二项填入'target' field。 | |||
# 其中每两项之间由'\t'分割开来 | |||
data_set = data_set_loader._load('path/to/your/file') | |||
数据集内容样例如下 :: | |||
But it does not leave you with much . 1 | |||
You could hate it for the same reason . 1 | |||
The performances are an absolute joy . 4 | |||
:class:`~fastNLP.io.dataset_loader.JsonLoader` | |||
读取Json类型的数据集文件,数据必须按行存储,每行是一个包含各类属性的Json对象。例子如下: | |||
.. code-block:: python | |||
data_set_loader = JsonLoader( | |||
fields={'sentence1': 'words1', 'sentence2': 'words2', 'gold_label': 'target'} | |||
) | |||
# 表示将Json对象中'sentence1'、'sentence2'和'gold_label'对应的值赋给'words1'、'words2'、'target'这三个fields | |||
data_set = data_set_loader._load('path/to/your/file') | |||
数据集内容样例如下 :: | |||
{"annotator_labels": ["neutral"], "captionID": "3416050480.jpg#4", "gold_label": "neutral", "pairID": "3416050480.jpg#4r1n", "sentence1": "A person on a horse jumps over a broken down airplane.", "sentence1_binary_parse": "( ( ( A person ) ( on ( a horse ) ) ) ( ( jumps ( over ( a ( broken ( down airplane ) ) ) ) ) . ) )", "sentence1_parse": "(ROOT (S (NP (NP (DT A) (NN person)) (PP (IN on) (NP (DT a) (NN horse)))) (VP (VBZ jumps) (PP (IN over) (NP (DT a) (JJ broken) (JJ down) (NN airplane)))) (. .)))", "sentence2": "A person is training his horse for a competition.", "sentence2_binary_parse": "( ( A person ) ( ( is ( ( training ( his horse ) ) ( for ( a competition ) ) ) ) . ) )", "sentence2_parse": "(ROOT (S (NP (DT A) (NN person)) (VP (VBZ is) (VP (VBG training) (NP (PRP$ his) (NN horse)) (PP (IN for) (NP (DT a) (NN competition))))) (. .)))"} | |||
{"annotator_labels": ["contradiction"], "captionID": "3416050480.jpg#4", "gold_label": "contradiction", "pairID": "3416050480.jpg#4r1c", "sentence1": "A person on a horse jumps over a broken down airplane.", "sentence1_binary_parse": "( ( ( A person ) ( on ( a horse ) ) ) ( ( jumps ( over ( a ( broken ( down airplane ) ) ) ) ) . ) )", "sentence1_parse": "(ROOT (S (NP (NP (DT A) (NN person)) (PP (IN on) (NP (DT a) (NN horse)))) (VP (VBZ jumps) (PP (IN over) (NP (DT a) (JJ broken) (JJ down) (NN airplane)))) (. .)))", "sentence2": "A person is at a diner, ordering an omelette.", "sentence2_binary_parse": "( ( A person ) ( ( ( ( is ( at ( a diner ) ) ) , ) ( ordering ( an omelette ) ) ) . ) )", "sentence2_parse": "(ROOT (S (NP (DT A) (NN person)) (VP (VBZ is) (PP (IN at) (NP (DT a) (NN diner))) (, ,) (S (VP (VBG ordering) (NP (DT an) (NN omelette))))) (. .)))"} | |||
{"annotator_labels": ["entailment"], "captionID": "3416050480.jpg#4", "gold_label": "entailment", "pairID": "3416050480.jpg#4r1e", "sentence1": "A person on a horse jumps over a broken down airplane.", "sentence1_binary_parse": "( ( ( A person ) ( on ( a horse ) ) ) ( ( jumps ( over ( a ( broken ( down airplane ) ) ) ) ) . ) )", "sentence1_parse": "(ROOT (S (NP (NP (DT A) (NN person)) (PP (IN on) (NP (DT a) (NN horse)))) (VP (VBZ jumps) (PP (IN over) (NP (DT a) (JJ broken) (JJ down) (NN airplane)))) (. .)))", "sentence2": "A person is outdoors, on a horse.", "sentence2_binary_parse": "( ( A person ) ( ( ( ( is outdoors ) , ) ( on ( a horse ) ) ) . ) )", "sentence2_parse": "(ROOT (S (NP (DT A) (NN person)) (VP (VBZ is) (ADVP (RB outdoors)) (, ,) (PP (IN on) (NP (DT a) (NN horse)))) (. .)))"} | |||
------------------------------------------ | |||
Part IV: DataSetLoader举例 | |||
------------------------------------------ | |||
以Matching任务为例子: | |||
:class:`~fastNLP.io.data_loader.MatchingLoader` | |||
我们在fastNLP当中封装了一个Matching任务数据集的数据加载类: :class:`~fastNLP.io.data_loader.MatchingLoader` . | |||
在MatchingLoader类当中我们封装了一个对数据集中的文本内容进行进一步的预处理的函数: | |||
:meth:`~fastNLP.io.data_loader.MatchingLoader.process` | |||
这个函数具有各种预处理option,如: | |||
- 是否将文本转成全小写 | |||
- 是否需要序列长度信息,需要什么类型的序列长度信息 | |||
- 是否需要用BertTokenizer来获取序列的WordPiece信息 | |||
- 等等 | |||
具体内容参见 :meth:`fastNLP.io.MatchingLoader.process` 。 | |||
:class:`~fastNLP.io.data_loader.SNLILoader` | |||
一个关于SNLI数据集的DataSetLoader。SNLI数据集来自 | |||
`SNLI Data Set <https://nlp.stanford.edu/projects/snli/snli_1.0.zip>`_ . | |||
在 :class:`~fastNLP.io.data_loader.SNLILoader` 的 :meth:`~fastNLP.io.data_loader.SNLILoader._load` | |||
函数中,我们用以下代码将数据集内容从文本文件读入内存: | |||
.. code-block:: python | |||
data = SNLILoader().process( | |||
paths='path/to/snli/data', to_lower=False, seq_len_type='seq_len', | |||
get_index=True, concat=False, | |||
) | |||
print(data) | |||
输出的内容是:: | |||
In total 3 datasets: | |||
train has 549367 instances. | |||
dev has 9842 instances. | |||
test has 9824 instances. | |||
In total 2 vocabs: | |||
words has 43154 entries. | |||
target has 3 entries. | |||
这里的data是一个 :class:`~fastNLP.io.base_loader.DataBundle` ,取 ``datasets`` 字典里的内容即可直接传入 | |||
:class:`~fastNLP.Trainer` 或者 :class:`~fastNLP.Tester` 进行训练或者测试。 | |||
:class:`~fastNLP.io.data_loader.IMDBLoader` | |||
以IMDB数据集为例,在 :class:`~fastNLP.io.data_loader.IMDBLoader` 的 :meth:`~fastNLP.io.data_loader.IMDBLoader._load` | |||
函数中,我们用以下代码将数据集内容从文本文件读入内存: | |||
.. code-block:: python | |||
data = IMDBLoader().process( | |||
paths={'train': 'path/to/train/file', 'test': 'path/to/test/file'} | |||
) | |||
print(data) | |||
输出的内容是:: | |||
In total 3 datasets: | |||
train has 22500 instances. | |||
test has 25000 instances. | |||
dev has 2500 instances. | |||
In total 2 vocabs: | |||
words has 82846 entries. | |||
target has 2 entries. | |||
这里的将原来的train集按9:1的比例分成了训练集和验证集。 | |||
------------------------------------------ | |||
Part V: fastNLP封装好的数据集加载器 | |||
------------------------------------------ | |||
fastNLP封装好的数据集加载器可以适用于多种类型的任务: | |||
- `文本分类任务`_ | |||
- `序列标注任务`_ | |||
- `Matching任务`_ | |||
文本分类任务 | |||
------------------- | |||
========================== ================================================================== | |||
数据集名称 数据集加载器 | |||
-------------------------- ------------------------------------------------------------------ | |||
IMDb :class:`~fastNLP.io.data_loader.IMDBLoader` | |||
-------------------------- ------------------------------------------------------------------ | |||
SST :class:`~fastNLP.io.data_loader.SSTLoader` | |||
-------------------------- ------------------------------------------------------------------ | |||
SST-2 :class:`~fastNLP.io.data_loader.SST2Loader` | |||
-------------------------- ------------------------------------------------------------------ | |||
Yelp Polarity :class:`~fastNLP.io.data_loader.YelpLoader` | |||
-------------------------- ------------------------------------------------------------------ | |||
Yelp Full :class:`~fastNLP.io.data_loader.YelpLoader` | |||
-------------------------- ------------------------------------------------------------------ | |||
MTL16 :class:`~fastNLP.io.data_loader.MTL16Loader` | |||
========================== ================================================================== | |||
序列标注任务 | |||
------------------- | |||
========================== ================================================================== | |||
数据集名称 数据集加载器 | |||
-------------------------- ------------------------------------------------------------------ | |||
Conll :class:`~fastNLP.io.data_loader.ConllLoader` | |||
-------------------------- ------------------------------------------------------------------ | |||
Conll2003 :class:`~fastNLP.io.data_loader.Conll2003Loader` | |||
-------------------------- ------------------------------------------------------------------ | |||
人民日报数据集 :class:`~fastNLP.io.data_loader.PeopleDailyCorpusLoader` | |||
========================== ================================================================== | |||
Matching任务 | |||
------------------- | |||
========================== ================================================================== | |||
数据集名称 数据集加载器 | |||
-------------------------- ------------------------------------------------------------------ | |||
SNLI :class:`~fastNLP.io.data_loader.SNLILoader` | |||
-------------------------- ------------------------------------------------------------------ | |||
MultiNLI :class:`~fastNLP.io.data_loader.MNLILoader` | |||
-------------------------- ------------------------------------------------------------------ | |||
QNLI :class:`~fastNLP.io.data_loader.QNLILoader` | |||
-------------------------- ------------------------------------------------------------------ | |||
RTE :class:`~fastNLP.io.data_loader.RTELoader` | |||
-------------------------- ------------------------------------------------------------------ | |||
Quora Pair Dataset :class:`~fastNLP.io.data_loader.QuoraLoader` | |||
========================== ================================================================== | |||
@@ -0,0 +1,214 @@ | |||
========================================= | |||
使用Embedding模块将文本转成向量 | |||
========================================= | |||
这一部分是一个关于在fastNLP当中使用embedding的教程。 | |||
教程目录: | |||
- `Part I: embedding介绍`_ | |||
- `Part II: 使用随机初始化的embedding`_ | |||
- `Part III: 使用预训练的静态embedding`_ | |||
- `Part IV: 使用预训练的Contextual Embedding(ELMo & BERT)`_ | |||
- `Part V: 使用character-level的embedding`_ | |||
- `Part VI: 叠加使用多个embedding`_ | |||
--------------------------------------- | |||
Part I: embedding介绍 | |||
--------------------------------------- | |||
与torch.nn.Embedding类似,fastNLP的embedding接受的输入是一个被index好的序列,输出的内容是这个序列的embedding结果。 | |||
fastNLP的embedding包括了预训练embedding和随机初始化embedding。 | |||
--------------------------------------- | |||
Part II: 使用随机初始化的embedding | |||
--------------------------------------- | |||
使用随机初始化的embedding参见 :class:`~fastNLP.embeddings.embedding.Embedding` 。 | |||
可以传入词表大小和embedding维度: | |||
.. code-block:: python | |||
embed = Embedding(10000, 50) | |||
也可以传入一个初始化的参数矩阵: | |||
.. code-block:: python | |||
embed = Embedding(init_embed) | |||
其中的init_embed可以是torch.FloatTensor、torch.nn.Embedding或者numpy.ndarray。 | |||
--------------------------------------- | |||
Part III: 使用预训练的静态embedding | |||
--------------------------------------- | |||
在使用预训练的embedding之前,需要根据数据集的内容构建一个词表 :class:`~fastNLP.core.vocabulary.Vocabulary` ,在 | |||
预训练embedding类初始化的时候需要将这个词表作为参数传入。 | |||
在fastNLP中,我们提供了 :class:`~fastNLP.embeddings.StaticEmbedding` 这一个类。 | |||
通过 :class:`~fastNLP.embeddings.StaticEmbedding` 可以加载预训练好的静态 | |||
Embedding,例子如下: | |||
.. code-block:: python | |||
embed = StaticEmbedding(vocab, model_dir_or_name='en-glove-6b-50', requires_grad=True) | |||
vocab为根据数据集构建的词表,model_dir_or_name可以是一个路径,也可以是embedding模型的名称: | |||
1 如果传入的是路径,那么fastNLP将会根据该路径来读取预训练的权重文件并将embedding加载进来(glove | |||
和word2vec类型的权重文件都支持) | |||
2 如果传入的是模型名称,那么fastNLP将会根据名称查找embedding模型,如果在cache目录下找到模型则会 | |||
自动加载;如果找不到则会自动下载。可以通过环境变量 ``FASTNLP_CACHE_DIR`` 来自定义cache目录,如:: | |||
$ FASTNLP_CACHE_DIR=~/fastnlp_cache_dir python your_python_file.py | |||
这个命令表示fastNLP将会在 `~/fastnlp_cache_dir` 这个目录下寻找模型,找不到则会自动将模型下载到这个目录 | |||
目前支持的静态embedding模型有: | |||
========================== ================================ | |||
模型名称 模型 | |||
-------------------------- -------------------------------- | |||
en glove.840B.300d | |||
-------------------------- -------------------------------- | |||
en-glove-840d-300 glove.840B.300d | |||
-------------------------- -------------------------------- | |||
en-glove-6b-50 glove.6B.50d | |||
-------------------------- -------------------------------- | |||
en-word2vec-300 谷歌word2vec 300维 | |||
-------------------------- -------------------------------- | |||
en-fasttext 英文fasttext 300维 | |||
-------------------------- -------------------------------- | |||
cn 腾讯中文词向量 200维 | |||
-------------------------- -------------------------------- | |||
cn-fasttext 中文fasttext 300维 | |||
========================== ================================ | |||
----------------------------------------------------------- | |||
Part IV: 使用预训练的Contextual Embedding(ELMo & BERT) | |||
----------------------------------------------------------- | |||
在fastNLP中,我们提供了ELMo和BERT的embedding: :class:`~fastNLP.embeddings.ElmoEmbedding` | |||
和 :class:`~fastNLP.embeddings.BertEmbedding` 。 | |||
与静态embedding类似,ELMo的使用方法如下: | |||
.. code-block:: python | |||
embed = ElmoEmbedding(vocab, model_dir_or_name='small', requires_grad=False) | |||
目前支持的ElmoEmbedding模型有: | |||
========================== ================================ | |||
模型名称 模型 | |||
-------------------------- -------------------------------- | |||
small allennlp ELMo的small | |||
-------------------------- -------------------------------- | |||
medium allennlp ELMo的medium | |||
-------------------------- -------------------------------- | |||
original allennlp ELMo的original | |||
-------------------------- -------------------------------- | |||
5.5b-original allennlp ELMo的5.5B original | |||
========================== ================================ | |||
BERT-embedding的使用方法如下: | |||
.. code-block:: python | |||
embed = BertEmbedding( | |||
vocab, model_dir_or_name='en-base-cased', requires_grad=False, layers='4,-2,-1' | |||
) | |||
其中layers变量表示需要取哪几层的encode结果。 | |||
目前支持的BertEmbedding模型有: | |||
========================== ==================================== | |||
模型名称 模型 | |||
-------------------------- ------------------------------------ | |||
en bert-base-cased | |||
-------------------------- ------------------------------------ | |||
en-base-uncased bert-base-uncased | |||
-------------------------- ------------------------------------ | |||
en-base-cased bert-base-cased | |||
-------------------------- ------------------------------------ | |||
en-large-uncased bert-large-uncased | |||
-------------------------- ------------------------------------ | |||
en-large-cased bert-large-cased | |||
-------------------------- ------------------------------------ | |||
-------------------------- ------------------------------------ | |||
en-large-cased-wwm bert-large-cased-whole-word-mask | |||
-------------------------- ------------------------------------ | |||
en-large-uncased-wwm bert-large-uncased-whole-word-mask | |||
-------------------------- ------------------------------------ | |||
en-base-cased-mrpc bert-base-cased-finetuned-mrpc | |||
-------------------------- ------------------------------------ | |||
-------------------------- ------------------------------------ | |||
multilingual bert-base-multilingual-cased | |||
-------------------------- ------------------------------------ | |||
multilingual-base-uncased bert-base-multilingual-uncased | |||
-------------------------- ------------------------------------ | |||
multilingual-base-cased bert-base-multilingual-cased | |||
========================== ==================================== | |||
----------------------------------------------------- | |||
Part V: 使用character-level的embedding | |||
----------------------------------------------------- | |||
除了预训练的embedding以外,fastNLP还提供了CharEmbedding: :class:`~fastNLP.embeddings.CNNCharEmbedding` 和 | |||
:class:`~fastNLP.embeddings.LSTMCharEmbedding` 。 | |||
CNNCharEmbedding的使用例子如下: | |||
.. code-block:: python | |||
embed = CNNCharEmbedding(vocab, embed_size=100, char_emb_size=50) | |||
这表示这个CNNCharEmbedding当中character的embedding维度大小为50,返回的embedding结果维度大小为100。 | |||
与CNNCharEmbedding类似,LSTMCharEmbedding的使用例子如下: | |||
.. code-block:: python | |||
embed = LSTMCharEmbedding(vocab, embed_size=100, char_emb_size=50) | |||
这表示这个LSTMCharEmbedding当中character的embedding维度大小为50,返回的embedding结果维度大小为100。 | |||
----------------------------------------------------- | |||
Part VI: 叠加使用多个embedding | |||
----------------------------------------------------- | |||
在fastNLP中,我们使用 :class:`~fastNLP.embeddings.StackEmbedding` 来叠加多个embedding | |||
例子如下: | |||
.. code-block:: python | |||
embed_1 = StaticEmbedding(vocab, model_dir_or_name='en-glove-6b-50', requires_grad=True) | |||
embed_2 = StaticEmbedding(vocab, model_dir_or_name='en-word2vec-300', requires_grad=True) | |||
stack_embed = StackEmbedding([embed_1, embed_2]) | |||
StackEmbedding会把多个embedding的结果拼接起来,如上面例子的stack_embed返回的embedding维度为350维。 | |||
除此以外,还可以把静态embedding跟上下文相关的embedding拼接起来: | |||
.. code-block:: python | |||
elmo_embedding = ElmoEmbedding(vocab, model_dir_or_name='medium', layers='0,1,2', requires_grad=False) | |||
glove_embedding = StaticEmbedding(vocab, model_dir_or_name='en-glove-6b-50', requires_grad=True) | |||
stack_embed = StackEmbedding([elmo_embedding, glove_embedding]) |
@@ -0,0 +1,267 @@ | |||
============================================================================== | |||
动手实现一个文本分类器I-使用Trainer和Tester快速训练和测试 | |||
============================================================================== | |||
我们使用和 :doc:`/user/quickstart` 中一样的任务来进行详细的介绍。给出一段评价性文字,预测其情感倾向是积极(label=1)、 | |||
消极(label=0)还是中性(label=2),使用 :class:`~fastNLP.Trainer` 和 :class:`~fastNLP.Tester` 来进行快速训练和测试。 | |||
-------------- | |||
数据处理 | |||
-------------- | |||
数据读入 | |||
我们可以使用 fastNLP :mod:`fastNLP.io` 模块中的 :class:`~fastNLP.io.SSTLoader` 类,轻松地读取SST数据集(数据来源:https://nlp.stanford.edu/sentiment/trainDevTestTrees_PTB.zip)。 | |||
这里的 dataset 是 fastNLP 中 :class:`~fastNLP.DataSet` 类的对象。 | |||
.. code-block:: python | |||
from fastNLP.io import SSTLoader | |||
loader = SSTLoader() | |||
#这里的all.txt是下载好数据后train.txt、dev.txt、test.txt的组合 | |||
dataset = loader.load("./trainDevTestTrees_PTB/trees/all.txt") | |||
print(dataset[0]) | |||
输出数据如下:: | |||
{'words': ['It', "'s", 'a', 'lovely', 'film', 'with', 'lovely', 'performances', 'by', 'Buy', 'and', 'Accorsi', '.'] type=list, | |||
'target': positive type=str} | |||
除了读取数据外,fastNLP 还提供了读取其它文件类型的 Loader 类、读取 Embedding的 Loader 等。详见 :doc:`/fastNLP.io` 。 | |||
数据处理 | |||
我们使用 :class:`~fastNLP.DataSet` 类的 :meth:`~fastNLP.DataSet.apply` 方法将 ``target`` :mod:`~fastNLP.core.field` 转化为整数。 | |||
.. code-block:: python | |||
def label_to_int(x): | |||
if x['target']=="positive": | |||
return 1 | |||
elif x['target']=="negative": | |||
return 0 | |||
else: | |||
return 2 | |||
# 将label转为整数 | |||
dataset.apply(lambda x: label_to_int(x), new_field_name='target') | |||
``words`` 和 ``target`` 已经足够用于 :class:`~fastNLP.models.CNNText` 的训练了,但我们从其文档 | |||
:class:`~fastNLP.models.CNNText` 中看到,在 :meth:`~fastNLP.models.CNNText.forward` 的时候,还可以传入可选参数 ``seq_len`` 。 | |||
所以,我们再使用 :meth:`~fastNLP.DataSet.apply_field` 方法增加一个名为 ``seq_len`` 的 :mod:`~fastNLP.core.field` 。 | |||
.. code-block:: python | |||
# 增加长度信息 | |||
dataset.apply_field(lambda x: len(x), field_name='words', new_field_name='seq_len') | |||
观察可知: :meth:`~fastNLP.DataSet.apply_field` 与 :meth:`~fastNLP.DataSet.apply` 类似, | |||
但所传入的 `lambda` 函数是针对一个 :class:`~fastNLP.Instance` 中的一个 :mod:`~fastNLP.core.field` 的; | |||
而 :meth:`~fastNLP.DataSet.apply` 所传入的 `lambda` 函数是针对整个 :class:`~fastNLP.Instance` 的。 | |||
.. note:: | |||
`lambda` 函数即匿名函数,是 Python 的重要特性。 ``lambda x: len(x)`` 和下面的这个函数的作用相同:: | |||
def func_lambda(x): | |||
return len(x) | |||
你也可以编写复杂的函数做为 :meth:`~fastNLP.DataSet.apply_field` 与 :meth:`~fastNLP.DataSet.apply` 的参数 | |||
Vocabulary 的使用 | |||
我们再用 :class:`~fastNLP.Vocabulary` 类来统计数据中出现的单词,并使用 :meth:`~fastNLP.Vocabulary.index_dataset` | |||
将单词序列转化为训练可用的数字序列。 | |||
.. code-block:: python | |||
from fastNLP import Vocabulary | |||
# 使用Vocabulary类统计单词,并将单词序列转化为数字序列 | |||
vocab = Vocabulary(min_freq=2).from_dataset(dataset, field_name='words') | |||
vocab.index_dataset(dataset, field_name='words',new_field_name='words') | |||
print(dataset[0]) | |||
输出数据如下:: | |||
{'words': [27, 9, 6, 913, 16, 18, 913, 124, 31, 5715, 5, 1, 2] type=list, | |||
'target': 1 type=int, | |||
'seq_len': 13 type=int} | |||
--------------------- | |||
使用内置模型训练 | |||
--------------------- | |||
内置模型的输入输出命名 | |||
fastNLP内置了一些完整的神经网络模型,详见 :doc:`/fastNLP.models` , 我们使用其中的 :class:`~fastNLP.models.CNNText` 模型进行训练。 | |||
为了使用内置的 :class:`~fastNLP.models.CNNText`,我们必须修改 :class:`~fastNLP.DataSet` 中 :mod:`~fastNLP.core.field` 的名称。 | |||
在这个例子中模型输入 (forward方法的参数) 为 ``words`` 和 ``seq_len`` ; 预测输出为 ``pred`` ;标准答案为 ``target`` 。 | |||
具体的命名规范可以参考 :doc:`/fastNLP.core.const` 。 | |||
如果不想查看文档,您也可以使用 :class:`~fastNLP.Const` 类进行命名。下面的代码展示了给 :class:`~fastNLP.DataSet` 中 | |||
:mod:`~fastNLP.core.field` 改名的 :meth:`~fastNLP.DataSet.rename_field` 方法,以及 :class:`~fastNLP.Const` 类的使用方法。 | |||
.. code-block:: python | |||
from fastNLP import Const | |||
dataset.rename_field('words', Const.INPUT) | |||
dataset.rename_field('seq_len', Const.INPUT_LEN) | |||
dataset.rename_field('target', Const.TARGET) | |||
print(Const.INPUT) | |||
print(Const.INPUT_LEN) | |||
print(Const.TARGET) | |||
print(Const.OUTPUT) | |||
输出结果为:: | |||
words | |||
seq_len | |||
target | |||
pred | |||
在给 :class:`~fastNLP.DataSet` 中 :mod:`~fastNLP.core.field` 改名后,我们还需要设置训练所需的输入和目标,这里使用的是 | |||
:meth:`~fastNLP.DataSet.set_input` 和 :meth:`~fastNLP.DataSet.set_target` 两个函数。 | |||
.. code-block:: python | |||
#使用dataset的 set_input 和 set_target函数,告诉模型dataset中那些数据是输入,那些数据是标签(目标输出) | |||
dataset.set_input(Const.INPUT, Const.INPUT_LEN) | |||
dataset.set_target(Const.TARGET) | |||
数据集分割 | |||
除了修改 :mod:`~fastNLP.core.field` 之外,我们还可以对 :class:`~fastNLP.DataSet` 进行分割,以供训练、开发和测试使用。 | |||
下面这段代码展示了 :meth:`~fastNLP.DataSet.split` 的使用方法 | |||
.. code-block:: python | |||
train_dev_data, test_data = dataset.split(0.1) | |||
train_data, dev_data = train_dev_data.split(0.1) | |||
print(len(train_data), len(dev_data), len(test_data)) | |||
输出结果为:: | |||
9603 1067 1185 | |||
评价指标 | |||
训练模型需要提供一个评价指标。这里使用准确率做为评价指标。参数的 `命名规则` 跟上面类似。 | |||
``pred`` 参数对应的是模型的 forward 方法返回的 dict 中的一个 key 的名字。 | |||
``target`` 参数对应的是 :class:`~fastNLP.DataSet` 中作为标签的 :mod:`~fastNLP.core.field` 的名字。 | |||
.. code-block:: python | |||
from fastNLP import AccuracyMetric | |||
# metrics=AccuracyMetric() 在本例中与下面这行代码等价 | |||
metrics=AccuracyMetric(pred=Const.OUTPUT, target=Const.TARGET) | |||
损失函数 | |||
训练模型需要提供一个损失函数 | |||
,fastNLP中提供了直接可以导入使用的四种loss,分别为: | |||
* :class:`~fastNLP.CrossEntropyLoss`:包装了torch.nn.functional.cross_entropy()函数,返回交叉熵损失(可以运用于多分类场景) | |||
* :class:`~fastNLP.BCELoss`:包装了torch.nn.functional.binary_cross_entropy()函数,返回二分类的交叉熵 | |||
* :class:`~fastNLP.L1Loss`:包装了torch.nn.functional.l1_loss()函数,返回L1 损失 | |||
* :class:`~fastNLP.NLLLoss`:包装了torch.nn.functional.nll_loss()函数,返回负对数似然损失 | |||
下面提供了一个在分类问题中常用的交叉熵损失。注意它的 **初始化参数** 。 | |||
``pred`` 参数对应的是模型的 forward 方法返回的 dict 中的一个 key 的名字。 | |||
``target`` 参数对应的是 :class:`~fastNLP.DataSet` 中作为标签的 :mod:`~fastNLP.core.field` 的名字。 | |||
这里我们用 :class:`~fastNLP.Const` 来辅助命名,如果你自己编写模型中 forward 方法的返回值或 | |||
数据集中 :mod:`~fastNLP.core.field` 的名字与本例不同, 你可以把 ``pred`` 参数和 ``target`` 参数设定符合自己代码的值。 | |||
.. code-block:: python | |||
from fastNLP import CrossEntropyLoss | |||
# loss = CrossEntropyLoss() 在本例中与下面这行代码等价 | |||
loss = CrossEntropyLoss(pred=Const.OUTPUT, target=Const.TARGET) | |||
优化器 | |||
定义模型运行的时候使用的优化器,可以使用fastNLP包装好的优化器: | |||
* :class:`~fastNLP.SGD` :包装了torch.optim.SGD优化器 | |||
* :class:`~fastNLP.Adam` :包装了torch.optim.Adam优化器 | |||
也可以直接使用torch.optim.Optimizer中的优化器,并在实例化 :class:`~fastNLP.Trainer` 类的时候传入优化器实参 | |||
.. code-block:: python | |||
import torch.optim as optim | |||
from fastNLP import Adam | |||
#使用 torch.optim 定义优化器 | |||
optimizer_1=optim.RMSprop(model_cnn.parameters(), lr=0.01, alpha=0.99, eps=1e-08, weight_decay=0, momentum=0, centered=False) | |||
#使用fastNLP中包装的 Adam 定义优化器 | |||
optimizer_2=Adam(lr=4e-3, betas=(0.9, 0.999), eps=1e-08, weight_decay=0, model_params=model_cnn.parameters()) | |||
快速训练 | |||
现在我们可以导入 fastNLP 内置的文本分类模型 :class:`~fastNLP.models.CNNText` ,并使用 :class:`~fastNLP.Trainer` 进行训练, | |||
除了使用 :class:`~fastNLP.Trainer`进行训练,我们也可以通过使用 :class:`~fastNLP.DataSetIter` 来编写自己的训练过程,具体见 :doc:`/tutorials/tutorial_5_datasetiter` | |||
.. code-block:: python | |||
from fastNLP.models import CNNText | |||
#词嵌入的维度、训练的轮数和batch size | |||
EMBED_DIM = 100 | |||
N_EPOCHS = 10 | |||
BATCH_SIZE = 16 | |||
#使用CNNText的时候第一个参数输入一个tuple,作为模型定义embedding的参数 | |||
#还可以传入 kernel_nums, kernel_sizes, padding, dropout的自定义值 | |||
model_cnn = CNNText((len(vocab),EMBED_DIM), num_classes=3, padding=2, dropout=0.1) | |||
#如果在定义trainer的时候没有传入optimizer参数,模型默认的优化器为torch.optim.Adam且learning rate为lr=4e-3 | |||
#这里只使用了optimizer_1作为优化器输入,感兴趣可以尝试optimizer_2或者其他优化器作为输入 | |||
#这里只使用了loss作为损失函数输入,感兴趣可以尝试其他损失函数输入 | |||
trainer = Trainer(model=model_cnn, train_data=train_data, dev_data=dev_data, loss=loss, metrics=metrics, | |||
optimizer=optimizer_1,n_epochs=N_EPOCHS, batch_size=BATCH_SIZE) | |||
trainer.train() | |||
训练过程的输出如下:: | |||
input fields after batch(if batch size is 2): | |||
words: (1)type:torch.Tensor (2)dtype:torch.int64, (3)shape:torch.Size([2, 40]) | |||
seq_len: (1)type:torch.Tensor (2)dtype:torch.int64, (3)shape:torch.Size([2]) | |||
target fields after batch(if batch size is 2): | |||
target: (1)type:torch.Tensor (2)dtype:torch.int64, (3)shape:torch.Size([2]) | |||
training epochs started 2019-07-08-15-44-48 | |||
Evaluation at Epoch 1/10. Step:601/6010. AccuracyMetric: acc=0.59044 | |||
Evaluation at Epoch 2/10. Step:1202/6010. AccuracyMetric: acc=0.599813 | |||
Evaluation at Epoch 3/10. Step:1803/6010. AccuracyMetric: acc=0.508903 | |||
Evaluation at Epoch 4/10. Step:2404/6010. AccuracyMetric: acc=0.596064 | |||
Evaluation at Epoch 5/10. Step:3005/6010. AccuracyMetric: acc=0.47985 | |||
Evaluation at Epoch 6/10. Step:3606/6010. AccuracyMetric: acc=0.589503 | |||
Evaluation at Epoch 7/10. Step:4207/6010. AccuracyMetric: acc=0.311153 | |||
Evaluation at Epoch 8/10. Step:4808/6010. AccuracyMetric: acc=0.549203 | |||
Evaluation at Epoch 9/10. Step:5409/6010. AccuracyMetric: acc=0.581068 | |||
Evaluation at Epoch 10/10. Step:6010/6010. AccuracyMetric: acc=0.523899 | |||
In Epoch:2/Step:1202, got best dev performance:AccuracyMetric: acc=0.599813 | |||
Reloaded the best model. | |||
快速测试 | |||
与 :class:`~fastNLP.Trainer` 对应,fastNLP 也提供了 :class:`~fastNLP.Tester` 用于快速测试,用法如下 | |||
.. code-block:: python | |||
from fastNLP import Tester | |||
tester = Tester(test_data, model_cnn, metrics=AccuracyMetric()) | |||
tester.test() | |||
训练过程输出如下:: | |||
[tester] | |||
AccuracyMetric: acc=0.565401 |
@@ -0,0 +1,250 @@ | |||
============================================================================== | |||
动手实现一个文本分类器II-使用DataSetIter实现自定义训练过程 | |||
============================================================================== | |||
我们使用和 :doc:`/user/quickstart` 中一样的任务来进行详细的介绍。给出一段评价性文字,预测其情感倾向是积极(label=1)、 | |||
消极(label=0)还是中性(label=2),使用 :class:`~fastNLP.DataSetIter` 类来编写自己的训练过程。 | |||
自己编写训练过程之前的内容与 :doc:`/tutorials/tutorial_4_loss_optimizer` 中的完全一样,如已经阅读过可以跳过。 | |||
-------------- | |||
数据处理 | |||
-------------- | |||
数据读入 | |||
我们可以使用 fastNLP :mod:`fastNLP.io` 模块中的 :class:`~fastNLP.io.SSTLoader` 类,轻松地读取SST数据集(数据来源:https://nlp.stanford.edu/sentiment/trainDevTestTrees_PTB.zip)。 | |||
这里的 dataset 是 fastNLP 中 :class:`~fastNLP.DataSet` 类的对象。 | |||
.. code-block:: python | |||
from fastNLP.io import SSTLoader | |||
loader = SSTLoader() | |||
#这里的all.txt是下载好数据后train.txt、dev.txt、test.txt的组合 | |||
dataset = loader.load("./trainDevTestTrees_PTB/trees/all.txt") | |||
print(dataset[0]) | |||
输出数据如下:: | |||
{'words': ['It', "'s", 'a', 'lovely', 'film', 'with', 'lovely', 'performances', 'by', 'Buy', 'and', 'Accorsi', '.'] type=list, | |||
'target': positive type=str} | |||
除了读取数据外,fastNLP 还提供了读取其它文件类型的 Loader 类、读取 Embedding的 Loader 等。详见 :doc:`/fastNLP.io` 。 | |||
数据处理 | |||
我们使用 :class:`~fastNLP.DataSet` 类的 :meth:`~fastNLP.DataSet.apply` 方法将 ``target`` :mod:`~fastNLP.core.field` 转化为整数。 | |||
.. code-block:: python | |||
def label_to_int(x): | |||
if x['target']=="positive": | |||
return 1 | |||
elif x['target']=="negative": | |||
return 0 | |||
else: | |||
return 2 | |||
# 将label转为整数 | |||
dataset.apply(lambda x: label_to_int(x), new_field_name='target') | |||
``words`` 和 ``target`` 已经足够用于 :class:`~fastNLP.models.CNNText` 的训练了,但我们从其文档 | |||
:class:`~fastNLP.models.CNNText` 中看到,在 :meth:`~fastNLP.models.CNNText.forward` 的时候,还可以传入可选参数 ``seq_len`` 。 | |||
所以,我们再使用 :meth:`~fastNLP.DataSet.apply_field` 方法增加一个名为 ``seq_len`` 的 :mod:`~fastNLP.core.field` 。 | |||
.. code-block:: python | |||
# 增加长度信息 | |||
dataset.apply_field(lambda x: len(x), field_name='words', new_field_name='seq_len') | |||
观察可知: :meth:`~fastNLP.DataSet.apply_field` 与 :meth:`~fastNLP.DataSet.apply` 类似, | |||
但所传入的 `lambda` 函数是针对一个 :class:`~fastNLP.Instance` 中的一个 :mod:`~fastNLP.core.field` 的; | |||
而 :meth:`~fastNLP.DataSet.apply` 所传入的 `lambda` 函数是针对整个 :class:`~fastNLP.Instance` 的。 | |||
.. note:: | |||
`lambda` 函数即匿名函数,是 Python 的重要特性。 ``lambda x: len(x)`` 和下面的这个函数的作用相同:: | |||
def func_lambda(x): | |||
return len(x) | |||
你也可以编写复杂的函数做为 :meth:`~fastNLP.DataSet.apply_field` 与 :meth:`~fastNLP.DataSet.apply` 的参数 | |||
Vocabulary 的使用 | |||
我们再用 :class:`~fastNLP.Vocabulary` 类来统计数据中出现的单词,并使用 :meth:`~fastNLP.Vocabulary.index_dataset` | |||
将单词序列转化为训练可用的数字序列。 | |||
.. code-block:: python | |||
from fastNLP import Vocabulary | |||
# 使用Vocabulary类统计单词,并将单词序列转化为数字序列 | |||
vocab = Vocabulary(min_freq=2).from_dataset(dataset, field_name='words') | |||
vocab.index_dataset(dataset, field_name='words',new_field_name='words') | |||
print(dataset[0]) | |||
输出数据如下:: | |||
{'words': [27, 9, 6, 913, 16, 18, 913, 124, 31, 5715, 5, 1, 2] type=list, | |||
'target': 1 type=int, | |||
'seq_len': 13 type=int} | |||
--------------------- | |||
使用内置模型训练 | |||
--------------------- | |||
内置模型的输入输出命名 | |||
fastNLP内置了一些完整的神经网络模型,详见 :doc:`/fastNLP.models` , 我们使用其中的 :class:`~fastNLP.models.CNNText` 模型进行训练。 | |||
为了使用内置的 :class:`~fastNLP.models.CNNText`,我们必须修改 :class:`~fastNLP.DataSet` 中 :mod:`~fastNLP.core.field` 的名称。 | |||
在这个例子中模型输入 (forward方法的参数) 为 ``words`` 和 ``seq_len`` ; 预测输出为 ``pred`` ;标准答案为 ``target`` 。 | |||
具体的命名规范可以参考 :doc:`/fastNLP.core.const` 。 | |||
如果不想查看文档,您也可以使用 :class:`~fastNLP.Const` 类进行命名。下面的代码展示了给 :class:`~fastNLP.DataSet` 中 | |||
:mod:`~fastNLP.core.field` 改名的 :meth:`~fastNLP.DataSet.rename_field` 方法,以及 :class:`~fastNLP.Const` 类的使用方法。 | |||
.. code-block:: python | |||
from fastNLP import Const | |||
dataset.rename_field('words', Const.INPUT) | |||
dataset.rename_field('seq_len', Const.INPUT_LEN) | |||
dataset.rename_field('target', Const.TARGET) | |||
print(Const.INPUT) | |||
print(Const.INPUT_LEN) | |||
print(Const.TARGET) | |||
print(Const.OUTPUT) | |||
输出结果为:: | |||
words | |||
seq_len | |||
target | |||
pred | |||
在给 :class:`~fastNLP.DataSet` 中 :mod:`~fastNLP.core.field` 改名后,我们还需要设置训练所需的输入和目标,这里使用的是 | |||
:meth:`~fastNLP.DataSet.set_input` 和 :meth:`~fastNLP.DataSet.set_target` 两个函数。 | |||
.. code-block:: python | |||
#使用dataset的 set_input 和 set_target函数,告诉模型dataset中那些数据是输入,那些数据是标签(目标输出) | |||
dataset.set_input(Const.INPUT, Const.INPUT_LEN) | |||
dataset.set_target(Const.TARGET) | |||
数据集分割 | |||
除了修改 :mod:`~fastNLP.core.field` 之外,我们还可以对 :class:`~fastNLP.DataSet` 进行分割,以供训练、开发和测试使用。 | |||
下面这段代码展示了 :meth:`~fastNLP.DataSet.split` 的使用方法 | |||
.. code-block:: python | |||
train_dev_data, test_data = dataset.split(0.1) | |||
train_data, dev_data = train_dev_data.split(0.1) | |||
print(len(train_data), len(dev_data), len(test_data)) | |||
输出结果为:: | |||
9603 1067 1185 | |||
评价指标 | |||
训练模型需要提供一个评价指标。这里使用准确率做为评价指标。参数的 `命名规则` 跟上面类似。 | |||
``pred`` 参数对应的是模型的 forward 方法返回的 dict 中的一个 key 的名字。 | |||
``target`` 参数对应的是 :class:`~fastNLP.DataSet` 中作为标签的 :mod:`~fastNLP.core.field` 的名字。 | |||
.. code-block:: python | |||
from fastNLP import AccuracyMetric | |||
# metrics=AccuracyMetric() 在本例中与下面这行代码等价 | |||
metrics=AccuracyMetric(pred=Const.OUTPUT, target=Const.TARGET) | |||
-------------------------- | |||
自己编写训练过程 | |||
-------------------------- | |||
如果你想用类似 PyTorch 的使用方法,自己编写训练过程,你可以参考下面这段代码。 | |||
其中使用了 fastNLP 提供的 :class:`~fastNLP.DataSetIter` 来获得小批量训练的小批量数据, | |||
使用 :class:`~fastNLP.BucketSampler` 做为 :class:`~fastNLP.DataSetIter` 的参数来选择采样的方式。 | |||
DataSetIter | |||
fastNLP定义的 :class:`~fastNLP.DataSetIter` 类,用于定义一个batch,并实现batch的多种功能,在初始化时传入的参数有: | |||
* dataset: :class:`~fastNLP.DataSet` 对象, 数据集 | |||
* batch_size: 取出的batch大小 | |||
* sampler: 规定使用的 :class:`~fastNLP.Sampler` 若为 None, 使用 :class:`~fastNLP.RandomSampler` (Default: None) | |||
* as_numpy: 若为 True, 输出batch为 `numpy.array`. 否则为 `torch.Tensor` (Default: False) | |||
* prefetch: 若为 True使用多进程预先取出下一batch. (Default: False) | |||
sampler | |||
fastNLP 实现的采样器有: | |||
* :class:`~fastNLP.BucketSampler` 可以随机地取出长度相似的元素 【初始化参数: num_buckets:bucket的数量; batch_size:batch大小; seq_len_field_name:dataset中对应序列长度的 :mod:`~fastNLP.core.field` 的名字】 | |||
* SequentialSampler: 顺序取出元素的采样器【无初始化参数】 | |||
* RandomSampler:随机化取元素的采样器【无初始化参数】 | |||
以下代码使用BucketSampler作为 :class:`~fastNLP.DataSetIter` 初始化的输入,运用 :class:`~fastNLP.DataSetIter` 自己写训练程序 | |||
.. code-block:: python | |||
from fastNLP import BucketSampler | |||
from fastNLP import DataSetIter | |||
from fastNLP.models import CNNText | |||
from fastNLP import Tester | |||
import torch | |||
import time | |||
embed_dim = 100 | |||
model = CNNText((len(vocab),embed_dim), num_classes=3, padding=2, dropout=0.1) | |||
def train(epoch, data, devdata): | |||
optimizer = torch.optim.Adam(model.parameters(), lr=0.001) | |||
lossfunc = torch.nn.CrossEntropyLoss() | |||
batch_size = 32 | |||
# 定义一个Batch,传入DataSet,规定batch_size和去batch的规则。 | |||
# 顺序(Sequential),随机(Random),相似长度组成一个batch(Bucket) | |||
train_sampler = BucketSampler(batch_size=batch_size, seq_len_field_name='seq_len') | |||
train_batch = DataSetIter(batch_size=batch_size, dataset=data, sampler=train_sampler) | |||
start_time = time.time() | |||
print("-"*5+"start training"+"-"*5) | |||
for i in range(epoch): | |||
loss_list = [] | |||
for batch_x, batch_y in train_batch: | |||
optimizer.zero_grad() | |||
output = model(batch_x['words']) | |||
loss = lossfunc(output['pred'], batch_y['target']) | |||
loss.backward() | |||
optimizer.step() | |||
loss_list.append(loss.item()) | |||
#这里verbose如果为0,在调用Tester对象的test()函数时不输出任何信息,返回评估信息; 如果为1,打印出验证结果,返回评估信息 | |||
#在调用过Tester对象的test()函数后,调用其_format_eval_results(res)函数,结构化输出验证结果 | |||
tester_tmp = Tester(devdata, model, metrics=AccuracyMetric(), verbose=0) | |||
res=tester_tmp.test() | |||
print('Epoch {:d} Avg Loss: {:.2f}'.format(i, sum(loss_list) / len(loss_list)),end=" ") | |||
print(tester._format_eval_results(res),end=" ") | |||
print('{:d}ms'.format(round((time.time()-start_time)*1000))) | |||
loss_list.clear() | |||
train(10, train_data, dev_data) | |||
#使用tester进行快速测试 | |||
tester = Tester(test_data, model, metrics=AccuracyMetric()) | |||
tester.test() | |||
这段代码的输出如下:: | |||
-----start training----- | |||
Epoch 0 Avg Loss: 1.09 AccuracyMetric: acc=0.480787 58989ms | |||
Epoch 1 Avg Loss: 1.00 AccuracyMetric: acc=0.500469 118348ms | |||
Epoch 2 Avg Loss: 0.93 AccuracyMetric: acc=0.536082 176220ms | |||
Epoch 3 Avg Loss: 0.87 AccuracyMetric: acc=0.556701 236032ms | |||
Epoch 4 Avg Loss: 0.78 AccuracyMetric: acc=0.562324 294351ms | |||
Epoch 5 Avg Loss: 0.69 AccuracyMetric: acc=0.58388 353673ms | |||
Epoch 6 Avg Loss: 0.60 AccuracyMetric: acc=0.574508 412106ms | |||
Epoch 7 Avg Loss: 0.51 AccuracyMetric: acc=0.589503 471097ms | |||
Epoch 8 Avg Loss: 0.44 AccuracyMetric: acc=0.581068 529174ms | |||
Epoch 9 Avg Loss: 0.39 AccuracyMetric: acc=0.572634 586216ms | |||
[tester] | |||
AccuracyMetric: acc=0.527426 | |||
@@ -0,0 +1,114 @@ | |||
===================== | |||
快速实现序列标注模型 | |||
===================== | |||
这一部分的内容主要展示如何使用fastNLP 实现序列标注任务。你可以使用fastNLP的各个组件快捷,方便地完成序列标注任务,达到出色的效果。 | |||
在阅读这篇Tutorial前,希望你已经熟悉了fastNLP的基础使用,包括基本数据结构以及数据预处理,embedding的嵌入等,希望你对之前的教程有更进一步的掌握。 | |||
我们将对CoNLL-03的英文数据集进行处理,展示如何完成命名实体标注任务整个训练的过程。 | |||
载入数据 | |||
=================================== | |||
fastNLP可以方便地载入各种类型的数据。同时,针对常见的数据集,我们已经预先实现了载入方法,其中包含CoNLL-03数据集。 | |||
在设计dataloader时,以DataSetLoader为基类,可以改写并应用于其他数据集的载入。 | |||
.. code-block:: python | |||
class Conll2003DataLoader(DataSetLoader): | |||
def __init__(self, task:str='ner', encoding_type:str='bioes'): | |||
assert task in ('ner', 'pos', 'chunk') | |||
index = {'ner':3, 'pos':1, 'chunk':2}[task] | |||
#ConllLoader是fastNLP内置的类 | |||
self._loader = ConllLoader(headers=['raw_words', 'target'], indexes=[0, index]) | |||
self._tag_converters = None | |||
if task in ('ner', 'chunk'): | |||
#iob和iob2bioes会对tag进行统一,标准化 | |||
self._tag_converters = [iob2] | |||
if encoding_type == 'bioes': | |||
self._tag_converters.append(iob2bioes) | |||
def load(self, path: str): | |||
dataset = self._loader.load(path) | |||
def convert_tag_schema(tags): | |||
for converter in self._tag_converters: | |||
tags = converter(tags) | |||
return tags | |||
if self._tag_converters: | |||
#使用apply实现convert_tag_schema函数,实际上也支持匿名函数 | |||
dataset.apply_field(convert_tag_schema, field_name=Const.TARGET, new_field_name=Const.TARGET) | |||
return dataset | |||
输出数据格式如: | |||
{'raw_words': ['on', 'Friday', ':'] type=list, | |||
'target': ['O', 'O', 'O'] type=list}, | |||
数据处理 | |||
---------------------------- | |||
我们进一步处理数据。将数据和词表封装在 :class:`~fastNLP.DataBundle` 类中。data是DataBundle的实例。 | |||
我们输入模型的数据包括char embedding,以及word embedding。在数据处理部分,我们尝试完成词表的构建。 | |||
使用fastNLP中的Vocabulary类来构建词表。 | |||
.. code-block:: python | |||
word_vocab = Vocabulary(min_freq=2) | |||
word_vocab.from_dataset(data.datasets['train'], field_name=Const.INPUT) | |||
word_vocab.index_dataset(*data.datasets.values(),field_name=Const.INPUT, new_field_name=Const.INPUT) | |||
处理后的data对象内部为: | |||
dataset | |||
vocabs | |||
dataset保存了train和test中的数据,并保存为dataset类型 | |||
vocab保存了words,raw-words以及target的词表。 | |||
模型构建 | |||
-------------------------------- | |||
我们使用CNN-BILSTM-CRF模型完成这一任务。在网络构建方面,fastNLP的网络定义继承pytorch的 :class:`nn.Module` 类。 | |||
自己可以按照pytorch的方式定义网络。需要注意的是命名。fastNLP的标准命名位于 :class:`~fastNLP.Const` 类。 | |||
模型的训练 | |||
首先实例化模型,导入所需的char embedding以及word embedding。Embedding的载入可以参考教程。 | |||
也可以查看 :mod:`~fastNLP.modules.encoder.embedding` 使用所需的embedding 载入方法。 | |||
fastNLP将模型的训练过程封装在了 :class:`~fastnlp.trainer` 类中。 | |||
根据不同的任务调整trainer中的参数即可。通常,一个trainer实例需要有:指定的训练数据集,模型,优化器,loss函数,评测指标,以及指定训练的epoch数,batch size等参数。 | |||
.. code-block:: python | |||
#实例化模型 | |||
model = CNNBiLSTMCRF(word_embed, char_embed, hidden_size=200, num_layers=1, tag_vocab=data.vocabs[Const.TARGET], encoding_type=encoding_type) | |||
#定义优化器 | |||
optimizer = Adam(model.parameters(), lr=0.005) | |||
#定义评估指标 | |||
Metrics=SpanFPreRecMetric(tag_vocab=data.vocabs[Const.TARGET], encoding_type=encoding_type) | |||
#实例化trainer | |||
trainer = Trainer(train_data=data.datasets['train'], model=model, optimizer=optimizer, dev_data=data.datasets['test'], batch_size=10, metrics=Metrics,callbacks=callbacks, n_epochs=100) | |||
#开始训练 | |||
trainer.train() | |||
训练中会保存最优的参数配置。 | |||
训练的结果如下: | |||
.. code-block:: python | |||
Evaluation on DataSet test: | |||
SpanFPreRecMetric: f=0.727661, pre=0.732293, rec=0.723088 | |||
Evaluation at Epoch 1/100. Step:1405/140500. SpanFPreRecMetric: f=0.727661, pre=0.732293, rec=0.723088 | |||
Evaluation on DataSet test: | |||
SpanFPreRecMetric: f=0.784307, pre=0.779371, rec=0.789306 | |||
Evaluation at Epoch 2/100. Step:2810/140500. SpanFPreRecMetric: f=0.784307, pre=0.779371, rec=0.789306 | |||
Evaluation on DataSet test: | |||
SpanFPreRecMetric: f=0.810068, pre=0.811003, rec=0.809136 | |||
Evaluation at Epoch 3/100. Step:4215/140500. SpanFPreRecMetric: f=0.810068, pre=0.811003, rec=0.809136 | |||
Evaluation on DataSet test: | |||
SpanFPreRecMetric: f=0.829592, pre=0.84153, rec=0.817989 | |||
Evaluation at Epoch 4/100. Step:5620/140500. SpanFPreRecMetric: f=0.829592, pre=0.84153, rec=0.817989 | |||
Evaluation on DataSet test: | |||
SpanFPreRecMetric: f=0.828789, pre=0.837096, rec=0.820644 | |||
Evaluation at Epoch 5/100. Step:7025/140500. SpanFPreRecMetric: f=0.828789, pre=0.837096, rec=0.820644 | |||
@@ -0,0 +1,207 @@ | |||
====================================== | |||
使用Modules和Models快速搭建自定义模型 | |||
====================================== | |||
:mod:`~fastNLP.modules` 和 :mod:`~fastNLP.models` 用于构建 fastNLP 所需的神经网络模型,它可以和 torch.nn 中的模型一起使用。 | |||
下面我们会分三节介绍编写构建模型的具体方法。 | |||
---------------------- | |||
使用 models 中的模型 | |||
---------------------- | |||
fastNLP 在 :mod:`~fastNLP.models` 模块中内置了如 :class:`~fastNLP.models.CNNText` 、 | |||
:class:`~fastNLP.models.SeqLabeling` 等完整的模型,以供用户直接使用。 | |||
以 :class:`~fastNLP.models.CNNText` 为例,我们看一个简单的文本分类的任务的实现过程。 | |||
首先是数据读入和处理部分,这里的代码和 :doc:`快速入门 </user/quickstart>` 中一致。 | |||
.. code-block:: python | |||
from fastNLP.io import CSVLoader | |||
from fastNLP import Vocabulary, CrossEntropyLoss, AccuracyMetric | |||
loader = CSVLoader(headers=('raw_sentence', 'label'), sep='\t') | |||
dataset = loader.load("./sample_data/tutorial_sample_dataset.csv") | |||
dataset.apply(lambda x: x['raw_sentence'].lower(), new_field_name='sentence') | |||
dataset.apply_field(lambda x: x.split(), field_name='sentence', new_field_name='words', is_input=True) | |||
dataset.apply(lambda x: int(x['label']), new_field_name='target', is_target=True) | |||
train_dev_data, test_data = dataset.split(0.1) | |||
train_data, dev_data = train_dev_data.split(0.1) | |||
vocab = Vocabulary(min_freq=2).from_dataset(train_data, field_name='words') | |||
vocab.index_dataset(train_data, dev_data, test_data, field_name='words', new_field_name='words') | |||
然后我们从 :mod:`~fastNLP.models` 中导入 ``CNNText`` 模型,用它进行训练 | |||
.. code-block:: python | |||
from fastNLP.models import CNNText | |||
from fastNLP import Trainer | |||
model_cnn = CNNText((len(vocab),50), num_classes=5, padding=2, dropout=0.1) | |||
trainer = Trainer(model=model_cnn, train_data=train_data, dev_data=dev_data, | |||
loss=CrossEntropyLoss(), metrics=AccuracyMetric()) | |||
trainer.train() | |||
在 iPython 环境输入 `model_cnn` ,我们可以看到 ``model_cnn`` 的网络结构 | |||
.. parsed-literal:: | |||
CNNText( | |||
(embed): Embedding( | |||
169, 50 | |||
(dropout): Dropout(p=0.0) | |||
) | |||
(conv_pool): ConvMaxpool( | |||
(convs): ModuleList( | |||
(0): Conv1d(50, 3, kernel_size=(3,), stride=(1,), padding=(2,)) | |||
(1): Conv1d(50, 4, kernel_size=(4,), stride=(1,), padding=(2,)) | |||
(2): Conv1d(50, 5, kernel_size=(5,), stride=(1,), padding=(2,)) | |||
) | |||
) | |||
(dropout): Dropout(p=0.1) | |||
(fc): Linear(in_features=12, out_features=5, bias=True) | |||
) | |||
FastNLP 中内置的 models 如下表所示,您可以点击具体的名称查看详细的 API: | |||
.. csv-table:: | |||
:header: 名称, 介绍 | |||
:class:`~fastNLP.models.CNNText` , 使用 CNN 进行文本分类的模型 | |||
:class:`~fastNLP.models.SeqLabeling` , 简单的序列标注模型 | |||
:class:`~fastNLP.models.AdvSeqLabel` , 更大网络结构的序列标注模型 | |||
:class:`~fastNLP.models.ESIM` , ESIM 模型的实现 | |||
:class:`~fastNLP.models.StarTransEnc` , 带 word-embedding的Star-Transformer模 型 | |||
:class:`~fastNLP.models.STSeqLabel` , 用于序列标注的 Star-Transformer 模型 | |||
:class:`~fastNLP.models.STNLICls` ,用于自然语言推断 (NLI) 的 Star-Transformer 模型 | |||
:class:`~fastNLP.models.STSeqCls` , 用于分类任务的 Star-Transformer 模型 | |||
:class:`~fastNLP.models.BiaffineParser` , Biaffine 依存句法分析网络的实现 | |||
---------------------------- | |||
使用 nn.torch 编写模型 | |||
---------------------------- | |||
FastNLP 完全支持使用 pyTorch 编写的模型,但与 pyTorch 中编写模型的常见方法不同, | |||
用于 fastNLP 的模型中 forward 函数需要返回一个字典,字典中至少需要包含 ``pred`` 这个字段。 | |||
下面是使用 pyTorch 中的 torch.nn 模块编写的文本分类,注意观察代码中标注的向量维度。 | |||
由于 pyTorch 使用了约定俗成的维度设置,使得 forward 中需要多次处理维度顺序 | |||
.. code-block:: python | |||
import torch | |||
import torch.nn as nn | |||
class LSTMText(nn.Module): | |||
def __init__(self, vocab_size, embedding_dim, output_dim, hidden_dim=64, num_layers=2, dropout=0.5): | |||
super().__init__() | |||
self.embedding = nn.Embedding(vocab_size, embedding_dim) | |||
self.lstm = nn.LSTM(embedding_dim, hidden_dim, num_layers=num_layers, bidirectional=True, dropout=dropout) | |||
self.fc = nn.Linear(hidden_dim * 2, output_dim) | |||
self.dropout = nn.Dropout(dropout) | |||
def forward(self, words): | |||
# (input) words : (batch_size, seq_len) | |||
words = words.permute(1,0) | |||
# words : (seq_len, batch_size) | |||
embedded = self.dropout(self.embedding(words)) | |||
# embedded : (seq_len, batch_size, embedding_dim) | |||
output, (hidden, cell) = self.lstm(embedded) | |||
# output: (seq_len, batch_size, hidden_dim * 2) | |||
# hidden: (num_layers * 2, batch_size, hidden_dim) | |||
# cell: (num_layers * 2, batch_size, hidden_dim) | |||
hidden = torch.cat((hidden[-2, :, :], hidden[-1, :, :]), dim=1) | |||
hidden = self.dropout(hidden) | |||
# hidden: (batch_size, hidden_dim * 2) | |||
pred = self.fc(hidden.squeeze(0)) | |||
# result: (batch_size, output_dim) | |||
return {"pred":pred} | |||
我们同样可以在 iPython 环境中查看这个模型的网络结构 | |||
.. parsed-literal:: | |||
LSTMText( | |||
(embedding): Embedding(169, 50) | |||
(lstm): LSTM(50, 64, num_layers=2, dropout=0.5, bidirectional=True) | |||
(fc): Linear(in_features=128, out_features=5, bias=True) | |||
(dropout): Dropout(p=0.5) | |||
) | |||
---------------------------- | |||
使用 modules 编写模型 | |||
---------------------------- | |||
下面我们使用 :mod:`fastNLP.modules` 中的组件来构建同样的网络。由于 fastNLP 统一把 ``batch_size`` 放在第一维, | |||
在编写代码的过程中会有一定的便利。 | |||
.. code-block:: python | |||
from fastNLP.modules import Embedding, LSTM, MLP | |||
class Model(nn.Module): | |||
def __init__(self, vocab_size, embedding_dim, output_dim, hidden_dim=64, num_layers=2, dropout=0.5): | |||
super().__init__() | |||
self.embedding = Embedding((vocab_size, embedding_dim)) | |||
self.lstm = LSTM(embedding_dim, hidden_dim, num_layers=num_layers, bidirectional=True) | |||
self.mlp = MLP([hidden_dim*2,output_dim], dropout=dropout) | |||
def forward(self, words): | |||
embedded = self.embedding(words) | |||
_,(hidden,_) = self.lstm(embedded) | |||
pred = self.mlp(torch.cat((hidden[-1],hidden[-2]),dim=1)) | |||
return {"pred":pred} | |||
我们自己编写模型的网络结构如下 | |||
.. parsed-literal:: | |||
Model( | |||
(embedding): Embedding( | |||
169, 50 | |||
(dropout): Dropout(p=0.0) | |||
) | |||
(lstm): LSTM( | |||
(lstm): LSTM(50, 64, num_layers=2, batch_first=True, bidirectional=True) | |||
) | |||
(mlp): MLP( | |||
(hiddens): ModuleList() | |||
(output): Linear(in_features=128, out_features=5, bias=True) | |||
(dropout): Dropout(p=0.5) | |||
) | |||
) | |||
FastNLP 中包含的各种模块如下表,您可以点击具体的名称查看详细的 API,也可以通过 :doc:`/fastNLP.modules` 进行了解。 | |||
.. csv-table:: | |||
:header: 名称, 介绍 | |||
:class:`~fastNLP.modules.ConvolutionCharEncoder` , char级别的卷积 encoder | |||
:class:`~fastNLP.modules.LSTMCharEncoder` , char级别基于LSTM的 encoder | |||
:class:`~fastNLP.modules.ConvMaxpool` , 结合了Convolution和Max-Pooling于一体的模块 | |||
:class:`~fastNLP.modules.LSTM` , LSTM模块, 轻量封装了PyTorch的LSTM | |||
:class:`~fastNLP.modules.StarTransformer` , Star-Transformer 的encoder部分 | |||
:class:`~fastNLP.modules.TransformerEncoder` , Transformer的encoder模块,不包含embedding层 | |||
:class:`~fastNLP.modules.VarRNN` , Variational Dropout RNN 模块 | |||
:class:`~fastNLP.modules.VarLSTM` , Variational Dropout LSTM 模块 | |||
:class:`~fastNLP.modules.VarGRU` , Variational Dropout GRU 模块 | |||
:class:`~fastNLP.modules.MaxPool` , Max-pooling模块 | |||
:class:`~fastNLP.modules.MaxPoolWithMask` , 带mask矩阵的max pooling。在做 max-pooling的时候不会考虑mask值为0的位置。 | |||
:class:`~fastNLP.modules.AvgPool` , Average-pooling模块 | |||
:class:`~fastNLP.modules.AvgPoolWithMask` , 带mask矩阵的average pooling。在做 average-pooling的时候不会考虑mask值为0的位置。 | |||
:class:`~fastNLP.modules.MultiHeadAttention` , MultiHead Attention 模块 | |||
:class:`~fastNLP.modules.MLP` , 简单的多层感知器模块 | |||
:class:`~fastNLP.modules.ConditionalRandomField` , 条件随机场模块 | |||
:class:`~fastNLP.modules.viterbi_decode` , 给定一个特征矩阵以及转移分数矩阵,计算出最佳的路径以及对应的分数 (与 :class:`~fastNLP.modules.ConditionalRandomField` 配合使用) | |||
:class:`~fastNLP.modules.allowed_transitions` , 给定一个id到label的映射表,返回所有可以跳转的列表(与 :class:`~fastNLP.modules.ConditionalRandomField` 配合使用) | |||
:class:`~fastNLP.modules.TimestepDropout` , 简单包装过的Dropout 组件 |
@@ -0,0 +1,121 @@ | |||
=============================== | |||
使用Metric快速评测你的模型 | |||
=============================== | |||
在进行训练时,fastNLP提供了各种各样的 :mod:`~fastNLP.core.metrics` 。 | |||
如 :doc:`/user/quickstart` 中所介绍的,:class:`~fastNLP.AccuracyMetric` 类的对象被直接传到 :class:`~fastNLP.Trainer` 中用于训练 | |||
.. code-block:: python | |||
from fastNLP import Trainer, CrossEntropyLoss, AccuracyMetric | |||
trainer = Trainer(model=model, train_data=train_data, dev_data=dev_data, | |||
loss=CrossEntropyLoss(), metrics=AccuracyMetric()) | |||
trainer.train() | |||
除了 :class:`~fastNLP.AccuracyMetric` 之外,:class:`~fastNLP.SpanFPreRecMetric` 也是一种非常见的评价指标, | |||
例如在序列标注问题中,常以span的方式计算 F-measure, precision, recall。 | |||
另外,fastNLP 还实现了用于抽取式QA(如SQuAD)的metric :class:`~fastNLP.ExtractiveQAMetric`。 | |||
用户可以参考下面这个表格,点击第一列查看各个 :mod:`~fastNLP.core.metrics` 的详细文档。 | |||
.. csv-table:: | |||
:header: 名称, 介绍 | |||
:class:`~fastNLP.core.metrics.MetricBase` , 自定义metrics需继承的基类 | |||
:class:`~fastNLP.core.metrics.AccuracyMetric` , 简单的正确率metric | |||
:class:`~fastNLP.core.metrics.SpanFPreRecMetric` , "同时计算 F-measure, precision, recall 值的 metric" | |||
:class:`~fastNLP.core.metrics.ExtractiveQAMetric` , 用于抽取式QA任务 的metric | |||
更多的 :mod:`~fastNLP.core.metrics` 正在被添加到 fastNLP 当中,敬请期待。 | |||
------------------------------ | |||
定义自己的metrics | |||
------------------------------ | |||
在定义自己的metrics类时需继承 fastNLP 的 :class:`~fastNLP.core.metrics.MetricBase`, | |||
并覆盖写入 ``evaluate`` 和 ``get_metric`` 方法。 | |||
evaluate(xxx) 中传入一个批次的数据,将针对一个批次的预测结果做评价指标的累计 | |||
get_metric(xxx) 当所有数据处理完毕时调用该方法,它将根据 evaluate函数累计的评价指标统计量来计算最终的评价结果 | |||
以分类问题中,Accuracy计算为例,假设model的forward返回dict中包含 `pred` 这个key, 并且该key需要用于Accuracy:: | |||
class Model(nn.Module): | |||
def __init__(xxx): | |||
# do something | |||
def forward(self, xxx): | |||
# do something | |||
return {'pred': pred, 'other_keys':xxx} # pred's shape: batch_size x num_classes | |||
假设dataset中 `label` 这个field是需要预测的值,并且该field被设置为了target | |||
对应的AccMetric可以按如下的定义, version1, 只使用这一次:: | |||
class AccMetric(MetricBase): | |||
def __init__(self): | |||
super().__init__() | |||
# 根据你的情况自定义指标 | |||
self.corr_num = 0 | |||
self.total = 0 | |||
def evaluate(self, label, pred): # 这里的名称需要和dataset中target field与model返回的key是一样的,不然找不到对应的value | |||
# dev或test时,每个batch结束会调用一次该方法,需要实现如何根据每个batch累加metric | |||
self.total += label.size(0) | |||
self.corr_num += label.eq(pred).sum().item() | |||
def get_metric(self, reset=True): # 在这里定义如何计算metric | |||
acc = self.corr_num/self.total | |||
if reset: # 是否清零以便重新计算 | |||
self.corr_num = 0 | |||
self.total = 0 | |||
return {'acc': acc} # 需要返回一个dict,key为该metric的名称,该名称会显示到Trainer的progress bar中 | |||
version2,如果需要复用Metric,比如下一次使用AccMetric时,dataset中目标field不叫label而叫y,或者model的输出不是pred:: | |||
class AccMetric(MetricBase): | |||
def __init__(self, label=None, pred=None): | |||
# 假设在另一场景使用时,目标field叫y,model给出的key为pred_y。则只需要在初始化AccMetric时, | |||
# acc_metric = AccMetric(label='y', pred='pred_y')即可。 | |||
# 当初始化为acc_metric = AccMetric(),即label=None, pred=None, fastNLP会直接使用'label', 'pred'作为key去索取对 | |||
# 应的的值 | |||
super().__init__() | |||
self._init_param_map(label=label, pred=pred) # 该方法会注册label和pred. 仅需要注册evaluate()方法会用到的参数名即可 | |||
# 如果没有注册该则效果与version1就是一样的 | |||
# 根据你的情况自定义指标 | |||
self.corr_num = 0 | |||
self.total = 0 | |||
def evaluate(self, label, pred): # 这里的参数名称需要和self._init_param_map()注册时一致。 | |||
# dev或test时,每个batch结束会调用一次该方法,需要实现如何根据每个batch累加metric | |||
self.total += label.size(0) | |||
self.corr_num += label.eq(pred).sum().item() | |||
def get_metric(self, reset=True): # 在这里定义如何计算metric | |||
acc = self.corr_num/self.total | |||
if reset: # 是否清零以便重新计算 | |||
self.corr_num = 0 | |||
self.total = 0 | |||
return {'acc': acc} # 需要返回一个dict,key为该metric的名称,该名称会显示到Trainer的progress bar中 | |||
``MetricBase`` 将会在输入的字典 ``pred_dict`` 和 ``target_dict`` 中进行检查. | |||
``pred_dict`` 是模型当中 ``forward()`` 函数或者 ``predict()`` 函数的返回值. | |||
``target_dict`` 是DataSet当中的ground truth, 判定ground truth的条件是field的 ``is_target`` 被设置为True. | |||
``MetricBase`` 会进行以下的类型检测: | |||
1. self.evaluate当中是否有varargs, 这是不支持的. | |||
2. self.evaluate当中所需要的参数是否既不在 ``pred_dict`` 也不在 ``target_dict`` . | |||
3. self.evaluate当中所需要的参数是否既在 ``pred_dict`` 也在 ``target_dict`` . | |||
除此以外,在参数被传入self.evaluate以前,这个函数会检测 ``pred_dict`` 和 ``target_dict`` 当中没有被用到的参数 | |||
如果kwargs是self.evaluate的参数,则不会检测 | |||
self.evaluate将计算一个批次(batch)的评价指标,并累计。 没有返回值 | |||
self.get_metric将统计当前的评价指标并返回评价结果, 返回值需要是一个dict, key是指标名称,value是指标的值 | |||
@@ -0,0 +1,67 @@ | |||
=================================================== | |||
使用Callback自定义你的训练过程 | |||
=================================================== | |||
在训练时,我们常常要使用trick来提高模型的性能(如调节学习率),或者要打印训练中的信息。 | |||
这里我们提供Callback类,在Trainer中插入代码,完成一些自定义的操作。 | |||
我们使用和 :doc:`/user/quickstart` 中一样的任务来进行详细的介绍。 | |||
给出一段评价性文字,预测其情感倾向是积极(label=1)、消极(label=0)还是中性(label=2),使用 :class:`~fastNLP.Trainer` 和 :class:`~fastNLP.Tester` 来进行快速训练和测试。 | |||
关于数据处理,Loss和Optimizer的选择可以看其他教程,这里仅在训练时加入学习率衰减。 | |||
--------------------- | |||
Callback的构建和使用 | |||
--------------------- | |||
创建Callback | |||
我们可以继承fastNLP :class:`~fastNLP.Callback` 类来定义自己的Callback。 | |||
这里我们实现一个让学习率线性衰减的Callback。 | |||
.. code-block:: python | |||
import fastNLP | |||
class LRDecay(fastNLP.Callback): | |||
def __init__(self): | |||
super(MyCallback, self).__init__() | |||
self.base_lrs = [] | |||
self.delta = [] | |||
def on_train_begin(self): | |||
# 初始化,仅训练开始时调用 | |||
self.base_lrs = [pg['lr'] for pg in self.optimizer.param_groups] | |||
self.delta = [float(lr) / self.n_epochs for lr in self.base_lrs] | |||
def on_epoch_end(self): | |||
# 每个epoch结束时,更新学习率 | |||
ep = self.epoch | |||
lrs = [lr - d * ep for lr, d in zip(self.base_lrs, self.delta)] | |||
self.change_lr(lrs) | |||
def change_lr(self, lrs): | |||
for pg, lr in zip(self.optimizer.param_groups, lrs): | |||
pg['lr'] = lr | |||
这里,:class:`~fastNLP.Callback` 中所有以 ``on_`` 开头的类方法会在 :class:`~fastNLP.Trainer` 的训练中在特定时间调用。 | |||
如 on_train_begin() 会在训练开始时被调用,on_epoch_end() 会在每个 epoch 结束时调用。 | |||
具体有哪些类方法,参见文档 :class:`~fastNLP.Callback` 。 | |||
另外,为了使用方便,可以在 :class:`~fastNLP.Callback` 内部访问 :class:`~fastNLP.Trainer` 中的属性,如 optimizer, epoch, step,分别对应训练时的优化器,当前epoch数,和当前的总step数。 | |||
具体可访问的属性,参见文档 :class:`~fastNLP.Callback` 。 | |||
使用Callback | |||
在定义好 :class:`~fastNLP.Callback` 之后,就能将它传入Trainer的 ``callbacks`` 参数,在实际训练时使用。 | |||
.. code-block:: python | |||
""" | |||
数据预处理,模型定义等等 | |||
""" | |||
trainer = fastNLP.Trainer( | |||
model=model, train_data=train_data, dev_data=dev_data, | |||
optimizer=optimizer, metrics=metrics, | |||
batch_size=10, n_epochs=100, | |||
callbacks=[LRDecay()]) | |||
trainer.train() |
@@ -0,0 +1,3 @@ | |||
=============== | |||
在代码中写文档 | |||
=============== |
@@ -20,7 +20,13 @@ | |||
小标题4 | |||
------------------- | |||
参考 http://docutils.sourceforge.net/docs/user/rst/quickref.html | |||
推荐使用大标题、小标题3和小标题4 | |||
官方文档 http://docutils.sourceforge.net/docs/user/rst/quickref.html | |||
`熟悉markdown的同学推荐参考这篇文章 <https://macplay.github.io/posts/cong-markdown-dao-restructuredtext/#id30>`_ | |||
\<\>内表示的是链接地址,\<\>外的是显示到外面的文字 | |||
常见语法 | |||
============ | |||
@@ -75,6 +81,7 @@ http://docutils.sf.net/ 孤立的网址会自动生成链接 | |||
不显示冒号的代码块 | |||
.. code-block:: python | |||
:linenos: | |||
:emphasize-lines: 1,3 | |||
@@ -83,22 +90,67 @@ http://docutils.sf.net/ 孤立的网址会自动生成链接 | |||
print("有行号和高亮") | |||
数学块 | |||
========== | |||
.. math:: | |||
H_2O + Na = NaOH + H_2 \uparrow | |||
复杂表格 | |||
========== | |||
+------------------------+------------+----------+----------+ | |||
| Header row, column 1 | Header 2 | Header 3 | Header 4 | | |||
| (header rows optional) | | | | | |||
+========================+============+==========+==========+ | |||
| body row 1, column 1 | column 2 | column 3 | column 4 | | |||
+------------------------+------------+----------+----------+ | |||
| body row 2 | Cells may span columns. | | |||
+------------------------+------------+---------------------+ | |||
| body row 3 | Cells may | - Table cells | | |||
+------------------------+ span rows. | - contain | | |||
| body row 4 | | - body elements. | | |||
+------------------------+------------+---------------------+ | |||
简易表格 | |||
========== | |||
===== ===== ====== | |||
Inputs Output | |||
------------ ------ | |||
A B A or B | |||
===== ===== ====== | |||
False False False | |||
True True True | |||
===== ===== ====== | |||
csv 表格 | |||
============ | |||
.. csv-table:: | |||
:header: sentence, target | |||
This is the first instance ., 0 | |||
Second instance ., 1 | |||
Third instance ., 1 | |||
..., ... | |||
[重要]各种链接 | |||
=================== | |||
各种链接帮助我们连接到fastNLP文档的各个位置 | |||
各种连接 | |||
=========== | |||
\<\>内表示的是链接地址,\<\>外的是显示到外面的文字 | |||
:doc:`/user/with_fitlog` | |||
:doc:`根据文件名链接 </user/quickstart>` | |||
:mod:`~fastNLP.core.batch` | |||
:class:`~fastNLP.Batch` | |||
~表示指显示最后一项 | |||
~表示只显示最后一项 | |||
:meth:`fastNLP.DataSet.apply` | |||
@@ -7,10 +7,12 @@ | |||
fastNLP 依赖如下包:: | |||
torch>=0.4.0 | |||
numpy | |||
tqdm | |||
nltk | |||
numpy>=1.14.2 | |||
torch>=1.0.0 | |||
tqdm>=4.28.1 | |||
nltk>=3.4.1 | |||
requests | |||
spacy | |||
其中torch的安装可能与操作系统及 CUDA 的版本相关,请参见 `PyTorch 官网 <https://pytorch.org/get-started/locally/>`_ 。 | |||
在依赖包安装完成的情况,您可以在命令行执行如下指令完成安装 | |||
@@ -18,3 +20,4 @@ fastNLP 依赖如下包:: | |||
.. code:: shell | |||
>>> pip install fastNLP | |||
>>> python -m spacy download en |
@@ -121,4 +121,4 @@ | |||
In Epoch:6/Step:12, got best dev performance:AccuracyMetric: acc=0.8 | |||
Reloaded the best model. | |||
这份教程只是简单地介绍了使用 fastNLP 工作的流程,具体的细节分析见 :doc:`/user/tutorial_one` | |||
这份教程只是简单地介绍了使用 fastNLP 工作的流程,更多的教程分析见 :doc:`/user/tutorials` |
@@ -1,371 +0,0 @@ | |||
=============== | |||
详细指南 | |||
=============== | |||
我们使用和 :doc:`/user/quickstart` 中一样的任务来进行详细的介绍。给出一段文字,预测它的标签是0~4中的哪一个 | |||
(数据来源 `kaggle <https://www.kaggle.com/c/sentiment-analysis-on-movie-reviews>`_ )。 | |||
-------------- | |||
数据处理 | |||
-------------- | |||
数据读入 | |||
我们可以使用 fastNLP :mod:`fastNLP.io` 模块中的 :class:`~fastNLP.io.CSVLoader` 类,轻松地从 csv 文件读取我们的数据。 | |||
这里的 dataset 是 fastNLP 中 :class:`~fastNLP.DataSet` 类的对象 | |||
.. code-block:: python | |||
from fastNLP.io import CSVLoader | |||
loader = CSVLoader(headers=('raw_sentence', 'label'), sep='\t') | |||
dataset = loader.load("./sample_data/tutorial_sample_dataset.csv") | |||
除了读取数据外,fastNLP 还提供了读取其它文件类型的 Loader 类、读取 Embedding的 Loader 等。详见 :doc:`/fastNLP.io` 。 | |||
Instance 和 DataSet | |||
fastNLP 中的 :class:`~fastNLP.DataSet` 类对象类似于二维表格,它的每一列是一个 :mod:`~fastNLP.core.field` | |||
每一行是一个 :mod:`~fastNLP.core.instance` 。我们可以手动向数据集中添加 :class:`~fastNLP.Instance` 类的对象 | |||
.. code-block:: python | |||
from fastNLP import Instance | |||
dataset.append(Instance(raw_sentence='fake data', label='0')) | |||
此时的 ``dataset[-1]`` 的值如下,可以看到,数据集中的每个数据包含 ``raw_sentence`` 和 ``label`` 两个 | |||
:mod:`~fastNLP.core.field` ,他们的类型都是 ``str`` :: | |||
{'raw_sentence': fake data type=str, 'label': 0 type=str} | |||
field 的修改 | |||
我们使用 :class:`~fastNLP.DataSet` 类的 :meth:`~fastNLP.DataSet.apply` 方法将 ``raw_sentence`` 中字母变成小写,并将句子分词。 | |||
同时也将 ``label`` :mod:`~fastNLP.core.field` 转化为整数并改名为 ``target`` | |||
.. code-block:: python | |||
dataset.apply(lambda x: x['raw_sentence'].lower(), new_field_name='sentence') | |||
dataset.apply_field(lambda x: x.split(), field_name='sentence', new_field_name='words') | |||
dataset.apply(lambda x: int(x['label']), new_field_name='target') | |||
``words`` 和 ``target`` 已经足够用于 :class:`~fastNLP.models.CNNText` 的训练了,但我们从其文档 | |||
:class:`~fastNLP.models.CNNText` 中看到,在 :meth:`~fastNLP.models.CNNText.forward` 的时候,还可以传入可选参数 ``seq_len`` 。 | |||
所以,我们再使用 :meth:`~fastNLP.DataSet.apply_field` 方法增加一个名为 ``seq_len`` 的 :mod:`~fastNLP.core.field` 。 | |||
.. code-block:: python | |||
dataset.apply_field(lambda x: len(x), field_name='words', new_field_name='seq_len') | |||
观察可知: :meth:`~fastNLP.DataSet.apply_field` 与 :meth:`~fastNLP.DataSet.apply` 类似, | |||
但所传入的 `lambda` 函数是针对一个 :class:`~fastNLP.Instance` 中的一个 :mod:`~fastNLP.core.field` 的; | |||
而 :meth:`~fastNLP.DataSet.apply` 所传入的 `lambda` 函数是针对整个 :class:`~fastNLP.Instance` 的。 | |||
.. note:: | |||
`lambda` 函数即匿名函数,是 Python 的重要特性。 ``lambda x: len(x)`` 和下面的这个函数的作用相同:: | |||
def func_lambda(x): | |||
return len(x) | |||
你也可以编写复杂的函数做为 :meth:`~fastNLP.DataSet.apply_field` 与 :meth:`~fastNLP.DataSet.apply` 的参数 | |||
Vocabulary 的使用 | |||
我们再用 :class:`~fastNLP.Vocabulary` 类来统计数据中出现的单词,并使用 :meth:`~fastNLP.Vocabularyindex_dataset` | |||
将单词序列转化为训练可用的数字序列。 | |||
.. code-block:: python | |||
from fastNLP import Vocabulary | |||
vocab = Vocabulary(min_freq=2).from_dataset(dataset, field_name='words') | |||
vocab.index_dataset(dataset, field_name='words',new_field_name='words') | |||
数据集分割 | |||
除了修改 :mod:`~fastNLP.core.field` 之外,我们还可以对 :class:`~fastNLP.DataSet` 进行分割,以供训练、开发和测试使用。 | |||
下面这段代码展示了 :meth:`~fastNLP.DataSet.split` 的使用方法(但实际应该放在后面两段改名和设置输入的代码之后) | |||
.. code-block:: python | |||
train_dev_data, test_data = dataset.split(0.1) | |||
train_data, dev_data = train_dev_data.split(0.1) | |||
len(train_data), len(dev_data), len(test_data) | |||
--------------------- | |||
使用内置模型训练 | |||
--------------------- | |||
内置模型的输入输出命名 | |||
fastNLP内置了一些完整的神经网络模型,详见 :doc:`/fastNLP.models` , 我们使用其中的 :class:`~fastNLP.models.CNNText` 模型进行训练。 | |||
为了使用内置的 :class:`~fastNLP.models.CNNText`,我们必须修改 :class:`~fastNLP.DataSet` 中 :mod:`~fastNLP.core.field` 的名称。 | |||
在这个例子中模型输入 (forward方法的参数) 为 ``words`` 和 ``seq_len`` ; 预测输出为 ``pred`` ;标准答案为 ``target`` 。 | |||
具体的命名规范可以参考 :doc:`/fastNLP.core.const` 。 | |||
如果不想查看文档,您也可以使用 :class:`~fastNLP.Const` 类进行命名。下面的代码展示了给 :class:`~fastNLP.DataSet` 中 | |||
:mod:`~fastNLP.core.field` 改名的 :meth:`~fastNLP.DataSet.rename_field` 方法,以及 :class:`~fastNLP.Const` 类的使用方法。 | |||
.. code-block:: python | |||
from fastNLP import Const | |||
dataset.rename_field('words', Const.INPUT) | |||
dataset.rename_field('seq_len', Const.INPUT_LEN) | |||
dataset.rename_field('target', Const.TARGET) | |||
在给 :class:`~fastNLP.DataSet` 中 :mod:`~fastNLP.core.field` 改名后,我们还需要设置训练所需的输入和目标,这里使用的是 | |||
:meth:`~fastNLP.DataSet.set_input` 和 :meth:`~fastNLP.DataSet.set_target` 两个函数。 | |||
.. code-block:: python | |||
dataset.set_input(Const.INPUT, Const.INPUT_LEN) | |||
dataset.set_target(Const.TARGET) | |||
快速训练 | |||
现在我们可以导入 fastNLP 内置的文本分类模型 :class:`~fastNLP.models.CNNText` ,并使用 :class:`~fastNLP.Trainer` 进行训练了 | |||
(其中 ``loss`` 和 ``metrics`` 的定义,我们将在后续两段代码中给出)。 | |||
.. code-block:: python | |||
from fastNLP.models import CNNText | |||
from fastNLP import Trainer | |||
model = CNNText((len(vocab),50), num_classes=5, padding=2, dropout=0.1) | |||
trainer = Trainer(model=model_cnn, train_data=train_data, dev_data=dev_data, | |||
loss=loss, metrics=metrics) | |||
trainer.train() | |||
训练过程的输出如下:: | |||
input fields after batch(if batch size is 2): | |||
words: (1)type:torch.Tensor (2)dtype:torch.int64, (3)shape:torch.Size([2, 26]) | |||
target fields after batch(if batch size is 2): | |||
target: (1)type:torch.Tensor (2)dtype:torch.int64, (3)shape:torch.Size([2]) | |||
training epochs started 2019-05-09-10-59-39 | |||
Evaluation at Epoch 1/10. Step:2/20. AccuracyMetric: acc=0.333333 | |||
Evaluation at Epoch 2/10. Step:4/20. AccuracyMetric: acc=0.533333 | |||
Evaluation at Epoch 3/10. Step:6/20. AccuracyMetric: acc=0.533333 | |||
Evaluation at Epoch 4/10. Step:8/20. AccuracyMetric: acc=0.533333 | |||
Evaluation at Epoch 5/10. Step:10/20. AccuracyMetric: acc=0.6 | |||
Evaluation at Epoch 6/10. Step:12/20. AccuracyMetric: acc=0.8 | |||
Evaluation at Epoch 7/10. Step:14/20. AccuracyMetric: acc=0.8 | |||
Evaluation at Epoch 8/10. Step:16/20. AccuracyMetric: acc=0.733333 | |||
Evaluation at Epoch 9/10. Step:18/20. AccuracyMetric: acc=0.733333 | |||
Evaluation at Epoch 10/10. Step:20/20. AccuracyMetric: acc=0.733333 | |||
In Epoch:6/Step:12, got best dev performance:AccuracyMetric: acc=0.8 | |||
Reloaded the best model. | |||
损失函数 | |||
训练模型需要提供一个损失函数, 下面提供了一个在分类问题中常用的交叉熵损失。注意它的 **初始化参数** 。 | |||
``pred`` 参数对应的是模型的 forward 方法返回的 dict 中的一个 key 的名字。 | |||
``target`` 参数对应的是 :class:`~fastNLP.DataSet` 中作为标签的 :mod:`~fastNLP.core.field` 的名字。 | |||
这里我们用 :class:`~fastNLP.Const` 来辅助命名,如果你自己编写模型中 forward 方法的返回值或 | |||
数据集中 :mod:`~fastNLP.core.field` 的名字与本例不同, 你可以把 ``pred`` 参数和 ``target`` 参数设定符合自己代码的值。 | |||
.. code-block:: python | |||
from fastNLP import CrossEntropyLoss | |||
# loss = CrossEntropyLoss() 在本例中与下面这行代码等价 | |||
loss = CrossEntropyLoss(pred=Const.OUTPUT, target=Const.TARGET) | |||
评价指标 | |||
训练模型需要提供一个评价指标。这里使用准确率做为评价指标。参数的 `命名规则` 跟上面类似。 | |||
``pred`` 参数对应的是模型的 forward 方法返回的 dict 中的一个 key 的名字。 | |||
``target`` 参数对应的是 :class:`~fastNLP.DataSet` 中作为标签的 :mod:`~fastNLP.core.field` 的名字。 | |||
.. code-block:: python | |||
from fastNLP import AccuracyMetric | |||
# metrics=AccuracyMetric() 在本例中与下面这行代码等价 | |||
metrics=AccuracyMetric(pred=Const.OUTPUT, target=Const.TARGET) | |||
快速测试 | |||
与 :class:`~fastNLP.Trainer` 对应,fastNLP 也提供了 :class:`~fastNLP.Tester` 用于快速测试,用法如下 | |||
.. code-block:: python | |||
from fastNLP import Tester | |||
tester = Tester(test_data, model_cnn, metrics=AccuracyMetric()) | |||
tester.test() | |||
--------------------- | |||
编写自己的模型 | |||
--------------------- | |||
因为 fastNLP 是基于 `PyTorch <https://pytorch.org/>`_ 开发的框架,所以我们可以基于 PyTorch 模型编写自己的神经网络模型。 | |||
与标准的 PyTorch 模型不同,fastNLP 模型中 forward 方法返回的是一个字典,字典中至少需要包含 "pred" 这个字段。 | |||
而 forward 方法的参数名称必须与 :class:`~fastNLP.DataSet` 中用 :meth:`~fastNLP.DataSet.set_input` 设定的名称一致。 | |||
模型定义的代码如下: | |||
.. code-block:: python | |||
import torch | |||
import torch.nn as nn | |||
class LSTMText(nn.Module): | |||
def __init__(self, vocab_size, embedding_dim, output_dim, hidden_dim=64, num_layers=2, dropout=0.5): | |||
super().__init__() | |||
self.embedding = nn.Embedding(vocab_size, embedding_dim) | |||
self.lstm = nn.LSTM(embedding_dim, hidden_dim, num_layers=num_layers, bidirectional=True, dropout=dropout) | |||
self.fc = nn.Linear(hidden_dim * 2, output_dim) | |||
self.dropout = nn.Dropout(dropout) | |||
def forward(self, words): | |||
# (input) words : (batch_size, seq_len) | |||
words = words.permute(1,0) | |||
# words : (seq_len, batch_size) | |||
embedded = self.dropout(self.embedding(words)) | |||
# embedded : (seq_len, batch_size, embedding_dim) | |||
output, (hidden, cell) = self.lstm(embedded) | |||
# output: (seq_len, batch_size, hidden_dim * 2) | |||
# hidden: (num_layers * 2, batch_size, hidden_dim) | |||
# cell: (num_layers * 2, batch_size, hidden_dim) | |||
hidden = torch.cat((hidden[-2, :, :], hidden[-1, :, :]), dim=1) | |||
hidden = self.dropout(hidden) | |||
# hidden: (batch_size, hidden_dim * 2) | |||
pred = self.fc(hidden.squeeze(0)) | |||
# result: (batch_size, output_dim) | |||
return {"pred":pred} | |||
模型的使用方法与内置模型 :class:`~fastNLP.models.CNNText` 一致 | |||
.. code-block:: python | |||
model_lstm = LSTMText(len(vocab),50,5) | |||
trainer = Trainer(model=model_lstm, train_data=train_data, dev_data=dev_data, | |||
loss=loss, metrics=metrics) | |||
trainer.train() | |||
tester = Tester(test_data, model_lstm, metrics=AccuracyMetric()) | |||
tester.test() | |||
.. todo:: | |||
使用 :doc:`/fastNLP.modules` 编写模型 | |||
-------------------------- | |||
自己编写训练过程 | |||
-------------------------- | |||
如果你想用类似 PyTorch 的使用方法,自己编写训练过程,你可以参考下面这段代码。其中使用了 fastNLP 提供的 :class:`~fastNLP.Batch` | |||
来获得小批量训练的小批量数据,使用 :class:`~fastNLP.BucketSampler` 做为 :class:`~fastNLP.Batch` 的参数来选择采样的方式。 | |||
这段代码中使用了 PyTorch 的 `torch.optim.Adam` 优化器 和 `torch.nn.CrossEntropyLoss` 损失函数,并自己计算了正确率 | |||
.. code-block:: python | |||
from fastNLP import BucketSampler | |||
from fastNLP import Batch | |||
import torch | |||
import time | |||
model = CNNText((len(vocab),50), num_classes=5, padding=2, dropout=0.1) | |||
def train(epoch, data): | |||
optim = torch.optim.Adam(model.parameters(), lr=0.001) | |||
lossfunc = torch.nn.CrossEntropyLoss() | |||
batch_size = 32 | |||
train_sampler = BucketSampler(batch_size=batch_size, seq_len_field_name='seq_len') | |||
train_batch = Batch(batch_size=batch_size, dataset=data, sampler=train_sampler) | |||
start_time = time.time() | |||
for i in range(epoch): | |||
loss_list = [] | |||
for batch_x, batch_y in train_batch: | |||
optim.zero_grad() | |||
output = model(batch_x['words']) | |||
loss = lossfunc(output['pred'], batch_y['target']) | |||
loss.backward() | |||
optim.step() | |||
loss_list.append(loss.item()) | |||
print('Epoch {:d} Avg Loss: {:.2f}'.format(i, sum(loss_list) / len(loss_list)),end=" ") | |||
print('{:d}ms'.format(round((time.time()-start_time)*1000))) | |||
loss_list.clear() | |||
train(10, train_data) | |||
tester = Tester(test_data, model, metrics=AccuracyMetric()) | |||
tester.test() | |||
这段代码的输出如下:: | |||
Epoch 0 Avg Loss: 2.76 17ms | |||
Epoch 1 Avg Loss: 2.55 29ms | |||
Epoch 2 Avg Loss: 2.37 41ms | |||
Epoch 3 Avg Loss: 2.30 53ms | |||
Epoch 4 Avg Loss: 2.12 65ms | |||
Epoch 5 Avg Loss: 2.16 76ms | |||
Epoch 6 Avg Loss: 1.88 88ms | |||
Epoch 7 Avg Loss: 1.84 99ms | |||
Epoch 8 Avg Loss: 1.71 111ms | |||
Epoch 9 Avg Loss: 1.62 122ms | |||
[tester] | |||
AccuracyMetric: acc=0.142857 | |||
---------------------------------- | |||
使用 Callback 增强 Trainer | |||
---------------------------------- | |||
如果你不想自己实现繁琐的训练过程,只希望在训练过程中实现一些自己的功能(比如:输出从训练开始到当前 batch 结束的总时间), | |||
你可以使用 fastNLP 提供的 :class:`~fastNLP.Callback` 类。下面的例子中,我们继承 :class:`~fastNLP.Callback` 类实现了这个功能。 | |||
.. code-block:: python | |||
from fastNLP import Callback | |||
start_time = time.time() | |||
class MyCallback(Callback): | |||
def on_epoch_end(self): | |||
print('Sum Time: {:d}ms\n\n'.format(round((time.time()-start_time)*1000))) | |||
model = CNNText((len(vocab),50), num_classes=5, padding=2, dropout=0.1) | |||
trainer = Trainer(model=model, train_data=train_data, dev_data=dev_data, | |||
loss=CrossEntropyLoss(), metrics=AccuracyMetric(), callbacks=[MyCallback()]) | |||
trainer.train() | |||
训练输出如下:: | |||
input fields after batch(if batch size is 2): | |||
words: (1)type:torch.Tensor (2)dtype:torch.int64, (3)shape:torch.Size([2, 16]) | |||
seq_len: (1)type:torch.Tensor (2)dtype:torch.int64, (3)shape:torch.Size([2]) | |||
target fields after batch(if batch size is 2): | |||
target: (1)type:torch.Tensor (2)dtype:torch.int64, (3)shape:torch.Size([2]) | |||
training epochs started 2019-05-12-21-38-40 | |||
Evaluation at Epoch 1/10. Step:2/20. AccuracyMetric: acc=0.285714 | |||
Sum Time: 51ms | |||
………………………… | |||
Evaluation at Epoch 10/10. Step:20/20. AccuracyMetric: acc=0.857143 | |||
Sum Time: 212ms | |||
In Epoch:10/Step:20, got best dev performance:AccuracyMetric: acc=0.857143 | |||
Reloaded the best model. | |||
这个例子只是介绍了 :class:`~fastNLP.Callback` 类的使用方法。实际应用(比如:负采样、Learning Rate Decay、Early Stop 等)中 | |||
很多功能已经被 fastNLP 实现了。你可以直接 import 它们使用,详细请查看文档 :doc:`/fastNLP.core.callback` 。 |
@@ -0,0 +1,20 @@ | |||
======================== | |||
fastNLP 详细使用教程 | |||
======================== | |||
这里是更详细的使用教程。对于大部分的用户,我们建议你从第一篇开始顺序阅读;如果你只想了解其中的一部分,也可以进行选读。 | |||
.. toctree:: | |||
:maxdepth: 1 | |||
使用DataSet预处理文本 </tutorials/tutorial_1_data_preprocess> | |||
使用DataSetLoader加载数据集 </tutorials/tutorial_2_load_dataset> | |||
使用Embedding模块将文本转成向量 </tutorials/tutorial_3_embedding> | |||
动手实现一个文本分类器I-使用Trainer和Tester快速训练和测试 </tutorials/tutorial_4_loss_optimizer> | |||
动手实现一个文本分类器II-使用DataSetIter实现自定义训练过程 </tutorials/tutorial_5_datasetiter> | |||
快速实现序列标注模型 </tutorials/tutorial_6_seq_labeling> | |||
使用Modules和Models快速搭建自定义模型 </tutorials/tutorial_7_modules_models> | |||
使用Metric快速评测你的模型 </tutorials/tutorial_8_metrics> | |||
使用Callback自定义你的训练过程 </tutorials/tutorial_9_callback> | |||
使用fitlog 辅助 fastNLP 进行科研 </tutorials/tutorial_10_fitlog> | |||
@@ -1,11 +1,12 @@ | |||
""" | |||
fastNLP 由 :mod:`~fastNLP.core` 、 :mod:`~fastNLP.io` 、:mod:`~fastNLP.modules`、:mod:`~fastNLP.models` | |||
等子模块组成,你可以点进去查看每个模块的文档。 | |||
fastNLP 由 :mod:`~fastNLP.core` 、 :mod:`~fastNLP.io` 、:mod:`~fastNLP.embeddings` 、 :mod:`~fastNLP.modules`、 | |||
:mod:`~fastNLP.models` 等子模块组成,你可以查看每个模块的文档。 | |||
- :mod:`~fastNLP.core` 是fastNLP 的核心模块,包括 DataSet、 Trainer、 Tester 等组件。详见文档 :doc:`/fastNLP.core` | |||
- :mod:`~fastNLP.io` 是实现输入输出的模块,包括了数据集的读取,模型的存取等功能。详见文档 :doc:`/fastNLP.io` | |||
- :mod:`~fastNLP.embeddings` 提供用于构建复杂网络模型所需的各种embedding。详见文档 :doc:`/fastNLP.embeddings` | |||
- :mod:`~fastNLP.modules` 包含了用于搭建神经网络模型的诸多组件,可以帮助用户快速搭建自己所需的网络。详见文档 :doc:`/fastNLP.modules` | |||
- :mod:`~fastNLP.models` 包含了一些使用 fastNLP 实现的完整网络模型,包括CNNText、SeqLabeling等常见模型。详见文档 :doc:`/fastNLP.models` | |||
- :mod:`~fastNLP.models` 包含了一些使用 fastNLP 实现的完整网络模型,包括 :class:`~fastNLP.models.CNNText` 、 :class:`~fastNLP.models.SeqLabeling` 等常见模型。详见文档 :doc:`fastNLP.models` | |||
fastNLP 中最常用的组件可以直接从 fastNLP 包中 import ,他们的文档如下: | |||
""" | |||
@@ -56,9 +57,10 @@ __all__ = [ | |||
"cache_results" | |||
] | |||
__version__ = '0.4.0' | |||
__version__ = '0.4.5' | |||
from .core import * | |||
from . import models | |||
from . import modules | |||
from . import embeddings | |||
from .io import data_loader |
@@ -1,17 +1,15 @@ | |||
""" | |||
core 模块里实现了 fastNLP 的核心框架,常用的功能都可以从 fastNLP 包中直接 import。当然你也同样可以从 core 模块的子模块中 import, | |||
例如 Batch 组件有两种 import 的方式:: | |||
例如 :class:`~fastNLP.DataSetIter` 组件有两种 import 的方式:: | |||
# 直接从 fastNLP 中 import | |||
from fastNLP import Batch | |||
from fastNLP import DataSetIter | |||
# 从 core 模块的子模块 batch 中 import | |||
from fastNLP.core.batch import Batch | |||
# 从 core 模块的子模块 batch 中 import DataSetIter | |||
from fastNLP.core.batch import DataSetIter | |||
对于常用的功能,你只需要在 :doc:`fastNLP` 中查看即可。如果想了解各个子模块的具体作用,您可以在下面找到每个子模块的具体文档。 | |||
.. todo:: | |||
介绍core 的子模块的分工,好像必要性不大 | |||
""" | |||
from .batch import DataSetIter, BatchIter, TorchLoaderIter | |||
@@ -1,6 +1,7 @@ | |||
import threading | |||
import torch | |||
from torch import nn | |||
from torch.nn.parallel.parallel_apply import get_a_var | |||
from torch.nn.parallel.scatter_gather import scatter_kwargs, gather | |||
@@ -86,3 +87,16 @@ def _data_parallel_wrapper(func_name, device_ids, output_device): | |||
outputs = parallel_apply(replicas, func_name, inputs, kwargs, device_ids[:len(replicas)]) | |||
return gather(outputs, output_device) | |||
return wrapper | |||
def _model_contains_inner_module(model): | |||
""" | |||
:param nn.Module model: 模型文件,判断是否内部包含model.module, 多用于check模型是否是nn.DataParallel, | |||
nn.parallel.DistributedDataParallel。主要是在做形参匹配的时候需要使用最内部的model的function。 | |||
:return: bool | |||
""" | |||
if isinstance(model, nn.Module): | |||
if isinstance(model, (nn.DataParallel, nn.parallel.DistributedDataParallel)): | |||
return True | |||
return False |
@@ -1,18 +1,17 @@ | |||
""" | |||
batch 模块实现了 fastNLP 所需的 Batch 类。 | |||
batch 模块实现了 fastNLP 所需的 :class:`~fastNLP.core.batch.DataSetIter` 类。 | |||
""" | |||
__all__ = [ | |||
"BatchIter", | |||
"DataSetIter", | |||
"TorchLoaderIter", | |||
] | |||
import atexit | |||
from queue import Empty, Full | |||
import numpy as np | |||
import torch | |||
import torch.multiprocessing as mp | |||
import torch.utils.data | |||
from numbers import Number | |||
@@ -94,9 +93,13 @@ class DataSetGetter: | |||
class SamplerAdapter(torch.utils.data.Sampler): | |||
def __init__(self, sampler, dataset): | |||
super().__init__(dataset) | |||
self.sampler = sampler | |||
self.dataset = dataset | |||
def __len__(self): | |||
return len(self.dataset) | |||
def __iter__(self): | |||
return iter(self.sampler(self.dataset)) | |||
@@ -166,15 +169,19 @@ class DataSetIter(BatchIter): | |||
timeout=0, worker_init_fn=None): | |||
super().__init__() | |||
assert isinstance(dataset, DataSet) | |||
sampler = SamplerAdapter(sampler=sampler or SequentialSampler(), dataset=dataset) | |||
if not isinstance(sampler, torch.utils.data.Sampler): | |||
self.sampler = SamplerAdapter(sampler=sampler or SequentialSampler(), dataset=dataset) | |||
else: | |||
self.sampler = sampler | |||
dataset = DataSetGetter(dataset, as_numpy) | |||
collate_fn = dataset.collate_fn if hasattr(dataset, 'collate_fn') else None | |||
self.dataiter = torch.utils.data.DataLoader( | |||
dataset=dataset, batch_size=batch_size, sampler=sampler, | |||
dataset=dataset, batch_size=batch_size, sampler=self.sampler, | |||
collate_fn=collate_fn, num_workers=num_workers, | |||
pin_memory=pin_memory, drop_last=drop_last, | |||
timeout=timeout, worker_init_fn=worker_init_fn) | |||
self.num_batches = self.get_num_batches(len(dataset), batch_size, drop_last) | |||
# 以sampler的数量为准,因为DistributedSampler的时候每个进程上并不是所有的数据都用上了 | |||
self.num_batches = self.get_num_batches(len(self.dataiter.sampler), batch_size, drop_last) | |||
self.batch_size = batch_size | |||
@@ -183,7 +190,7 @@ class TorchLoaderIter(BatchIter): | |||
super().__init__() | |||
assert isinstance(dataset, torch.utils.data.DataLoader) | |||
self.dataiter = dataset | |||
self.num_batches = self.get_num_batches(len(dataset), dataset.batch_size, dataset.drop_last) | |||
self.num_batches = self.get_num_batches(len(dataset.sampler), dataset.batch_size, dataset.drop_last) | |||
self.batch_size = dataset.batch_size | |||
@@ -2,11 +2,11 @@ r""" | |||
callback模块实现了 fastNLP 中的许多 callback 类,用于增强 :class:`~fastNLP.Trainer` 类。 | |||
虽然Trainer本身已经集成了一些功能,但仍然不足以囊括训练过程中可能需要到的功能, | |||
比如负采样,learning rate decay, Early Stop等。 | |||
为了解决这个问题fastNLP引入了callback的机制,Callback 是一种在Trainer训练过程中特定阶段会运行的函数集合。 | |||
关于Trainer的详细文档,请参见 :doc:`trainer 模块<fastNLP.core.trainer>` | |||
比如负采样,learning rate decay 和 early stop等。 | |||
为了解决这个问题,fastNLP引入了callback的机制,:class:`~fastNLP.Callback` 是一种在Trainer训练过程中特定阶段会运行的函数集合。 | |||
关于 :class:`~fastNLP.Trainer` 的详细文档,请参见 :doc:`trainer 模块<fastNLP.core.trainer>` | |||
我们将 :meth:`~fastNLP.Train.train` 这个函数内部分为以下的阶段,在对应阶段会触发相应的调用:: | |||
我们将 :meth:`~fastNLP.Trainer.train` 这个函数内部分为以下的阶段,在对应阶段会触发相应的调用:: | |||
callback.on_train_begin() # 开始进行训练 | |||
for i in range(1, n_epochs+1): | |||
@@ -31,8 +31,8 @@ callback模块实现了 fastNLP 中的许多 callback 类,用于增强 :class: | |||
callback.on_train_end() # 训练结束 | |||
callback.on_exception() # 这是一个特殊的步骤,在训练过程中遭遇exception会跳转到这里。 | |||
如下面的例子所示,我们可以使用内置的 callback 类,或者继承 :class:`~fastNLP.core.callback.Callback` | |||
定义自己的 callback 类:: | |||
如下面的例子所示,我们可以使用内置的 callback 组件,或者继承 :class:`~fastNLP.core.callback.Callback` | |||
定义自己的 callback 组件:: | |||
from fastNLP import Callback, EarlyStopCallback, Trainer, CrossEntropyLoss, AccuracyMetric | |||
from fastNLP.models import CNNText | |||
@@ -79,6 +79,7 @@ except: | |||
from ..io.model_io import ModelSaver, ModelLoader | |||
from .dataset import DataSet | |||
from .tester import Tester | |||
import logging | |||
try: | |||
import fitlog | |||
@@ -100,7 +101,8 @@ class Callback(object): | |||
def __init__(self): | |||
super(Callback, self).__init__() | |||
self._trainer = None # 在Trainer内部被重新赋值 | |||
self._disabled = False | |||
@property | |||
def trainer(self): | |||
""" | |||
@@ -158,7 +160,19 @@ class Callback(object): | |||
def batch_per_epoch(self): | |||
"""每个epoch一共有多少个batch,只有在on_epoch_begin之后才能调用该属性。""" | |||
return self._trainer.batch_per_epoch | |||
@property | |||
def is_master(self): | |||
return self._trainer.is_master() | |||
@property | |||
def disabled(self): | |||
return self._disabled | |||
@property | |||
def logger(self): | |||
return getattr(self._trainer, 'logger', logging) | |||
def on_train_begin(self): | |||
""" | |||
在Train过程开始之前调用。 | |||
@@ -250,6 +264,14 @@ class Callback(object): | |||
:return: | |||
""" | |||
pass | |||
def on_validation(self): | |||
""" | |||
如果Trainer中设置了验证,则会在每次需要验证时调用该函数 | |||
:return: | |||
""" | |||
pass | |||
def on_epoch_end(self): | |||
""" | |||
@@ -281,6 +303,8 @@ def _transfer(func): | |||
def wrapper(manager, *arg): | |||
returns = [] | |||
for callback in manager.callbacks: | |||
if callback.disabled: | |||
continue | |||
returns.append(getattr(callback, func.__name__)(*arg)) | |||
return returns | |||
@@ -297,22 +321,28 @@ class CallbackManager(Callback): | |||
""" | |||
super(CallbackManager, self).__init__() | |||
# set attribute of trainer environment | |||
self._env = env | |||
self.callbacks = [] | |||
if callbacks is not None: | |||
if isinstance(callbacks, list): | |||
if all([isinstance(cb, Callback) for cb in callbacks]) is True: | |||
self.callbacks.extend(callbacks) | |||
else: | |||
obj = [not isinstance(cb, Callback) for cb in callbacks][0] | |||
raise TypeError(f"Expect sub-classes of Callback. Got {type(obj)}") | |||
if callbacks: | |||
self.callbacks = self.prepare_callbacks(callbacks) | |||
def prepare_callbacks(self, callbacks): | |||
if not callbacks: | |||
return [] | |||
if isinstance(callbacks, list): | |||
if all([isinstance(cb, Callback) for cb in callbacks]) is True: | |||
pass | |||
else: | |||
raise TypeError(f"Expect callbacks in CallbackManager(callbacks) to be list. Got {type(callbacks)}.") | |||
for env_name, env_val in env.items(): | |||
for callback in self.callbacks: | |||
obj = [not isinstance(cb, Callback) for cb in callbacks][0] | |||
raise TypeError(f"Expect sub-classes of Callback. Got {type(obj)}") | |||
else: | |||
raise TypeError(f"Expect callbacks in CallbackManager(callbacks) to be list. Got {type(callbacks)}.") | |||
for env_name, env_val in self._env.items(): | |||
for callback in callbacks: | |||
setattr(callback, '_' + env_name, env_val) # Callback.trainer | |||
return callbacks | |||
@_transfer | |||
def on_train_begin(self): | |||
pass | |||
@@ -352,6 +382,10 @@ class CallbackManager(Callback): | |||
@_transfer | |||
def on_valid_end(self, eval_result, metric_key, optimizer, is_better_eval): | |||
pass | |||
@_transfer | |||
def on_validation(self): | |||
pass | |||
@_transfer | |||
def on_epoch_end(self): | |||
@@ -366,6 +400,25 @@ class CallbackManager(Callback): | |||
pass | |||
class DistCallbackManager(CallbackManager): | |||
def __init__(self, env, callbacks_all=None, callbacks_master=None): | |||
super(DistCallbackManager, self).__init__(env) | |||
assert 'trainer' in env | |||
is_master = env['trainer'].is_master | |||
self.patch_callback(callbacks_master, disabled=not is_master) | |||
self.callbacks_all = self.prepare_callbacks(callbacks_all) | |||
self.callbacks_master = self.prepare_callbacks(callbacks_master) | |||
self.callbacks = self.callbacks_all + self.callbacks_master | |||
def patch_callback(self, callbacks, disabled): | |||
if not callbacks: | |||
return | |||
if not isinstance(callbacks, (list, tuple)): | |||
callbacks = [callbacks] | |||
for cb in callbacks: | |||
cb._disabled = disabled | |||
class GradientClipCallback(Callback): | |||
""" | |||
别名::class:`fastNLP.GradientClipCallback` :class:`fastNLP.core.callback.GradientClipCallback` | |||
@@ -403,6 +456,9 @@ class GradientClipCallback(Callback): | |||
def on_backward_end(self): | |||
if self.step%self.update_every==0: | |||
if self.parameters is None: | |||
if getattr(self.trainer, 'fp16', ''): | |||
from apex import amp | |||
self.clip_fun(amp.master_params(self.optimizer), self.clip_value) | |||
self.clip_fun(self.model.parameters(), self.clip_value) | |||
else: | |||
self.clip_fun(self.parameters, self.clip_value) | |||
@@ -448,10 +504,10 @@ class FitlogCallback(Callback): | |||
并将验证结果写入到fitlog中。这些数据集的结果是根据dev上最好的结果报道的,即如果dev在第3个epoch取得了最佳,则 | |||
fitlog中记录的关于这些数据集的结果就是来自第三个epoch的结果。 | |||
:param DataSet,dict(DataSet) data: 传入DataSet对象,会使用多个Trainer中的metric对数据进行验证。如果需要传入多个 | |||
:param ~fastNLP.DataSet,Dict[~fastNLP.DataSet] data: 传入DataSet对象,会使用多个Trainer中的metric对数据进行验证。如果需要传入多个 | |||
DataSet请通过dict的方式传入,dict的key将作为对应dataset的name传递给fitlog。若tester不为None时,data需要通过 | |||
dict的方式传入。如果仅传入DataSet, 则被命名为test | |||
:param Tester tester: Tester对象,将在on_valid_end时调用。tester中的DataSet会被称为为`test` | |||
:param ~fastNLP.Tester tester: Tester对象,将在on_valid_end时调用。tester中的DataSet会被称为为`test` | |||
:param int log_loss_every: 多少个step记录一次loss(记录的是这几个batch的loss平均值),如果数据集较大建议将该值设置得 | |||
大一些,不然会导致log文件巨大。默认为0, 即不要记录loss。 | |||
:param int verbose: 是否在终端打印evaluation的结果,0不打印。 | |||
@@ -479,7 +535,7 @@ class FitlogCallback(Callback): | |||
self.datasets[key] = value | |||
elif isinstance(data, DataSet): | |||
self.datasets['test'] = data | |||
else: | |||
elif data is not None: | |||
raise TypeError("data receives dict[DataSet] or DataSet object.") | |||
self.verbose = verbose | |||
@@ -674,7 +730,7 @@ class TensorboardCallback(Callback): | |||
.. warning:: | |||
fastNLP 已停止对此功能的维护,请等待 fastNLP 兼容 PyTorch1.1 的下一个版本。 | |||
或者使用和 fastNLP 高度配合的 fitlog(参见 :doc:`/user/with_fitlog` )。 | |||
或者使用和 fastNLP 高度配合的 fitlog(参见 :doc:`/tutorials/tutorial_10_fitlog` )。 | |||
""" | |||
@@ -884,3 +940,59 @@ class EarlyStopError(CallbackException): | |||
def __init__(self, msg): | |||
super(EarlyStopError, self).__init__(msg) | |||
class EchoCallback(Callback): | |||
def __init__(self, name, out=sys.stdout): | |||
super(EchoCallback, self).__init__() | |||
self.name = name | |||
self.out = out | |||
def __getattribute__(self, item): | |||
if item.startswith('on_'): | |||
print('{}.{} has been called at pid: {}'.format(self.name, item, os.getpid()), | |||
file=self.out) | |||
return super(EchoCallback, self).__getattribute__(item) | |||
class TesterCallback(Callback): | |||
def __init__(self, data, model, metrics, metric_key=None, batch_size=16, num_workers=None): | |||
super(TesterCallback, self).__init__() | |||
self.tester = Tester(data, model, | |||
metrics=metrics, batch_size=batch_size, | |||
num_workers=num_workers, verbose=0) | |||
# parse metric_key | |||
# increase_better is True. It means the exp result gets better if the indicator increases. | |||
# It is true by default. | |||
self.increase_better = True | |||
if metric_key is not None: | |||
self.increase_better = False if metric_key[0] == "-" else True | |||
self.metric_key = metric_key[1:] if metric_key[0] == "+" or metric_key[0] == "-" else metric_key | |||
else: | |||
self.metric_key = None | |||
self.score = None | |||
def on_validation(self): | |||
cur_score = self.tester.test() | |||
eval_str = "Evaluation at Epoch {}/{}. Step:{}/{}. - {}".format( | |||
self.epoch, self.n_epochs, self.step, self.n_steps, | |||
self.tester._format_eval_results(cur_score)) | |||
self.logger.info(eval_str) | |||
is_better = self.compare_better(cur_score) | |||
if is_better: | |||
self.score = cur_score | |||
return cur_score, is_better | |||
def compare_better(self, a): | |||
if self.score is None: | |||
return True | |||
k = self.metric_key | |||
is_increase = self.score[k] <= a[k] # if equal, prefer more recent results | |||
if self.increase_better: | |||
return is_increase | |||
else: | |||
return not is_increase | |||
def on_train_end(self): | |||
self.logger.info('Evaluate on training ends.') | |||
self.on_validation() |
@@ -1,7 +1,7 @@ | |||
""" | |||
:class:`~fastNLP.core.dataset.DataSet` 是fastNLP中用于承载数据的容器。可以将DataSet看做是一个表格, | |||
每一行是一个sample (在fastNLP中被称为 :mod:`~.instance` ), | |||
每一列是一个feature (在fastNLP中称为 :mod:`.field` )。 | |||
每一行是一个sample (在fastNLP中被称为 :mod:`~fastNLP.core.instance` ), | |||
每一列是一个feature (在fastNLP中称为 :mod:`~fastNLP.core.field` )。 | |||
.. csv-table:: Following is a demo layout of DataSet | |||
:header: "sentence", "words", "seq_len" | |||
@@ -13,57 +13,64 @@ | |||
在fastNLP内部每一行是一个 :class:`~fastNLP.Instance` 对象; 每一列是一个 :class:`~fastNLP.FieldArray` 对象。 | |||
1 DataSet的创建 | |||
创建DataSet主要有以下的3种方式 | |||
---------------------------- | |||
1.DataSet的创建 | |||
---------------------------- | |||
1.1 传入dict | |||
创建DataSet主要有以下的3种方式 | |||
Example:: | |||
1.1 传入dict | |||
---------------------------- | |||
from fastNLP import DataSet | |||
data = {'sentence':["This is the first instance .", "Second instance .", "Third instance ."], | |||
'words': [['this', 'is', 'the', 'first', 'instance', '.'], ['Second', 'instance', '.'], ['Third', 'instance', '.'], | |||
'seq_len': [6, 3, 3]} | |||
dataset = DataSet(data) | |||
# 传入的dict的每个key的value应该为具有相同长度的list | |||
.. code-block:: | |||
1.2 通过构建Instance | |||
from fastNLP import DataSet | |||
data = {'sentence':["This is the first instance .", "Second instance .", "Third instance ."], | |||
'words': [['this', 'is', 'the', 'first', 'instance', '.'], ['Second', 'instance', '.'], ['Third', 'instance', '.'], | |||
'seq_len': [6, 3, 3]} | |||
dataset = DataSet(data) | |||
# 传入的dict的每个key的value应该为具有相同长度的list | |||
Example:: | |||
1.2 通过 Instance 构建 | |||
---------------------------- | |||
from fastNLP import DataSet | |||
from fastNLP import Instance | |||
dataset = DataSet() | |||
instance = Instance(sentence="This is the first instance", | |||
words=['this', 'is', 'the', 'first', 'instance', '.'], | |||
seq_len=6) | |||
dataset.append(instance) | |||
# 可以继续append更多内容,但是append的instance应该和第一个instance拥有完全相同的field | |||
.. code-block:: | |||
1.3 通过list(Instance) | |||
from fastNLP import DataSet | |||
from fastNLP import Instance | |||
dataset = DataSet() | |||
instance = Instance(sentence="This is the first instance", | |||
words=['this', 'is', 'the', 'first', 'instance', '.'], | |||
seq_len=6) | |||
dataset.append(instance) | |||
# 可以继续append更多内容,但是append的instance应该和第一个instance拥有完全相同的field | |||
Example:: | |||
1.3 通过 List[Instance] 构建 | |||
-------------------------------------- | |||
from fastNLP import DataSet | |||
from fastNLP import Instance | |||
instances = [] | |||
instances.append(Instance(sentence="This is the first instance", | |||
words=['this', 'is', 'the', 'first', 'instance', '.'], | |||
seq_len=6)) | |||
instances.append(Instance(sentence="Second instance .", | |||
words=['Second', 'instance', '.'], | |||
seq_len=3)) | |||
dataset = DataSet(instances) | |||
.. code-block:: | |||
2 DataSet与预处理 | |||
常见的预处理有如下几种 | |||
from fastNLP import DataSet | |||
from fastNLP import Instance | |||
instances = [] | |||
winstances.append(Instance(sentence="This is the first instance", | |||
ords=['this', 'is', 'the', 'first', 'instance', '.'], | |||
seq_len=6)) | |||
instances.append(Instance(sentence="Second instance .", | |||
words=['Second', 'instance', '.'], | |||
seq_len=3)) | |||
dataset = DataSet(instances) | |||
-------------------------------------- | |||
2.DataSet与预处理 | |||
-------------------------------------- | |||
2.1 从某个文本文件读取内容 # | |||
常见的预处理有如下几种 | |||
.. todo:: | |||
引用DataLoader | |||
2.1 从某个文本文件读取内容 | |||
-------------------------------------- | |||
Example:: | |||
.. code-block:: | |||
from fastNLP import DataSet | |||
from fastNLP import Instance | |||
@@ -78,21 +85,13 @@ | |||
sent, label = line.strip().split('\t') | |||
dataset.append(Instance(sentence=sent, label=label)) | |||
2.2 index, 返回结果为对DataSet对象的浅拷贝 | |||
Example:: | |||
.. note:: | |||
直接读取特定数据集的数据请参考 :doc:`/tutorials/tutorial_2_load_dataset` | |||
import numpy as np | |||
from fastNLP import DataSet | |||
dataset = DataSet({'a': np.arange(10), 'b': [[_] for _ in range(10)]}) | |||
d[0] # 使用一个下标获取一个instance | |||
>>{'a': 0 type=int,'b': [2] type=list} # 得到一个instance | |||
d[1:3] # 使用slice获取一个新的DataSet | |||
>>DataSet({'a': 1 type=int, 'b': [2] type=list}, {'a': 2 type=int, 'b': [2] type=list}) | |||
2.2 对DataSet中的内容处理 | |||
-------------------------------------- | |||
2.3 对DataSet中的内容处理 | |||
Example:: | |||
.. code-block:: | |||
from fastNLP import DataSet | |||
data = {'sentence':["This is the first instance .", "Second instance .", "Third instance ."]} | |||
@@ -108,9 +107,10 @@ | |||
return words | |||
dataset.apply(get_words, new_field_name='words') | |||
2.4 删除DataSet的内容 | |||
2.3 删除DataSet的内容 | |||
-------------------------------------- | |||
Example:: | |||
.. code-block:: | |||
from fastNLP import DataSet | |||
dataset = DataSet({'a': list(range(-5, 5))}) | |||
@@ -124,16 +124,18 @@ | |||
dataset.delete_field('a') | |||
2.5 遍历DataSet的内容 | |||
2.4 遍历DataSet的内容 | |||
-------------------------------------- | |||
Example:: | |||
.. code-block:: | |||
for instance in dataset: | |||
# do something | |||
2.6 一些其它操作 | |||
2.5 一些其它操作 | |||
-------------------------------------- | |||
Example:: | |||
.. code-block:: | |||
# 检查是否存在名为'a'的field | |||
dataset.has_field('a') # 或 ('a' in dataset) | |||
@@ -141,21 +143,25 @@ | |||
dataset.rename_field('a', 'b') | |||
# DataSet的长度 | |||
len(dataset) | |||
-------------------------------------- | |||
3.DataSet与自然语言处理(NLP) | |||
-------------------------------------- | |||
3 DataSet与自然语言处理(NLP) | |||
在目前深度学习的模型中,大都依赖于随机梯度下降法(SGD)进行模型的优化。随机梯度下降需要将数据切分成一个一个的Batch, | |||
一个Batch进行一次前向计算(forward)与梯度后向传播(backward)。在自然语言处理的场景下,往往还需要对数据进行pad。这是 | |||
由于句子的长度一般是不同的,但是一次Batch中的每个field都必须是一个tensor,所以需要将所有句子都补齐到相同的长度。 | |||
在目前深度学习的模型中,大都依赖于随机梯度下降法(SGD)进行模型的优化。随机梯度下降需要将数据切分成一个个的 batch, | |||
一个batch进行一次前向计算(forward)与梯度后向传播(backward)。在自然语言处理的场景下,往往还需要对数据进行pad。这是 | |||
由于句子的长度一般是不同的,但是一次batch中的每个field都必须是一个tensor,所以需要将所有句子都补齐到相同的长度。 | |||
3.1 DataSet与Batch | |||
3.1 DataSet与DataSetIter | |||
-------------------------------------- | |||
我们先看fastNLP中如何将数据分成一个一个的Batch的例子, 这里我们使用随机生成的数据来模拟一个二分类文本分类任务, | |||
我们先看fastNLP中如何将数据分成一个一个的batch的例子, 这里我们使用随机生成的数据来模拟一个二分类文本分类任务, | |||
words和characters是输入,labels是文本类别 | |||
Example:: | |||
.. code-block:: | |||
from fastNLP import DataSet | |||
from fastNLP import Batch | |||
from fastNLP import DataSetIter | |||
from fastNLP import SequentialSampler | |||
from fastNLP import EngChar2DPadder | |||
@@ -175,7 +181,7 @@ | |||
d.set_target('label') | |||
d.set_input('words', 'chars') | |||
for batch_x, batch_y in Batch(d, sampler=SequentialSampler(), batch_size=2): | |||
for batch_x, batch_y in DataSetIter(d, sampler=SequentialSampler(), batch_size=2): | |||
print("batch_x:", batch_x) | |||
print("batch_y:", batch_y) | |||
break | |||
@@ -194,23 +200,26 @@ | |||
# [ 0, 0, 0, 0, 0]]])} | |||
# {'label': tensor([0, 0])} | |||
其中 :class:`~fastNLP.Batch` 是用于从DataSet中按照batch_size为大小取出batch的迭代器, | |||
:class:`~fastNLP.SequentialSampler` 用于指示 Batch 以怎样的 | |||
其中 :class:`~fastNLP.DataSetIter` 是用于从DataSet中按照batch_size为大小取出batch的迭代器, | |||
:class:`~fastNLP.SequentialSampler` 用于指示 :class:`~fastNLP.DataSetIter` 以怎样的 | |||
顺序从DataSet中取出instance以组成一个batch, | |||
更详细的说明请参照 :class:`~fastNLP.Batch` 和 :class:`~fastNLP.SequentialSampler` 文档。 | |||
更详细的说明请参照 :class:`~fastNLP.DataSetIter` 和 :class:`~fastNLP.SequentialSampler` 文档。 | |||
通过DataSet.set_input('words', 'chars'), fastNLP将认为'words'和'chars'这两个field都是input,并将它们都放入迭代器 | |||
生成的第一个dict中; DataSet.set_target('labels'), fastNLP将认为'labels'这个field是target,并将其放入到迭代器的第 | |||
通过 ``DataSet.set_input('words', 'chars')`` , fastNLP将认为 `words` 和 `chars` 这两个field都是input,并将它们都放入迭代器 | |||
生成的第一个dict中; ``DataSet.set_target('labels')`` , fastNLP将认为 `labels` 这个field是target,并将其放入到迭代器的第 | |||
二个dict中。如上例中所打印结果。分为input和target的原因是由于它们在被 :class:`~fastNLP.Trainer` 所使用时会有所差异, | |||
详见 :class:`~fastNLP.Trainer` | |||
当把某个field设置为'target'或者'input'的时候(两者不是互斥的,可以同时设为input和target),fastNLP不仅仅只是将其放 | |||
置到不同的dict中,而还会对被设置为input或target的field进行类型检查。类型检查的目的是为了看能否把该field转为 | |||
pytorch的torch.LongTensor或torch.FloatTensor类型(也可以在Batch中设置输出numpy类型,参考 :class:`~fastNLP.Batch` ),如上例所示, | |||
fastNLP已将words,chars和label转为了Tensor类型。如果field在每个instance都拥有相同的维度(不能超过两维),且最内层 | |||
的元素都为相同的type(int, float, np.int*, np.float*),则fastNLP默认将对该field进行pad。也支持全为str的field作为 | |||
target和input,这种情况下,fastNLP默认不进行pad。另外,当某个field已经被设置为了target或者input后,之后append的 | |||
instance对应的field必须要和前面已有的内容一致,否则会报错。 | |||
当把某个field设置为 `target` 或者 `input` 的时候(两者不是互斥的,可以同时设为两种),fastNLP不仅仅只是将其放 | |||
置到不同的dict中,而还会对被设置为 `input` 或 `target` 的 field 进行类型检查。类型检查的目的是为了看能否把该 field 转为 | |||
pytorch的 :class:`torch.LongTensor` 或 :class:`torch.FloatTensor` 类型 | |||
(也可以在 :class:`~fastNLP.DataSetIter` 中设置输出numpy类型,参考 :class:`~fastNLP.DataSetIter` )。 | |||
如上例所示,fastNLP已将 `words` ,`chars` 和 `label` 转为了 :class:`Tensor` 类型。 | |||
如果 field 在每个 `instance` 都拥有相同的维度(不能超过两维),且最内层的元素都为相同的 type(int, float, np.int*, np.float*), | |||
则fastNLP默认将对该 field 进行pad。也支持全为str的field作为target和input,这种情况下,fastNLP默认不进行pad。 | |||
另外,当某个 field 已经被设置为了 target 或者 input 后,之后 `append` 的 | |||
`instance` 对应的 field 必须要和前面已有的内容一致,否则会报错。 | |||
可以查看field的dtype:: | |||
@@ -229,6 +238,7 @@ | |||
错误:: | |||
from fastNLP import DataSet | |||
d = DataSet({'data': [1, 'a']}) | |||
d.set_input('data') | |||
>> RuntimeError: Mixed data types in Field data: [<class 'str'>, <class 'int'>] | |||
@@ -243,6 +253,7 @@ | |||
当某个field被设置为忽略type之后,fastNLP将不对其进行pad。 | |||
3.2 DataSet与pad | |||
-------------------------------------- | |||
在fastNLP里,pad是与一个field绑定的。即不同的field可以使用不同的pad方式,比如在英文任务中word需要的pad和 | |||
character的pad方式往往是不同的。fastNLP是通过一个叫做 :class:`~fastNLP.Padder` 的子类来完成的。 | |||
@@ -252,7 +263,7 @@ | |||
如果 :class:`~fastNLP.AutoPadder` 或 :class:`~fastNLP.EngChar2DPadder` 无法满足需求, | |||
也可以自己写一个 :class:`~fastNLP.Padder` 。 | |||
Example:: | |||
.. code-block:: | |||
from fastNLP import DataSet | |||
from fastNLP import EngChar2DPadder | |||
@@ -417,7 +428,7 @@ class DataSet(object): | |||
""" | |||
将一个instance对象append到DataSet后面。 | |||
:param instance: :class:`~fastNLP.Instance` 类型。若DataSet不为空,则instance应该拥有和DataSet完全一样的field。 | |||
:param ~fastNLP.Instance instance: 若DataSet不为空,则instance应该拥有和DataSet完全一样的field。 | |||
""" | |||
if len(self.field_arrays) == 0: | |||
@@ -443,7 +454,7 @@ class DataSet(object): | |||
将fieldarray添加到DataSet中. | |||
:param str field_name: 新加入的field的名称 | |||
:param fieldarray: :class:`~fastNLP.FieldArray` 类型。需要加入DataSet的field的内容 | |||
:param ~fastNLP.core.FieldArray fieldarray: 需要加入DataSet的field的内容 | |||
:return: | |||
""" | |||
if not isinstance(fieldarray, FieldArray): | |||
@@ -459,8 +470,7 @@ class DataSet(object): | |||
:param str field_name: 新增的field的名称 | |||
:param list fields: 需要新增的field的内容 | |||
:param None, padder: :class:`~fastNLP.Padder` 类型, | |||
如果为None,则不进行pad,默认使用 :class:`~fastNLP.AutoPadder` 自动判断是否需要做pad。 | |||
:param None,~fastNLP.Padder padder: 如果为None,则不进行pad,默认使用 :class:`~fastNLP.AutoPadder` 自动判断是否需要做pad。 | |||
:param bool is_input: 新加入的field是否是input | |||
:param bool is_target: 新加入的field是否是target | |||
:param bool ignore_type: 是否忽略对新加入的field的类型检查 | |||
@@ -477,7 +487,7 @@ class DataSet(object): | |||
""" | |||
删除第index个instance | |||
:param int index: 需要删除的instance的index,从0开始 | |||
:param int index: 需要删除的instance的index,序号从0开始。 | |||
""" | |||
assert isinstance(index, int), "Only integer supported." | |||
if len(self) <= index: | |||
@@ -522,7 +532,7 @@ class DataSet(object): | |||
""" | |||
返回一个dict,key为field_name, value为对应的 :class:`~fastNLP.FieldArray` | |||
:return: dict: 返回如上所述的字典 | |||
:return dict: 返回如上所述的字典 | |||
""" | |||
return self.field_arrays | |||
@@ -530,7 +540,7 @@ class DataSet(object): | |||
""" | |||
返回一个list,包含所有 field 的名字 | |||
:return: list: 返回如上所述的列表 | |||
:return list: 返回如上所述的列表 | |||
""" | |||
return sorted(self.field_arrays.keys()) | |||
@@ -556,7 +566,7 @@ class DataSet(object): | |||
raise KeyError("DataSet has no field named {}.".format(old_name)) | |||
return self | |||
def set_target(self, *field_names, flag=True): | |||
def set_target(self, *field_names, flag=True, use_1st_ins_infer_dim_type=True): | |||
""" | |||
将field_names的field设置为target | |||
@@ -567,11 +577,14 @@ class DataSet(object): | |||
:param str field_names: field的名称 | |||
:param bool flag: 将field_name的target状态设置为flag | |||
:param bool use_1st_ins_infer_dim_type: 如果为True,将不会check该列是否所有数据都是同样的维度,同样的类型。将直接使用第一 | |||
行的数据进行类型和维度推断本列的数据的类型和维度。 | |||
""" | |||
assert isinstance(flag, bool), "Only bool type supported." | |||
for name in field_names: | |||
if name in self.field_arrays: | |||
try: | |||
self.field_arrays[name]._use_1st_ins_infer_dim_type = bool(use_1st_ins_infer_dim_type) | |||
self.field_arrays[name].is_target = flag | |||
except SetInputOrTargetException as e: | |||
print(f"Cannot set field:{name} as target.") | |||
@@ -579,7 +592,7 @@ class DataSet(object): | |||
else: | |||
raise KeyError("{} is not a valid field name.".format(name)) | |||
def set_input(self, *field_names, flag=True): | |||
def set_input(self, *field_names, flag=True, use_1st_ins_infer_dim_type=True): | |||
""" | |||
将field_names的field设置为input:: | |||
@@ -588,10 +601,13 @@ class DataSet(object): | |||
:param str field_names: field的名称 | |||
:param bool flag: 将field_name的input状态设置为flag | |||
:param bool use_1st_ins_infer_dim_type: 如果为True,将不会check该列是否所有数据都是同样的维度,同样的类型。将直接使用第一 | |||
行的数据进行类型和维度推断本列的数据的类型和维度。 | |||
""" | |||
for name in field_names: | |||
if name in self.field_arrays: | |||
try: | |||
self.field_arrays[name]._use_1st_ins_infer_dim_type = bool(use_1st_ins_infer_dim_type) | |||
self.field_arrays[name].is_input = flag | |||
except SetInputOrTargetException as e: | |||
print(f"Cannot set field:{name} as input, exception happens at the {e.index} value.") | |||
@@ -624,7 +640,7 @@ class DataSet(object): | |||
dataset.set_padder('chars', padder) # 则chars这个field会使用EngChar2DPadder进行pad操作 | |||
:param str field_name: 设置field的padding方式为padder | |||
:param None, Padder padder: 设置为None即删除padder, 即对该field不进行pad操作。 | |||
:param None,~fastNLP.Padder padder: 设置为None即删除padder, 即对该field不进行pad操作。 | |||
""" | |||
if field_name not in self.field_arrays: | |||
raise KeyError("There is no field named {}.".format(field_name)) | |||
@@ -672,7 +688,7 @@ class DataSet(object): | |||
2. is_target: bool, 如果为True则将名为 `new_field_name` 的field设置为target | |||
3. ignore_type: bool, 如果为True则将名为 `new_field_name` 的field的ignore_type设置为true, 忽略其类型 | |||
:return: list(Any), 里面的元素为func的返回值,所以list长度为DataSet的长度 | |||
:return List[Any]: 里面的元素为func的返回值,所以list长度为DataSet的长度 | |||
""" | |||
assert len(self) != 0, "Null DataSet cannot use apply_field()." | |||
@@ -699,7 +715,7 @@ class DataSet(object): | |||
""" | |||
将results作为加入到新的field中,field名称为new_field_name | |||
:param list(str) results: 一般是apply*()之后的结果 | |||
:param List[str] results: 一般是apply*()之后的结果 | |||
:param str new_field_name: 新加入的field的名称 | |||
:param dict kwargs: 用户apply*()时传入的自定义参数 | |||
:return: | |||
@@ -742,7 +758,7 @@ class DataSet(object): | |||
3. ignore_type: bool, 如果为True则将 `new_field_name` 的field的ignore_type设置为true, 忽略其类型 | |||
:return: list(Any), 里面的元素为func的返回值,所以list长度为DataSet的长度 | |||
:return List[Any]: 里面的元素为func的返回值,所以list长度为DataSet的长度 | |||
""" | |||
assert len(self) != 0, "Null DataSet cannot use apply()." | |||
idx = -1 | |||
@@ -807,7 +823,7 @@ class DataSet(object): | |||
:param float ratio: 0<ratio<1, 返回的第一个DataSet拥有 `(1-ratio)` 这么多数据,第二个DataSet拥有`ratio`这么多数据 | |||
:param bool shuffle: 在split前是否shuffle一下 | |||
:return: [DataSet, DataSet] | |||
:return: [ :class:`~fastNLP.读取后的DataSet` , :class:`~fastNLP.读取后的DataSet` ] | |||
""" | |||
assert isinstance(ratio, float) | |||
assert 0 < ratio < 1 | |||
@@ -831,7 +847,7 @@ class DataSet(object): | |||
@classmethod | |||
def read_csv(cls, csv_path, headers=None, sep=",", dropna=True): | |||
""" | |||
r""" | |||
.. warning:: | |||
此方法会在下个版本移除,请使用 :class:`fastNLP.io.CSVLoader` | |||
@@ -842,7 +858,7 @@ class DataSet(object): | |||
与csv文件中每行的元素个数相同。 | |||
:param str sep: 分割符 | |||
:param bool dropna: 是否忽略与header数量不一致行。 | |||
:return: 一个 :class:`~fastNLP.DataSet` 类型的对象 | |||
:return: 读取后的 :class:`~fastNLP.读取后的DataSet`。 | |||
""" | |||
warnings.warn('DataSet.read_csv is deprecated, use CSVLoader instead', | |||
category=DeprecationWarning) | |||
@@ -882,11 +898,11 @@ class DataSet(object): | |||
@staticmethod | |||
def load(path): | |||
""" | |||
r""" | |||
从保存的DataSet pickle文件的路径中读取DataSet | |||
:param str path: 从哪里读取DataSet | |||
:return: 一个 :class:`~fastNLP.DataSet` 类型的对象 | |||
:return: 读取后的 :class:`~fastNLP.读取后的DataSet`。 | |||
""" | |||
with open(path, 'rb') as f: | |||
d = pickle.load(f) | |||
@@ -0,0 +1,351 @@ | |||
import torch | |||
import torch.cuda | |||
import torch.optim | |||
import torch.distributed as dist | |||
from torch.utils.data.distributed import DistributedSampler | |||
from torch.nn.parallel import DistributedDataParallel as DDP | |||
import os | |||
from tqdm import tqdm | |||
import logging | |||
import time | |||
from datetime import datetime, timedelta | |||
from functools import partial | |||
from .batch import DataSetIter, BatchIter | |||
from .callback import DistCallbackManager, CallbackException, TesterCallback | |||
from .dataset import DataSet | |||
from .losses import _prepare_losser | |||
from .optimizer import Optimizer | |||
from .utils import _build_args | |||
from .utils import _move_dict_value_to_device | |||
from .utils import _get_func_signature | |||
from pkg_resources import parse_version | |||
__all__ = [ | |||
'get_local_rank', | |||
'DistTrainer', | |||
] | |||
def get_local_rank(): | |||
if 'LOCAL_RANK' in os.environ: | |||
return int(os.environ['LOCAL_RANK']) | |||
from argparse import ArgumentParser | |||
parser = ArgumentParser() | |||
parser.add_argument('--local_rank', type=int) | |||
args, _ = parser.parse_known_args() | |||
if 'local_rank' in args and args.local_rank: | |||
os.environ['LOCAL_RANK'] = str(args.local_rank) # for multiple calls for this function | |||
return args.local_rank | |||
raise RuntimeError('Please use "python -m torch.distributed.launch train_script.py') | |||
class DistTrainer(): | |||
"""Distributed Trainer that support distributed and mixed precision training | |||
""" | |||
def __init__(self, train_data, model, optimizer=None, loss=None, | |||
callbacks_all=None, callbacks_master=None, | |||
batch_size_per_gpu=8, n_epochs=1, | |||
num_data_workers=1, drop_last=False, | |||
dev_data=None, metrics=None, metric_key=None, | |||
update_every=1, print_every=10, validate_every=-1, | |||
log_path=None, | |||
save_every=-1, save_path=None, device='auto', | |||
fp16='', backend=None, init_method=None): | |||
assert device in ['auto', 'cuda', 'cpu'], "Please set correct device in [auto', 'cuda', 'cpu']" | |||
if device == 'auto': | |||
device = 'cuda' if torch.cuda.is_available() else 'cpu' | |||
if backend is None: | |||
backend = 'nccl' if device == 'cuda' else 'gloo' | |||
# init distributed | |||
if device == 'cuda': | |||
torch.cuda.set_device(get_local_rank()) | |||
self.device = torch.device("cuda", get_local_rank()) | |||
else: | |||
self.device = torch.device(device) | |||
dist.init_process_group(backend=backend, init_method=init_method) | |||
self.world_size = dist.get_world_size() | |||
self.rank = dist.get_rank() # unique id for each process | |||
self.model = model | |||
self.train_data = train_data | |||
self.batch_size_per_gpu = int(batch_size_per_gpu) | |||
self.n_epochs = int(n_epochs) | |||
self.num_data_workers = int(num_data_workers) | |||
self.drop_last = drop_last | |||
self.update_every = int(update_every) | |||
self.print_every = int(print_every) | |||
self.validate_every = int(validate_every) | |||
self.save_every = int(save_every) | |||
self.save_path = save_path | |||
self.losser = _prepare_losser(loss) | |||
self.fp16 = fp16 | |||
self.init_method = init_method | |||
self.backend = backend | |||
self.local_rank = get_local_rank() | |||
self._forward_func = model.forward | |||
self.callback_manager = DistCallbackManager( | |||
env={"trainer": self}, callbacks_all=callbacks_all, | |||
callbacks_master=callbacks_master) | |||
self.metric_key = metric_key | |||
model.to(self.device) | |||
optimizer = self._get_optimizer(optimizer) | |||
# init fp16, must before DataParallel init | |||
if len(self.fp16): | |||
assert isinstance(self.fp16, str), "Please set Apex AMP optimization level selected in ['O0', 'O1', 'O2', 'O3']" | |||
try: | |||
from apex import amp | |||
except ImportError: | |||
raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use fp16 training.") | |||
assert torch.backends.cudnn.enabled, "Amp requires cudnn backend to be enabled." | |||
assert device == 'cuda', "Amp requires cuda device" | |||
model, optimizer = amp.initialize(model, optimizer, opt_level=self.fp16) | |||
# init DataParallel | |||
if parse_version(torch.__version__)>=parse_version('1.1'): | |||
self.model = DDP(model, device_ids=[self.local_rank], | |||
output_device=self.local_rank, find_unused_parameters=True) | |||
else: | |||
self.model = DDP(model, device_ids=[self.local_rank], | |||
output_device=self.local_rank) | |||
self.optimizer = optimizer | |||
self.sampler = DistributedSampler(self.train_data) | |||
self.data_iterator = self._get_data_iter(self.train_data) | |||
self.n_steps = self._get_n_steps() | |||
# for evaluation, only run eval on master proc | |||
if dev_data and metrics: | |||
cb = TesterCallback( | |||
dev_data, model, metrics, | |||
batch_size=batch_size_per_gpu, num_workers=num_data_workers) | |||
self.callback_manager.callbacks_master += \ | |||
self.callback_manager.prepare_callbacks([cb]) | |||
# Setup logging | |||
dist.barrier() | |||
self.start_time = datetime.now().strftime('%m_%d_%Y-%H_%M') | |||
if self.save_path: | |||
self.cp_save_path = os.path.join(self.save_path, 'checkpoints', self.start_time) | |||
else: | |||
self.cp_save_path = None | |||
# use INFO in the master, WARN for others | |||
logging.basicConfig(filename=log_path, | |||
format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', | |||
datefmt='%m/%d/%Y %H:%M:%S', | |||
level=logging.INFO if self.is_master else logging.WARN) | |||
self.logger = logging.getLogger(__name__) | |||
self.logger.info("Setup Distributed Trainer") | |||
self.logger.warning("Process pid: {}, rank: {}, local rank: {}, device: {}, fp16: {}".format( | |||
os.getpid(), self.rank, self.local_rank, self.device, self.fp16 if self.fp16 else False)) | |||
self.logger.info("Num of processes: {}".format(self.world_size)) | |||
self.logger.info("Use device: {}".format(device)) | |||
self.logger.info("Training with fp16: {}, optimization level: {}".format( | |||
len(self.fp16) > 0, self.fp16 if self.fp16 else None)) | |||
def _get_n_steps(self): | |||
batch_size = self.world_size * self.batch_size_per_gpu | |||
return (len(self.train_data) // batch_size + int( | |||
len(self.train_data) % batch_size != 0)) * int(self.drop_last == 0) * self.n_epochs | |||
def _get_data_iter(self, dataset): | |||
if isinstance(dataset, DataSet): | |||
return DataSetIter( | |||
dataset=dataset, batch_size=self.batch_size_per_gpu, | |||
num_workers=self.num_data_workers, sampler=self.sampler, | |||
drop_last=self.drop_last | |||
) | |||
elif isinstance(dataset, BatchIter): | |||
return dataset | |||
else: | |||
raise TypeError("train_data type {} not support".format(type(dataset))) | |||
def _get_optimizer(self, optimizer): | |||
if isinstance(optimizer, torch.optim.Optimizer): | |||
return optimizer | |||
elif isinstance(optimizer, Optimizer): | |||
return optimizer.construct_from_pytorch(self.model.parameters()) | |||
elif optimizer is None: | |||
return torch.optim.Adam(self.model.parameters(), lr=4e-3) | |||
else: | |||
raise TypeError("optimizer can only be torch.optim.Optimizer type, not {}.".format(type(optimizer))) | |||
@property | |||
def is_master(self): | |||
return self.rank == 0 | |||
def train(self, on_exception='auto'): | |||
try: | |||
self.logger.info("###### Training epochs started ######") | |||
self.logger.info('Total epochs: %d'% self.n_epochs) | |||
self.logger.info('Total steps: %d'% self.n_steps) | |||
self.logger.info('Num instances per GPU %d'% self.batch_size_per_gpu) | |||
self.logger.info('Total batch_size: %d'% self.batch_size_per_gpu * dist.get_world_size()) | |||
self.logger.info('Total num of samples: %d'% len(self.train_data)) | |||
self.logger.info("Num of callbacks for all workers: {}".format( | |||
len(self.callback_manager.callbacks_all))) | |||
self.logger.info("Num of callbacks for master workers: {}".format( | |||
len(self.callback_manager.callbacks_master))) | |||
self.logger.info("Callbacks for all workers: {}".format( | |||
[repr(cb) for cb in self.callback_manager.callbacks_all])) | |||
self.logger.info("Callbacks for master workers: {}".format( | |||
[repr(cb) for cb in self.callback_manager.callbacks_master])) | |||
start_time = time.time() | |||
results = {} | |||
if self.n_epochs <= 0: | |||
self.logger.info("Training epoch is {}, nothing was done.".format(self.n_epochs)) | |||
results['seconds'] = 0. | |||
return results | |||
try: | |||
self.callback_manager.on_train_begin() | |||
self._train() | |||
self.callback_manager.on_train_end() | |||
except BaseException as e: | |||
self.callback_manager.on_exception(e) | |||
if on_exception == 'auto': | |||
if not isinstance(e, (CallbackException, KeyboardInterrupt)): | |||
raise e | |||
else: | |||
self.logger.info('Catch {}, ignored.'.format(e.__class__.__name__)) | |||
elif on_exception == 'raise': | |||
raise e | |||
results['seconds'] = round(time.time() - start_time, 2) | |||
self.logger.info("###### Train finished ######") | |||
self.logger.info('Total train time: {} seconds.'. format(results['seconds'])) | |||
return results | |||
finally: | |||
self.close() | |||
def _train(self): | |||
if self.fp16: | |||
# skip check, done in __init__() | |||
from apex import amp | |||
self.step = 0 | |||
self.epoch = 0 | |||
self.pbar = tqdm(total=self.n_steps, postfix='loss:{0:<6.5f}', | |||
leave=False, dynamic_ncols=True, disable=not self.is_master) | |||
pbar = self.pbar | |||
avg_loss = 0 | |||
data_iterator = self.data_iterator | |||
self.model.zero_grad() | |||
for epoch in range(1, self.n_epochs + 1): | |||
self.epoch = epoch | |||
pbar.set_description_str(desc="Epoch {}/{}".format(epoch, self.n_epochs)) | |||
# early stopping | |||
self.callback_manager.on_epoch_begin() | |||
for batch_x, batch_y in data_iterator: | |||
self.model.train() | |||
self.step += 1 | |||
_move_dict_value_to_device(batch_x, batch_y, device=self.device) | |||
indices = data_iterator.get_batch_indices() | |||
# negative sampling; replace unknown; re-weight batch_y | |||
self.callback_manager.on_batch_begin(batch_x, batch_y, indices) | |||
prediction = self._data_forward(self.model, batch_x) | |||
# edit prediction | |||
self.callback_manager.on_loss_begin(batch_y, prediction) | |||
loss = self._compute_loss(prediction, batch_y) | |||
avg_loss += loss.item() | |||
# Is loss NaN or inf? requires_grad = False | |||
self.callback_manager.on_backward_begin(loss) | |||
if self.fp16: | |||
with amp.scale_loss(loss, self.optimizer) as scale_loss: | |||
scale_loss.backward() | |||
else: | |||
loss.backward() | |||
self.callback_manager.on_backward_end() | |||
self._update() | |||
self.callback_manager.on_step_end() | |||
if self.step % self.print_every == 0: | |||
avg_loss = float(avg_loss) / self.print_every | |||
print_output = "loss:{:<6.5f}".format(avg_loss) | |||
pbar.update(self.print_every) | |||
pbar.set_postfix_str(print_output) | |||
avg_loss = 0 | |||
self.callback_manager.on_batch_end() | |||
if ((self.validate_every > 0 and self.step % self.validate_every == 0) or | |||
(self.validate_every < 0 and self.step % len(data_iterator) == 0)): | |||
self.callback_manager.on_valid_begin() | |||
eval_res = self.callback_manager.on_validation() | |||
eval_res = list(filter(lambda x: x is not None, eval_res)) | |||
if len(eval_res): | |||
eval_res, is_better = list(zip(*eval_res)) | |||
else: | |||
eval_res, is_better = None, None | |||
self.callback_manager.on_valid_end( | |||
eval_res, self.metric_key, self.optimizer, is_better) | |||
dist.barrier() | |||
if self.cp_save_path and \ | |||
self.save_every > 0 and \ | |||
self.step % self.save_every == 0: | |||
self.save_check_point() | |||
# ================= mini-batch end ==================== # | |||
if self.save_every < 0 and self.cp_save_path: | |||
self.save_check_point() | |||
# lr decay; early stopping | |||
self.callback_manager.on_epoch_end() | |||
# =============== epochs end =================== # | |||
pbar.close() | |||
self.pbar = None | |||
# ============ tqdm end ============== # | |||
def _update(self): | |||
"""Perform weight update on a model. | |||
""" | |||
if self.step % self.update_every == 0: | |||
self.optimizer.step() | |||
self.model.zero_grad() | |||
def _data_forward(self, network, x): | |||
x = _build_args(self._forward_func, **x) | |||
y = network(**x) | |||
if not isinstance(y, dict): | |||
raise TypeError( | |||
f"The return value of {_get_func_signature(self._forward_func)} should be dict, got {type(y)}.") | |||
return y | |||
def _compute_loss(self, predict, truth): | |||
"""Compute loss given prediction and ground truth. | |||
:param predict: prediction dict, produced by model.forward | |||
:param truth: ground truth dict, produced by batch_y | |||
:return: a scalar | |||
""" | |||
loss = self.losser(predict, truth) | |||
if self.update_every > 1: | |||
loss = loss / self.update_every | |||
return loss.mean() | |||
def save_check_point(self, only_params=False): | |||
# only master save models | |||
if self.is_master: | |||
os.makedirs(self.cp_save_path, exist_ok=True) | |||
path = os.path.join(self.cp_save_path, 'checkpoint-{}.bin'.format(self.step)) | |||
self.logger.info("Save checkpoint to {}".format(path)) | |||
model_to_save = self.model.module | |||
if only_params: | |||
model_to_save = model_to_save.state_dict() | |||
torch.save(model_to_save, path) | |||
def close(self): | |||
dist.destroy_process_group() |
@@ -23,7 +23,8 @@ class AppendToTargetOrInputException(Exception): | |||
self.field_name = field_name # 标示当前field的名称 | |||
class FieldArray: | |||
def __init__(self, name, content, is_target=False, is_input=False, padder=None, ignore_type=False): | |||
def __init__(self, name, content, is_target=False, is_input=False, padder=None, ignore_type=False, | |||
use_1st_ins_infer_dim_type=True): | |||
if len(content)==0: | |||
raise RuntimeError("Empty fieldarray is not allowed.") | |||
_content = content | |||
@@ -38,6 +39,7 @@ class FieldArray: | |||
# 根据input的情况设置input,target等 | |||
self._cell_ndim = None # 多少维度 | |||
self.dtype = None # 最内层的element都是什么类型的 | |||
self._use_1st_ins_infer_dim_type = bool(use_1st_ins_infer_dim_type) | |||
self._is_input = False | |||
self._is_target = False | |||
@@ -77,7 +79,7 @@ class FieldArray: | |||
if value is True and \ | |||
self._is_target is False and \ | |||
self._ignore_type is False: | |||
self._check_dtype_and_ndim() | |||
self._check_dtype_and_ndim(only_check_1st_ins_dim_type=self._use_1st_ins_infer_dim_type) | |||
if value is False and self._is_target is False: | |||
self.dtype = None | |||
self._cell_ndim = None | |||
@@ -95,32 +97,34 @@ class FieldArray: | |||
if value is True and \ | |||
self._is_input is False and \ | |||
self._ignore_type is False: | |||
self._check_dtype_and_ndim() | |||
self._check_dtype_and_ndim(only_check_1st_ins_dim_type=self._use_1st_ins_infer_dim_type) | |||
if value is False and self._is_input is False: | |||
self.dtype = None | |||
self._cell_ndim = None | |||
self._is_target = value | |||
def _check_dtype_and_ndim(self): | |||
def _check_dtype_and_ndim(self, only_check_1st_ins_dim_type=True): | |||
""" | |||
检查当前content所有的element是否是同一个类型,且是否每个元素具有相同的维度。通过的话,设置_cell_ndim与_ele_type属性;没有 | |||
通过将直接报错. | |||
:param bool only_check_1st_ins_dim_type: 是否只检查第一个元素的type和dim | |||
:return: | |||
""" | |||
cell_0 = self.content[0] | |||
index = 0 | |||
try: | |||
type_0, dim_0 = _get_ele_type_and_dim(cell_0) | |||
for cell in self.content[1:]: | |||
index += 1 | |||
type_i, dim_i = _get_ele_type_and_dim(cell) | |||
if type_i!=type_0: | |||
raise SetInputOrTargetException("Type:{} in index {} is different from the first element with type:{}." | |||
".".format(type_i, index, type_0)) | |||
if dim_0!=dim_i: | |||
raise SetInputOrTargetException("Dimension:{} in index {} is different from the first element with " | |||
"dimension:{}.".format(dim_i, index, dim_0)) | |||
if not only_check_1st_ins_dim_type: | |||
for cell in self.content[1:]: | |||
index += 1 | |||
type_i, dim_i = _get_ele_type_and_dim(cell) | |||
if type_i!=type_0: | |||
raise SetInputOrTargetException("Type:{} in index {} is different from the first element with type:{}." | |||
".".format(type_i, index, type_0)) | |||
if dim_0!=dim_i: | |||
raise SetInputOrTargetException("Dimension:{} in index {} is different from the first element with " | |||
"dimension:{}.".format(dim_i, index, dim_0)) | |||
self._cell_ndim = dim_0 | |||
self.dtype = type_0 | |||
except SetInputOrTargetException as e: | |||
@@ -132,7 +136,7 @@ class FieldArray: | |||
:param val: 把该val append到fieldarray。 | |||
:return: | |||
""" | |||
if (self._is_target or self._is_input) and self._ignore_type is False: | |||
if (self._is_target or self._is_input) and self._ignore_type is False and not self._use_1st_ins_infer_dim_type: | |||
type_, dim_ = _get_ele_type_and_dim(val) | |||
if self.dtype!=type_: | |||
raise AppendToTargetOrInputException(f"Value(type:{type_}) are of different types with " | |||
@@ -144,6 +148,14 @@ class FieldArray: | |||
else: | |||
self.content.append(val) | |||
def pop(self, index): | |||
""" | |||
删除该field中index处的元素 | |||
:param int index: 从0开始的数据下标。 | |||
:return: | |||
""" | |||
self.content.pop(index) | |||
def __getitem__(self, indices): | |||
return self.get(indices, pad=False) | |||
@@ -448,9 +460,10 @@ class Padder: | |||
用于对batch进行padding操作。传入的element是inplace的,即直接修改element可能导致数据变化,建议inplace修改之前deepcopy一份。 | |||
.. py:function:: __call__(self, contents, field_name, field_ele_dtype): | |||
传入的是List内容。假设有以下的DataSet。 | |||
:param list(Any) contents: 传入的element是inplace的,即直接修改element可能导致数据变化,建议inplace修改之前 | |||
:param List[Any] contents: 传入的element是inplace的,即直接修改element可能导致数据变化,建议inplace修改之前 | |||
deepcopy一份。 | |||
:param str, field_name: field的名称。 | |||
:param np.int64,np.float64,np.str,None, field_ele_dtype: 该field的内层元素的类型。如果该field的ignore_type为True,该这个值为None。 | |||
@@ -469,7 +482,7 @@ class Padder: | |||
""" | |||
传入的是List内容。假设有以下的DataSet。 | |||
:param list(Any) contents: 传入的element是inplace的,即直接修改element可能导致数据变化,建议inplace修改之前 | |||
:param List[Any] contents: 传入的element是inplace的,即直接修改element可能导致数据变化,建议inplace修改之前 | |||
deepcopy一份。 | |||
:param str, field_name: field的名称。 | |||
:param np.int64,np.float64,np.str,None, field_ele_dtype: 该field的内层元素的类型。如果该field的ignore_type为True, | |||
@@ -208,7 +208,7 @@ class CrossEntropyLoss(LossBase): | |||
:param seq_len: 句子的长度, 长度之外的token不会计算loss。。 | |||
:param padding_idx: padding的index,在计算loss时将忽略target中标号为padding_idx的内容, 可以通过该值代替 | |||
传入seq_len. | |||
:param str reduction: 支持'mean','sum'和'none'. | |||
:param str reduction: 支持 `mean` ,`sum` 和 `none` . | |||
Example:: | |||
@@ -225,7 +225,7 @@ class CrossEntropyLoss(LossBase): | |||
def get_loss(self, pred, target, seq_len=None): | |||
if pred.dim() > 2: | |||
if pred.size(1) != target.size(1): | |||
if pred.size(1) != target.size(1): # 有可能顺序替换了 | |||
pred = pred.transpose(1, 2) | |||
pred = pred.reshape(-1, pred.size(-1)) | |||
target = target.reshape(-1) | |||
@@ -265,9 +265,9 @@ class BCELoss(LossBase): | |||
二分类交叉熵损失函数 | |||
:param pred: 参数映射表中`pred`的映射关系,None表示映射关系为`pred`->`pred` | |||
:param target: 参数映射表中`target`的映射关系,None表示映射关系为`target`->`target` | |||
:param str reduction: 支持'mean','sum'和'none'. | |||
:param pred: 参数映射表中 `pred` 的映射关系,None表示映射关系为 `pred` -> `pred` | |||
:param target: 参数映射表中 `target` 的映射关系,None表示映射关系为 `target` -> `target` | |||
:param str reduction: 支持 `mean` ,`sum` 和 `none` . | |||
""" | |||
def __init__(self, pred=None, target=None, reduction='mean'): | |||
@@ -286,11 +286,11 @@ class NLLLoss(LossBase): | |||
负对数似然损失函数 | |||
:param pred: 参数映射表中`pred`的映射关系,None表示映射关系为`pred`->`pred` | |||
:param target: 参数映射表中`target`的映射关系,None表示映射关系为`target`->`target` | |||
:param pred: 参数映射表中 `pred` 的映射关系,None表示映射关系为 `pred` -> `pred` | |||
:param target: 参数映射表中 `target` 的映射关系,None表示映射关系为 `target` -> `target` | |||
:param ignore_idx: ignore的index,在计算loss时将忽略target中标号为ignore_idx的内容, 可以通过该值代替 | |||
传入seq_len. | |||
:param str reduction: 支持'mean','sum'和'none'. | |||
:param str reduction: 支持 `mean` ,`sum` 和 `none` . | |||
""" | |||
def __init__(self, pred=None, target=None, ignore_idx=-100, reduction='mean'): | |||
@@ -27,14 +27,14 @@ from abc import abstractmethod | |||
class MetricBase(object): | |||
""" | |||
所有metrics的基类,,所有的传入到Trainer, Tester的Metric需要继承自该对象,需要覆盖写入evaluate(), get_metric()方法。 | |||
所有metrics的基类,所有的传入到Trainer, Tester的Metric需要继承自该对象,需要覆盖写入evaluate(), get_metric()方法。 | |||
evaluate(xxx)中传入的是一个batch的数据。 | |||
get_metric(xxx)当所有数据处理完毕,调用该方法得到最终的metric值 | |||
以分类问题中,Accuracy计算为例 | |||
假设model的forward返回dict中包含'pred'这个key, 并且该key需要用于Accuracy:: | |||
假设model的forward返回dict中包含 `pred` 这个key, 并且该key需要用于Accuracy:: | |||
class Model(nn.Module): | |||
def __init__(xxx): | |||
@@ -43,7 +43,7 @@ class MetricBase(object): | |||
# do something | |||
return {'pred': pred, 'other_keys':xxx} # pred's shape: batch_size x num_classes | |||
假设dataset中'label'这个field是需要预测的值,并且该field被设置为了target | |||
假设dataset中 `label` 这个field是需要预测的值,并且该field被设置为了target | |||
对应的AccMetric可以按如下的定义, version1, 只使用这一次:: | |||
class AccMetric(MetricBase): | |||
@@ -478,7 +478,7 @@ class SpanFPreRecMetric(MetricBase): | |||
别名::class:`fastNLP.SpanFPreRecMetric` :class:`fastNLP.core.metrics.SpanFPreRecMetric` | |||
在序列标注问题中,以span的方式计算F, pre, rec. | |||
比如中文Part of speech中,会以character的方式进行标注,句子'中国在亚洲'对应的POS可能为(以BMES为例) | |||
比如中文Part of speech中,会以character的方式进行标注,句子 `中国在亚洲` 对应的POS可能为(以BMES为例) | |||
['B-NN', 'E-NN', 'S-DET', 'B-NN', 'E-NN']。该metric就是为类似情况下的F1计算。 | |||
最后得到的metric结果为:: | |||
@@ -502,15 +502,15 @@ class SpanFPreRecMetric(MetricBase): | |||
:param tag_vocab: 标签的 :class:`~fastNLP.Vocabulary` 。支持的标签为"B"(没有label);或"B-xxx"(xxx为某种label,比如POS中的NN), | |||
在解码时,会将相同xxx的认为是同一个label,比如['B-NN', 'E-NN']会被合并为一个'NN'. | |||
:param str pred: 用该key在evaluate()时从传入dict中取出prediction数据。 为None,则使用'pred'取数据 | |||
:param str target: 用该key在evaluate()时从传入dict中取出target数据。 为None,则使用'target'取数据 | |||
:param str seq_len: 用该key在evaluate()时从传入dict中取出sequence length数据。为None,则使用'seq_len'取数据。 | |||
:param str pred: 用该key在evaluate()时从传入dict中取出prediction数据。 为None,则使用 `pred` 取数据 | |||
:param str target: 用该key在evaluate()时从传入dict中取出target数据。 为None,则使用 `target` 取数据 | |||
:param str seq_len: 用该key在evaluate()时从传入dict中取出sequence length数据。为None,则使用 `seq_len` 取数据。 | |||
:param str encoding_type: 目前支持bio, bmes, bmeso, bioes | |||
:param list ignore_labels: str 组成的list. 这个list中的class不会被用于计算。例如在POS tagging时传入['NN'],则不会计算'NN'这 | |||
个label | |||
:param bool only_gross: 是否只计算总的f1, precision, recall的值;如果为False,不仅返回总的f1, pre, rec, 还会返回每个 | |||
label的f1, pre, rec | |||
:param str f_type: 'micro'或'macro'. 'micro':通过先计算总体的TP,FN和FP的数量,再计算f, precision, recall; 'macro': | |||
:param str f_type: `micro` 或 `macro` . `micro` :通过先计算总体的TP,FN和FP的数量,再计算f, precision, recall; `macro` : | |||
分布计算每个类别的f, precision, recall,然后做平均(各类别f的权重相同) | |||
:param float beta: f_beta分数, :math:`f_{beta} = \frac{(1 + {beta}^{2})*(pre*rec)}{({beta}^{2}*pre + rec)}` . | |||
常用为beta=0.5, 1, 2. 若为0.5则精确率的权重高于召回率;若为1,则两者平等;若为2,则召回率权重高于精确率。 | |||
@@ -814,8 +814,8 @@ class ExtractiveQAMetric(MetricBase): | |||
if not self.right_open: | |||
e += 1 | |||
te += 1 | |||
if ts == 0 and te == int(not self.right_open): | |||
if s == 0 and e == int(not self.right_open): | |||
if ts == 0 and te == 1: | |||
if s == 0 and e == 1: | |||
self.no_ans_correct += 1 | |||
self.no2no += 1 | |||
else: | |||
@@ -5,7 +5,8 @@ optimizer 模块定义了 fastNLP 中所需的各种优化器,一般做为 :cl | |||
__all__ = [ | |||
"Optimizer", | |||
"SGD", | |||
"Adam" | |||
"Adam", | |||
"AdamW" | |||
] | |||
import torch | |||
@@ -48,7 +49,7 @@ class NullOptimizer(Optimizer): | |||
super().__init__(None) | |||
def construct_from_pytorch(self, model_params): | |||
pass | |||
return self | |||
def __getattr__(self, item): | |||
def pass_func(*args, **kwargs): | |||
@@ -103,21 +104,28 @@ class Adam(Optimizer): | |||
class AdamW(TorchOptimizer): | |||
r"""对AdamW的实现,该实现应该会在pytorch更高版本中出现,https://github.com/pytorch/pytorch/pull/21250。这里提前加入 | |||
r""" | |||
别名::class:`fastNLP.AdamW` :class:`fastNLP.core.optimizer.AdamW` | |||
对AdamW的实现,该实现应该会在pytorch更高版本中出现,https://github.com/pytorch/pytorch/pull/21250。这里提前加入 | |||
.. todo:: | |||
翻译成中文 | |||
The original Adam algorithm was proposed in `Adam: A Method for Stochastic Optimization`_. | |||
The AdamW variant was proposed in `Decoupled Weight Decay Regularization`_. | |||
Arguments: | |||
params (iterable): iterable of parameters to optimize or dicts defining | |||
parameter groups | |||
lr (float, optional): learning rate (default: 1e-3) | |||
betas (Tuple[float, float], optional): coefficients used for computing | |||
running averages of gradient and its square (default: (0.9, 0.99)) | |||
eps (float, optional): term added to the denominator to improve | |||
numerical stability (default: 1e-8) | |||
weight_decay (float, optional): weight decay coefficient (default: 1e-2) | |||
amsgrad (boolean, optional): whether to use the AMSGrad variant of this | |||
algorithm from the paper `On the Convergence of Adam and Beyond`_ | |||
(default: False) | |||
:param params (iterable): iterable of parameters to optimize or dicts defining | |||
parameter groups | |||
:param lr (float, optional): learning rate (default: 1e-3) | |||
:param betas (Tuple[float, float], optional): coefficients used for computing | |||
running averages of gradient and its square (default: (0.9, 0.99)) | |||
:param eps (float, optional): term added to the denominator to improve | |||
numerical stability (default: 1e-8) | |||
:param weight_decay (float, optional): weight decay coefficient (default: 1e-2) | |||
algorithm from the paper `On the Convergence of Adam and Beyond`_ | |||
(default: False) | |||
.. _Adam\: A Method for Stochastic Optimization: | |||
https://arxiv.org/abs/1412.6980 | |||
.. _Decoupled Weight Decay Regularization: | |||
@@ -147,9 +155,9 @@ class AdamW(TorchOptimizer): | |||
def step(self, closure=None): | |||
"""Performs a single optimization step. | |||
Arguments: | |||
closure (callable, optional): A closure that reevaluates the model | |||
and returns the loss. | |||
:param closure: (callable, optional) A closure that reevaluates the model | |||
and returns the loss. | |||
""" | |||
loss = None | |||
if closure is not None: | |||
@@ -25,9 +25,9 @@ class Sampler(object): | |||
def __call__(self, data_set): | |||
""" | |||
:param DataSet data_set: `DataSet` 对象, 需要Sample的数据 | |||
:return result: list(int) 其中元素的下标序列, ``data_set`` 中元素会按 ``result`` 中顺序取出 | |||
""" | |||
:param DataSet data_set: `DataSet` 对象, 需要Sample的数据 | |||
:return result: list(int) 其中元素的下标序列, ``data_set`` 中元素会按 ``result`` 中顺序取出 | |||
""" | |||
raise NotImplementedError | |||
@@ -62,16 +62,27 @@ class BucketSampler(Sampler): | |||
带Bucket的 `Random Sampler`. 可以随机地取出长度相似的元素 | |||
:param int num_buckets: bucket的数量 | |||
:param int batch_size: batch的大小 | |||
:param int batch_size: batch的大小. 默认为None,Trainer在调用BucketSampler时,会将该值正确设置,如果是非Trainer场景使用,需 | |||
要显示传递该值 | |||
:param str seq_len_field_name: 对应序列长度的 `field` 的名字 | |||
""" | |||
def __init__(self, num_buckets=10, batch_size=32, seq_len_field_name='seq_len'): | |||
def __init__(self, num_buckets=10, batch_size=None, seq_len_field_name='seq_len'): | |||
self.num_buckets = num_buckets | |||
self.batch_size = batch_size | |||
self.seq_len_field_name = seq_len_field_name | |||
def set_batch_size(self, batch_size): | |||
""" | |||
:param int batch_size: 每个batch的大小 | |||
:return: | |||
""" | |||
self.batch_size = batch_size | |||
def __call__(self, data_set): | |||
if self.batch_size is None: | |||
raise RuntimeError("batch_size is None.") | |||
seq_lens = data_set.get_all_fields()[self.seq_len_field_name].content | |||
total_sample_num = len(seq_lens) | |||
@@ -1,7 +1,7 @@ | |||
""" | |||
tester模块实现了 fastNLP 所需的Tester类,能在提供数据、模型以及metric的情况下进行性能测试。 | |||
Example:: | |||
.. code-block:: | |||
import numpy as np | |||
import torch | |||
@@ -32,9 +32,16 @@ Tester在验证进行之前会调用model.eval()提示当前进入了evaluation | |||
""" | |||
import time | |||
import torch | |||
import torch.nn as nn | |||
try: | |||
from tqdm.auto import tqdm | |||
except: | |||
from .utils import _pseudo_tqdm as tqdm | |||
from .batch import BatchIter, DataSetIter | |||
from .dataset import DataSet | |||
from .metrics import _prepare_metrics | |||
@@ -47,6 +54,7 @@ from .utils import _get_func_signature | |||
from .utils import _get_model_device | |||
from .utils import _move_model_to_device | |||
from ._parallel_utils import _data_parallel_wrapper | |||
from ._parallel_utils import _model_contains_inner_module | |||
from functools import partial | |||
__all__ = [ | |||
@@ -60,15 +68,14 @@ class Tester(object): | |||
Tester是在提供数据,模型以及metric的情况下进行性能测试的类。需要传入模型,数据以及metric进行验证。 | |||
:param data: 需要测试的数据集, :class:`~fastNLP.DataSet` 类型 | |||
:param ~fastNLP.DataSet data: 需要测试的数据集 | |||
:param torch.nn.module model: 使用的模型 | |||
:param metrics: :class:`~fastNLP.core.metrics.MetricBase` 或者一个列表的 :class:`~fastNLP.core.metrics.MetricBase` | |||
:param ~fastNLP.core.metrics.MetricBase,List[~fastNLP.core.metrics.MetricBase] metrics: 测试时使用的metrics | |||
:param int batch_size: evaluation时使用的batch_size有多大。 | |||
:param str,int,torch.device,list(int) device: 将模型load到哪个设备。默认为None,即Trainer不对模型 | |||
的计算位置进行管理。支持以下的输入: | |||
1. str: ['cpu', 'cuda', 'cuda:0', 'cuda:1', ...] 依次为'cpu'中, 可见的第一个GPU中, 可见的第一个GPU中, | |||
可见的第二个GPU中; | |||
1. str: ['cpu', 'cuda', 'cuda:0', 'cuda:1', ...] 依次为'cpu'中, 可见的第一个GPU中,可见的第一个GPU中,可见的第二个GPU中; | |||
2. torch.device:将模型装载到torch.device上。 | |||
@@ -80,13 +87,12 @@ class Tester(object): | |||
如果模型是通过predict()进行预测的话,那么将不能使用多卡(DataParallel)进行验证,只会使用第一张卡上的模型。 | |||
:param int verbose: 如果为0不输出任何信息; 如果为1,打印出验证结果。 | |||
:param bool use_tqdm: 是否使用tqdm来显示测试进度; 如果为False,则不会显示任何内容。 | |||
""" | |||
def __init__(self, data, model, metrics, batch_size=16, num_workers=0, device=None, verbose=1): | |||
def __init__(self, data, model, metrics, batch_size=16, num_workers=0, device=None, verbose=1, use_tqdm=True): | |||
super(Tester, self).__init__() | |||
if not isinstance(data, DataSet): | |||
raise TypeError(f"The type of data must be `fastNLP.DataSet`, got `{type(data)}`.") | |||
if not isinstance(model, nn.Module): | |||
raise TypeError(f"The type of model must be `torch.nn.Module`, got `{type(model)}`.") | |||
@@ -96,6 +102,7 @@ class Tester(object): | |||
self._model = _move_model_to_device(model, device=device) | |||
self.batch_size = batch_size | |||
self.verbose = verbose | |||
self.use_tqdm = use_tqdm | |||
if isinstance(data, DataSet): | |||
self.data_iterator = DataSetIter( | |||
@@ -107,19 +114,22 @@ class Tester(object): | |||
# check predict | |||
if (hasattr(self._model, 'predict') and callable(self._model.predict)) or \ | |||
(isinstance(self._model, nn.DataParallel) and hasattr(self._model.module, 'predict') and | |||
callable(self._model.module.predict)): | |||
(_model_contains_inner_module(self._model) and hasattr(self._model.module, 'predict') and | |||
callable(self._model.module.predict)): | |||
if isinstance(self._model, nn.DataParallel): | |||
self._predict_func_wrapper = partial(_data_parallel_wrapper('predict', | |||
self._model.device_ids, | |||
self._model.output_device), | |||
network=self._model.module) | |||
self._predict_func = self._model.module.predict # 用于匹配参数 | |||
elif isinstance(self._model, nn.parallel.DistributedDataParallel): | |||
self._predict_func = self._model.module.predict | |||
self._predict_func_wrapper = self._model.module.predict # 用于调用 | |||
else: | |||
self._predict_func = self._model.predict | |||
self._predict_func_wrapper = self._model.predict | |||
else: | |||
if isinstance(self._model, nn.DataParallel): | |||
if _model_contains_inner_module(model): | |||
self._predict_func_wrapper = self._model.forward | |||
self._predict_func = self._model.module.forward | |||
else: | |||
@@ -140,21 +150,39 @@ class Tester(object): | |||
eval_results = {} | |||
try: | |||
with torch.no_grad(): | |||
for batch_x, batch_y in data_iterator: | |||
_move_dict_value_to_device(batch_x, batch_y, device=self._model_device) | |||
pred_dict = self._data_forward(self._predict_func, batch_x) | |||
if not isinstance(pred_dict, dict): | |||
raise TypeError(f"The return value of {_get_func_signature(self._predict_func)} " | |||
f"must be `dict`, got {type(pred_dict)}.") | |||
if not self.use_tqdm: | |||
from .utils import _pseudo_tqdm as inner_tqdm | |||
else: | |||
inner_tqdm = tqdm | |||
with inner_tqdm(total=len(data_iterator), leave=False, dynamic_ncols=True) as pbar: | |||
pbar.set_description_str(desc="Test") | |||
start_time = time.time() | |||
for batch_x, batch_y in data_iterator: | |||
_move_dict_value_to_device(batch_x, batch_y, device=self._model_device) | |||
pred_dict = self._data_forward(self._predict_func, batch_x) | |||
if not isinstance(pred_dict, dict): | |||
raise TypeError(f"The return value of {_get_func_signature(self._predict_func)} " | |||
f"must be `dict`, got {type(pred_dict)}.") | |||
for metric in self.metrics: | |||
metric(pred_dict, batch_y) | |||
if self.use_tqdm: | |||
pbar.update() | |||
for metric in self.metrics: | |||
metric(pred_dict, batch_y) | |||
for metric in self.metrics: | |||
eval_result = metric.get_metric() | |||
if not isinstance(eval_result, dict): | |||
raise TypeError(f"The return value of {_get_func_signature(metric.get_metric)} must be " | |||
f"`dict`, got {type(eval_result)}") | |||
metric_name = metric.__class__.__name__ | |||
eval_results[metric_name] = eval_result | |||
eval_result = metric.get_metric() | |||
if not isinstance(eval_result, dict): | |||
raise TypeError(f"The return value of {_get_func_signature(metric.get_metric)} must be " | |||
f"`dict`, got {type(eval_result)}") | |||
metric_name = metric.__class__.__name__ | |||
eval_results[metric_name] = eval_result | |||
end_time = time.time() | |||
test_str = f'Evaluate data in {round(end_time - start_time, 2)} seconds!' | |||
pbar.write(test_str) | |||
pbar.close() | |||
except _CheckError as e: | |||
prev_func_signature = _get_func_signature(self._predict_func) | |||
_check_loss_evaluate(prev_func_signature=prev_func_signature, func_signature=e.func_signature, | |||
@@ -11,288 +11,310 @@ Trainer在fastNLP中用于组织单任务的训练过程,可以避免用户在 | |||
(5) 保存获得更好验证性能的模型。 | |||
1 Trainer的基本使用 | |||
下面的例子是使用神经网络来进行预测一个序列中是否有偶数个1。 | |||
Example:: | |||
import numpy as np | |||
from torch import nn | |||
import torch | |||
import torch.nn.functional as F | |||
from torch.optim import SGD | |||
from fastNLP import DataSet | |||
from fastNLP import Trainer | |||
from fastNLP import CrossEntropyLoss | |||
from fastNLP import AccuracyMetric | |||
from fastNLP.modules.decoder import MLP | |||
# 模型 | |||
class Model(nn.Module): | |||
def __init__(self, input_num): | |||
super().__init__() | |||
self.fcs = MLP([input_num, 40, 40, 2], 'relu') | |||
def forward(self, x): | |||
x = self.fcs(x) | |||
return {'pred': x} | |||
model = Model(10) | |||
# 生成数据 | |||
def generate_psedo_dataset(num_samples): | |||
dataset = DataSet() | |||
data = np.random.randint(2, size=(num_samples, 10)) | |||
label = np.sum(data, axis=1)%2 | |||
dataset = DataSet({'x':data.astype(float), 'label': label}) | |||
dataset.set_input('x') | |||
dataset.set_target('label') | |||
return dataset | |||
tr_dataset = generate_psedo_dataset(1000) | |||
dev_data = generate_psedo_dataset(100) | |||
# 训练 | |||
trainer = Trainer(tr_dataset, model, loss=CrossEntropyLoss(target='label'), | |||
optimizer=SGD(model.parameters(), lr=0.1),n_epochs=1000, | |||
dev_data = dev_data, metrics=AccuracyMetric(target='label')) | |||
trainer.train() | |||
由上面的例子可以看出通过使用Trainer,可以使得训练部分的代码大幅减少。 | |||
使用Trainer需要满足以下几个条件: | |||
---------------------------- | |||
1. Trainer的基本使用 | |||
---------------------------- | |||
下面的例子是使用神经网络来进行预测一个序列中是否有偶数个1。 | |||
.. code-block:: python | |||
import numpy as np | |||
from torch import nn | |||
import torch | |||
import torch.nn.functional as F | |||
from torch.optim import SGD | |||
from fastNLP import DataSet | |||
from fastNLP import Trainer | |||
from fastNLP import CrossEntropyLoss | |||
from fastNLP import AccuracyMetric | |||
from fastNLP.modules.decoder import MLP | |||
# 模型 | |||
class Model(nn.Module): | |||
def __init__(self, input_num): | |||
super().__init__() | |||
self.fcs = MLP([input_num, 40, 40, 2], 'relu') | |||
def forward(self, x): | |||
x = self.fcs(x) | |||
return {'pred': x} | |||
model = Model(10) | |||
# 生成数据 | |||
def generate_psedo_dataset(num_samples): | |||
dataset = DataSet() | |||
data = np.random.randint(2, size=(num_samples, 10)) | |||
label = np.sum(data, axis=1)%2 | |||
dataset = DataSet({'x':data.astype(float), 'label': label}) | |||
dataset.set_input('x') | |||
dataset.set_target('label') | |||
return dataset | |||
tr_dataset = generate_psedo_dataset(1000) | |||
dev_data = generate_psedo_dataset(100) | |||
# 训练 | |||
trainer = Trainer(tr_dataset, model, loss=CrossEntropyLoss(target='label'), | |||
optimizer=SGD(model.parameters(), lr=0.1),n_epochs=1000, | |||
dev_data = dev_data, metrics=AccuracyMetric(target='label')) | |||
trainer.train() | |||
由上面的例子可以看出通过使用Trainer,可以使得训练部分的代码大幅减少。 | |||
使用Trainer需要满足以下几个条件: | |||
1.1 模型 | |||
1 模型的forward()的参数名需要与DataSet中的名字对应。实际上fastNLP在将DataSet中的数据传递给模型forward()时,是 | |||
通过匹配名称实现的。所以上例中,如果Model的forward函数修改为forward(self, data), 则DataSet中的'x'这个field就应该 | |||
改名为'data'。 | |||
---------------------------- | |||
1 模型的forward()的参数名需要与DataSet中的名字对应。实际上fastNLP在将DataSet中的数据传递给模型forward()时,是 | |||
通过匹配名称实现的。所以上例中,如果Model的forward函数修改为forward(self, data), 则DataSet中的'x'这个field就应该 | |||
改名为'data'。 | |||
2 传递给forward()的参数是DataSet中被设置为input的那些field。但如果forward()中没有对应的参数,则不会将数据传递 | |||
给forward()。例如,DataSet中'x1', 'x2'都是input,但是模型的函数为forward(self, x1), 那么'x2'不会传递给forward()。 | |||
2 传递给forward()的参数是DataSet中被设置为input的那些field。但如果forward()中没有对应的参数,则不会将数据传递 | |||
给forward()。例如,DataSet中'x1', 'x2'都是input,但是模型的函数为forward(self, x1), 那么'x2'不会传递给forward()。 | |||
3 模型的forward()返回值需要为一个dict。 | |||
3 模型的forward()返回值需要为一个dict。 | |||
1.2 Loss | |||
fastNLP中的为了不限制forward函数的返回内容数量(比如一些复杂任务需要返回多个内容,如Dependency Parsing, | |||
:mod:`Loss<fastNLP.core.losses>` 与 :mod:`Metric<fastNLP.core.metrics>` 都使用了通过名称来匹配相应内容的策略。如上面的例子中 | |||
---------------------------- | |||
Example:: | |||
fastNLP中的为了不限制forward函数的返回内容数量(比如一些复杂任务需要返回多个内容,如Dependency Parsing, | |||
:mod:`Loss<fastNLP.core.losses>` 与 :mod:`Metric<fastNLP.core.metrics>` 都使用了通过名称来匹配相应内容的策略。如上面的例子中 | |||
trainer = Trainer(tr_dataset, model, loss=CrossEntropyLoss(target='label'), | |||
optimizer=SGD(model.parameters(), lr=0.1),n_epochs=1000, | |||
dev_data = dev_data, metrics=AccuracyMetric(target='label')) | |||
.. code-block:: python | |||
loss被设置为了 :class:`~fastNLP.CrossEntropyLoss` , 但在初始化的时候传入了target='label'这个参数, | |||
:class:`~fastNLP.CrossEntropyLoss` 的初始化参数为(pred=None, target=None, padding_idx=-100)。 | |||
这里的两个参数分别为计算CrossEntropy时需要使用到的模型的预测值与真实值。 | |||
其中 `pred` 一般来自于模型forward()的返回结果,`target` 一般是来自于DataSet中被设置为target的field。 | |||
由于每个人对真实值或者model的返回值取名并不一样,所以fastNLP的 :mod:`Loss<fastNLP.core.losses>` 提供一种类似于映射的机制来匹配对应的值, | |||
比如这里 :class:`~fastNLP.CrossEntropyLoss` 将尝试找到名为'label'的内容来作为真实值得到loss; | |||
而pred=None, 则 :class:`~fastNLP.CrossEntropyLoss` 使用'pred'作为名称匹配预测值, | |||
正好forward的返回值也叫pred,所以这里不需要申明pred。 | |||
尽管fastNLP使用了映射机制来使得loss的计算变得比较灵活,但有些情况下loss必须在模型中进行计算,比如使用了CRF的模型。 | |||
fastNLP中提供了 :class:`~fastNLP.LossInForward` 这个loss。 | |||
这个loss的原理是直接在forward()的返回结果中找到loss_key(默认寻找'loss')指定的那个tensor,并使用它作为loss。 | |||
如果Trainer初始化没有提供loss则默认使用 :class:`~fastNLP.LossInForward` 。 | |||
.. todo:: | |||
补充一个例子 详细例子可以参照 | |||
trainer = Trainer(tr_dataset, model, loss=CrossEntropyLoss(target='label'), | |||
optimizer=SGD(model.parameters(), lr=0.1),n_epochs=1000, | |||
dev_data = dev_data, metrics=AccuracyMetric(target='label')) | |||
loss被设置为了 :class:`~fastNLP.CrossEntropyLoss` , 但在初始化的时候传入了target='label'这个参数, | |||
:class:`~fastNLP.CrossEntropyLoss` 的初始化参数为(pred=None, target=None, padding_idx=-100)。 | |||
这里的两个参数分别为计算CrossEntropy时需要使用到的模型的预测值与真实值。 | |||
其中 `pred` 一般来自于模型forward()的返回结果,`target` 一般是来自于DataSet中被设置为target的field。 | |||
由于每个人对真实值或者model的返回值取名并不一样,所以fastNLP的 :mod:`Loss<fastNLP.core.losses>` 提供一种类似于映射的机制来匹配对应的值, | |||
比如这里 :class:`~fastNLP.CrossEntropyLoss` 将尝试找到名为'label'的内容来作为真实值得到loss; | |||
而pred=None, 则 :class:`~fastNLP.CrossEntropyLoss` 使用'pred'作为名称匹配预测值, | |||
正好forward的返回值也叫pred,所以这里不需要申明pred。 | |||
尽管fastNLP使用了映射机制来使得loss的计算变得比较灵活,但有些情况下loss必须在模型中进行计算,比如使用了CRF的模型。 | |||
fastNLP中提供了 :class:`~fastNLP.LossInForward` 这个loss。 | |||
这个loss的原理是直接在forward()的返回结果中找到loss_key(默认寻找'loss')指定的那个tensor,并使用它作为loss。 | |||
如果Trainer初始化没有提供loss则默认使用 :class:`~fastNLP.LossInForward` 。 | |||
.. todo:: | |||
补充一个例子 详细例子可以参照 | |||
1.3 Metric | |||
:mod:`Metric<fastNLP.core.metrics>` 使用了与上述Loss一样的策略,即使用名称进行匹配。 | |||
AccuracyMetric(target='label')的情况与CrossEntropyLoss 是同理的。 | |||
在进行验证时,可能用到的计算与forward()中不太一致,没有办法直接从forward()的结果中得到预测值,这时模型可以提供一个predict()方法, | |||
如果提供的模型具有predict方法,则在模型验证时将调用predict()方法获取预测结果, | |||
传入到predict()的参数也是从DataSet中被设置为input的field中选择出来的; | |||
与forward()一样,返回值需要为一个dict。 | |||
---------------------------- | |||
:mod:`Metric<fastNLP.core.metrics>` 使用了与上述Loss一样的策略,即使用名称进行匹配。 | |||
AccuracyMetric(target='label')的情况与CrossEntropyLoss 是同理的。 | |||
在进行验证时,可能用到的计算与forward()中不太一致,没有办法直接从forward()的结果中得到预测值,这时模型可以提供一个predict()方法, | |||
如果提供的模型具有predict方法,则在模型验证时将调用predict()方法获取预测结果, | |||
传入到predict()的参数也是从DataSet中被设置为input的field中选择出来的; | |||
与forward()一样,返回值需要为一个dict。 | |||
.. todo:: | |||
补充一个例子 具体例子可以参考 | |||
.. todo:: | |||
补充一个例子 具体例子可以参考 | |||
---------------------------- | |||
2. Trainer的代码检查 | |||
---------------------------- | |||
2 Trainer的代码检查 | |||
由于在fastNLP中采取了映射的机制,所以难免可能存在对应出错的情况。Trainer提供一种映射检查机制,可以通过check_code_level来进行控制 | |||
比如下面的例子中,由于各种原因产生的报错 | |||
由于在fastNLP中采取了映射的机制,所以难免可能存在对应出错的情况。Trainer提供一种映射检查机制,可以通过check_code_level来进行控制 | |||
比如下面的例子中,由于各种原因产生的报错 | |||
Example2.1 | |||
:: | |||
import numpy as np | |||
from torch import nn | |||
import torch | |||
from torch.optim import SGD | |||
from fastNLP import Trainer | |||
from fastNLP import DataSet | |||
class Model(nn.Module): | |||
def __init__(self): | |||
super().__init__() | |||
self.fc = nn.Linear(1, 1) | |||
def forward(self, x, b): | |||
loss = torch.mean((self.fc(x)-b)**2) | |||
return {'loss': loss} | |||
model = Model() | |||
dataset = DataSet({'a': np.arange(10), 'b':np.arange(10)*2}) | |||
dataset.set_input('a', 'b') | |||
trainer = Trainer(dataset, model, loss=None, optimizer=SGD(model.parameters(), lr=0.001)) | |||
trainer = Trainer(dataset, model, SGD(model.parameters())) | |||
# 会报以下的错误 | |||
# input fields after batch(if batch size is 2): | |||
# a: (1)type:torch.Tensor (2)dtype:torch.int64, (3)shape:torch.Size([2]) | |||
# b: (1)type:torch.Tensor (2)dtype:torch.int64, (3)shape:torch.Size([2]) | |||
# There is no target field. | |||
# .... | |||
# NameError: | |||
# Problems occurred when calling Model.forward(self, x, b) | |||
# missing param: ['x'] | |||
# unused field: ['a'] | |||
# Suggestion: You need to provide ['x'] in DataSet and set it as input. | |||
这里就是由于在Trainer初始化的时候,fastNLP会尝试使用一个batch_size=2的batch去运行一遍forward()以及backward()。这里有两类 | |||
信息可以为你提供参考 | |||
1 'input fields after batch...'这部分显示的是train dataset经过Batch操作后,每个field对应的类型以及进行shape。这里 | |||
因为train dataset没有target所以没有显示。根据这里可以看出是否正确将需要的内容设置为了input或target。 | |||
2 NameError,NameError发生在映射出错的情况。这里报错的原因是由于尝试进行forward计算时(可以通过Model.forward(self, x, b)判断 | |||
出当前是在调取forward),却没有获取到forward()函数中需要的'x';在报错信息中同时指出了缺'x',而'a'没有被使用,那么可能 | |||
就是由于field的名称不对。这里将dataset中'a'这个field的名称改为'x',或者model的参数从'x'修改为'a'都可以解决问题。 | |||
下面的例子是由于loss计算的时候找不到需要的值 | |||
---------------------------- | |||
.. code-block:: python | |||
import numpy as np | |||
from torch import nn | |||
import torch | |||
from torch.optim import SGD | |||
from fastNLP import Trainer | |||
from fastNLP import DataSet | |||
class Model(nn.Module): | |||
def __init__(self): | |||
super().__init__() | |||
self.fc = nn.Linear(1, 1) | |||
def forward(self, x, b): | |||
loss = torch.mean((self.fc(x)-b)**2) | |||
return {'loss': loss} | |||
model = Model() | |||
dataset = DataSet({'a': np.arange(10), 'b':np.arange(10)*2}) | |||
dataset.set_input('a', 'b') | |||
trainer = Trainer(dataset, model, loss=None, optimizer=SGD(model.parameters(), lr=0.001)) | |||
trainer = Trainer(dataset, model, SGD(model.parameters())) | |||
# 会报以下的错误 | |||
# input fields after batch(if batch size is 2): | |||
# a: (1)type:torch.Tensor (2)dtype:torch.int64, (3)shape:torch.Size([2]) | |||
# b: (1)type:torch.Tensor (2)dtype:torch.int64, (3)shape:torch.Size([2]) | |||
# There is no target field. | |||
# .... | |||
# NameError: | |||
# Problems occurred when calling Model.forward(self, x, b) | |||
# missing param: ['x'] | |||
# unused field: ['a'] | |||
# Suggestion: You need to provide ['x'] in DataSet and set it as input. | |||
这里就是由于在Trainer初始化的时候,fastNLP会尝试使用一个batch_size=2的batch去运行一遍forward()以及backward()。这里有两类 | |||
信息可以为你提供参考 | |||
1 'input fields after batch...'这部分显示的是train dataset经过Batch操作后,每个field对应的类型以及进行shape。这里 | |||
因为train dataset没有target所以没有显示。根据这里可以看出是否正确将需要的内容设置为了input或target。 | |||
2 NameError,NameError发生在映射出错的情况。这里报错的原因是由于尝试进行forward计算时(可以通过Model.forward(self, x, b)判断 | |||
出当前是在调取forward),却没有获取到forward()函数中需要的'x';在报错信息中同时指出了缺'x',而'a'没有被使用,那么可能 | |||
就是由于field的名称不对。这里将dataset中'a'这个field的名称改为'x',或者model的参数从'x'修改为'a'都可以解决问题。 | |||
下面的例子是由于loss计算的时候找不到需要的值 | |||
Example2.2 | |||
:: | |||
import numpy as np | |||
from torch import nn | |||
from torch.optim import SGD | |||
from fastNLP import Trainer | |||
from fastNLP import DataSet | |||
from fastNLP import L1Loss | |||
import torch | |||
class Model(nn.Module): | |||
def __init__(self): | |||
super().__init__() | |||
self.fc = nn.Linear(1, 1) | |||
def forward(self, a): | |||
return {'pred_b': self.fc(a.unsqueeze(1)).squeeze(1), 'No use':1} | |||
model = Model() | |||
dataset = DataSet({'a': np.arange(10, dtype=float), 'b':np.arange(10, dtype=float)*2}) | |||
dataset.set_input('a') | |||
dataset.set_target('b') | |||
trainer = Trainer(dataset, model, loss=L1Loss(target='label'), optimizer=SGD(model.parameters(), lr=0.001)) | |||
# 报错信息如下 | |||
# input fields after batch(if batch size is 2): | |||
# a: (1)type:torch.Tensor (2)dtype:torch.float32, (3)shape:torch.Size([2]) | |||
# target fields after batch(if batch size is 2): | |||
# b: (1)type:torch.Tensor (2)dtype:torch.float32, (3)shape:torch.Size([2]) | |||
# .... | |||
# NameError: | |||
# Problems occurred when calling L1Loss.get_loss(self, pred, target) | |||
# missing param: ['pred(assign to `pred` in `L1Loss`)', 'label(assign to `target` in `L1Loss`)'] | |||
# unused field: ['b'] | |||
# unused param: ['pred_b', 'No use'] | |||
# target field: ['b'] | |||
# param from Model.forward(self, a): ['pred_b', 'No use'] | |||
# Suggestion: (1). Check key assignment for `target` when initialize L1Loss. Or provide `label` in DataSet or output of Model.forward(self, a). | |||
# (2). Check key assignment for `pred` when initialize L1Loss. Or provide `pred` in DataSet or output of Model.forward(self, a). | |||
报错信息也包含两部分: | |||
1 第一部分与上面是一样的 | |||
2 这里报错的原因是由于计算loss的时候找不到相应的值(通过L1Loss.get_loss(self, pred, target)判断出来的); | |||
报错的原因是因为 `pred` 和 `label` (我们在初始化L1Loss时将target指定为了label)都没有找到。 | |||
这里'unused field'是DataSet中出现了,但却没有被设置为input或者target的field; | |||
'unused param'是forward()中返回且没有被使用到的内容;'target field'是被设置为了target的field; | |||
'param from Model.forward(self, a)'是forward()返回的所有key。"Suggestion"是关于当前错误处理的建议。 | |||
但是在一些情况下,比如forward()返回值只有一个,target也只有一个,fastNLP不会进行匹配,而直接将forward()的结果作为pred, | |||
将DataSet中的target设置为target。上面的例子在返回值中加入了一个'No use'则只是为了使得Loss去匹配结果。 | |||
下面是带有dev dataset时如果出现错误会发生的报错, | |||
---------------------------- | |||
.. code-block:: python | |||
import numpy as np | |||
from torch import nn | |||
from torch.optim import SGD | |||
from fastNLP import Trainer | |||
from fastNLP import DataSet | |||
from fastNLP import L1Loss | |||
import torch | |||
class Model(nn.Module): | |||
def __init__(self): | |||
super().__init__() | |||
self.fc = nn.Linear(1, 1) | |||
def forward(self, a): | |||
return {'pred_b': self.fc(a.unsqueeze(1)).squeeze(1), 'No use':1} | |||
model = Model() | |||
dataset = DataSet({'a': np.arange(10, dtype=float), 'b':np.arange(10, dtype=float)*2}) | |||
dataset.set_input('a') | |||
dataset.set_target('b') | |||
trainer = Trainer(dataset, model, loss=L1Loss(target='label'), optimizer=SGD(model.parameters(), lr=0.001)) | |||
# 报错信息如下 | |||
# input fields after batch(if batch size is 2): | |||
# a: (1)type:torch.Tensor (2)dtype:torch.float32, (3)shape:torch.Size([2]) | |||
# target fields after batch(if batch size is 2): | |||
# b: (1)type:torch.Tensor (2)dtype:torch.float32, (3)shape:torch.Size([2]) | |||
# .... | |||
# NameError: | |||
# Problems occurred when calling L1Loss.get_loss(self, pred, target) | |||
# missing param: ['pred(assign to `pred` in `L1Loss`)', 'label(assign to `target` in `L1Loss`)'] | |||
# unused field: ['b'] | |||
# unused param: ['pred_b', 'No use'] | |||
# target field: ['b'] | |||
# param from Model.forward(self, a): ['pred_b', 'No use'] | |||
# Suggestion: (1). Check key assignment for `target` when initialize L1Loss. Or provide `label` in DataSet or output of Model.forward(self, a). | |||
# (2). Check key assignment for `pred` when initialize L1Loss. Or provide `pred` in DataSet or output of Model.forward(self, a). | |||
报错信息也包含两部分: | |||
1 第一部分与上面是一样的 | |||
2 这里报错的原因是由于计算loss的时候找不到相应的值(通过L1Loss.get_loss(self, pred, target)判断出来的); | |||
报错的原因是因为 `pred` 和 `label` (我们在初始化L1Loss时将target指定为了label)都没有找到。 | |||
这里'unused field'是DataSet中出现了,但却没有被设置为input或者target的field; | |||
'unused param'是forward()中返回且没有被使用到的内容;'target field'是被设置为了target的field; | |||
'param from Model.forward(self, a)'是forward()返回的所有key。"Suggestion"是关于当前错误处理的建议。 | |||
但是在一些情况下,比如forward()返回值只有一个,target也只有一个,fastNLP不会进行匹配,而直接将forward()的结果作为pred, | |||
将DataSet中的target设置为target。上面的例子在返回值中加入了一个'No use'则只是为了使得Loss去匹配结果。 | |||
下面是带有dev dataset时如果出现错误会发生的报错, | |||
Example2.3 | |||
:: | |||
---------------------------- | |||
.. code-block:: python | |||
import numpy as np | |||
from torch import nn | |||
from torch.optim import SGD | |||
from fastNLP import Trainer | |||
from fastNLP import DataSet | |||
from fastNLP import AccuracyMetric | |||
import torch | |||
class Model(nn.Module): | |||
def __init__(self): | |||
super().__init__() | |||
self.fc = nn.Linear(1, 1) | |||
def forward(self, a, b): | |||
loss = torch.mean((self.fc(a.float().unsqueeze(1))-b.float())**2) | |||
return {'loss': loss} | |||
def predict(self, a): # 使用predict()进行验证 | |||
return {'output':self.fc(a.float().unsqueeze(1))} #这里return的值不包含'pred'这个key | |||
model = Model() | |||
dataset = DataSet({'a': np.arange(10), 'b':np.arange(10)*2}) | |||
dev_data = DataSet({'a': np.arange(10, 20), 'b':np.arange(10, 20)*2}) | |||
dataset.set_input('a', 'b') | |||
dev_data.set_input('a') # 这里没有设置target | |||
trainer = Trainer(dataset, model, loss=None, optimizer=SGD(model.parameters(), lr=0.001), | |||
dev_data=dev_data, metrics=AccuracyMetric()) | |||
# 报错信息 | |||
# ... | |||
# NameError: | |||
# Problems occurred when calling AccuracyMetric.evaluate(self, pred, target, seq_len=None) | |||
# missing param: ['pred(assign to `pred` in `AccuracyMetric`)', 'target(assign to `target` in `AccuracyMetric`)'] | |||
# unused param: ['output'] | |||
# target field: [] | |||
# param from Model.predict(self, a): ['output'] | |||
# Suggestion: (1). Check key assignment for `pred` when initialize AccuracyMetric. Or provide `pred` in DataSet or output of Model.predict(self, a). | |||
# (2). Check key assignment for `target` when initialize AccuracyMetric. Or provide `target` in DataSet or output of Model.predict(self, a). | |||
报错信息和前面都是类似的,但是可以通过'AccuracyMetric.evaluate(self, pred, target, seq_len=None)'看出这里是evaluation | |||
的时候发生了错误。这样避免了需要在完成一整个epoch的训练才能发现evaluation弄错的情况。这里的修改是通过在初始化metric的时候 | |||
指明通过'output'获取`pred`, 即AccuracyMetric(pred='output')。 | |||
可以通过check_code_level调节检查的强度。默认为0,即进行检查。 | |||
---------------------------- | |||
3. Trainer与callback | |||
---------------------------- | |||
虽然Trainer本身已经集成了一些功能,但仍然不足以囊括训练过程中可能需要到的功能,比如负采样,learning rate decay, Early Stop等。 | |||
为了解决这个问题fastNLP引入了callback的机制,:class:`~fastNLP.Callback` 是一种在Trainer训练过程中特定阶段会运行的函数集合, | |||
所有的 :class:`~fastNLP.Callback` 都具有on_*(比如on_train_start, on_backward_begin)等函数。 | |||
如果 Callback 实现了该函数,则Trainer运行至对应阶段,会进行调用,例如:: | |||
from fastNLP import Callback, EarlyStopCallback, Trainer, CrossEntropyLoss, AccuracyMetric | |||
from fastNLP.models import CNNText | |||
start_time = time.time() | |||
import numpy as np | |||
from torch import nn | |||
from torch.optim import SGD | |||
from fastNLP import Trainer | |||
from fastNLP import DataSet | |||
from fastNLP import AccuracyMetric | |||
import torch | |||
class Model(nn.Module): | |||
def __init__(self): | |||
super().__init__() | |||
self.fc = nn.Linear(1, 1) | |||
def forward(self, a, b): | |||
loss = torch.mean((self.fc(a.float().unsqueeze(1))-b.float())**2) | |||
return {'loss': loss} | |||
def predict(self, a): # 使用predict()进行验证 | |||
return {'output':self.fc(a.float().unsqueeze(1))} #这里return的值不包含'pred'这个key | |||
model = Model() | |||
dataset = DataSet({'a': np.arange(10), 'b':np.arange(10)*2}) | |||
dev_data = DataSet({'a': np.arange(10, 20), 'b':np.arange(10, 20)*2}) | |||
dataset.set_input('a', 'b') | |||
dev_data.set_input('a') # 这里没有设置target | |||
trainer = Trainer(dataset, model, loss=None, optimizer=SGD(model.parameters(), lr=0.001), | |||
dev_data=dev_data, metrics=AccuracyMetric()) | |||
# 报错信息 | |||
# ... | |||
# NameError: | |||
# Problems occurred when calling AccuracyMetric.evaluate(self, pred, target, seq_len=None) | |||
# missing param: ['pred(assign to `pred` in `AccuracyMetric`)', 'target(assign to `target` in `AccuracyMetric`)'] | |||
# unused param: ['output'] | |||
# target field: [] | |||
# param from Model.predict(self, a): ['output'] | |||
# Suggestion: (1). Check key assignment for `pred` when initialize AccuracyMetric. Or provide `pred` in DataSet or output of Model.predict(self, a). | |||
# (2). Check key assignment for `target` when initialize AccuracyMetric. Or provide `target` in DataSet or output of Model.predict(self, a). | |||
报错信息和前面都是类似的,但是可以通过'AccuracyMetric.evaluate(self, pred, target, seq_len=None)'看出这里是evaluation | |||
的时候发生了错误。这样避免了需要在完成一整个epoch的训练才能发现evaluation弄错的情况。这里的修改是通过在初始化metric的时候 | |||
指明通过'output'获取`pred`, 即AccuracyMetric(pred='output')。 | |||
可以通过check_code_level调节检查的强度。默认为0,即进行检查。 | |||
3 Trainer与callback | |||
虽然Trainer本身已经集成了一些功能,但仍然不足以囊括训练过程中可能需要到的功能,比如负采样,learning rate decay, Early Stop等。 | |||
为了解决这个问题fastNLP引入了callback的机制,:class:`~fastNLP.Callback` 是一种在Trainer训练过程中特定阶段会运行的函数集合, | |||
所有的 :class:`~fastNLP.Callback` 都具有on_*(比如on_train_start, on_backward_begin)等函数。 | |||
如果 Callback 实现了该函数,则Trainer运行至对应阶段,会进行调用,例如:: | |||
class MyCallback(Callback): | |||
def on_epoch_end(self): | |||
print('{:d}ms\n\n'.format(round((time.time()-start_time)*1000))) | |||
from fastNLP import Callback, EarlyStopCallback, Trainer, CrossEntropyLoss, AccuracyMetric | |||
from fastNLP.models import CNNText | |||
start_time = time.time() | |||
class MyCallback(Callback): | |||
def on_epoch_end(self): | |||
print('{:d}ms\n\n'.format(round((time.time()-start_time)*1000))) | |||
model = CNNText((len(vocab),50), num_classes=5, padding=2, dropout=0.1) | |||
trainer = Trainer(model=model, train_data=train_data, dev_data=dev_data, loss=CrossEntropyLoss(), | |||
metrics=AccuracyMetric(), callbacks=[MyCallback(),EarlyStopCallback(10)]) | |||
trainer.train() | |||
这里,我们通过继承 :class:`~fastNLP.Callback` 类定义了自己的 callback 的,并和内置的 :class:`~fastNLP.EarlyStopCallback` | |||
一起传给了 :class:`~fastNLP.Trainer` ,增强了 :class:`~fastNLP.Trainer` 的功能 | |||
model = CNNText((len(vocab),50), num_classes=5, padding=2, dropout=0.1) | |||
trainer = Trainer(model=model, train_data=train_data, dev_data=dev_data, loss=CrossEntropyLoss(), | |||
metrics=AccuracyMetric(), callbacks=[MyCallback(),EarlyStopCallback(10)]) | |||
trainer.train() | |||
fastNLP已经自带了很多callback函数供使用,可以参考 :doc:`fastNLP.core.callback` 。 | |||
这里,我们通过继承 :class:`~fastNLP.Callback` 类定义了自己的 callback 的,并和内置的 :class:`~fastNLP.EarlyStopCallback` | |||
一起传给了 :class:`~fastNLP.Trainer` ,增强了 :class:`~fastNLP.Trainer` 的功能 | |||
fastNLP已经自带了很多callback函数供使用,可以参考 :doc:`fastNLP.core.callback` 。 | |||
""" | |||
__all__ = [ | |||
@@ -330,6 +352,7 @@ from .utils import _move_dict_value_to_device | |||
from .utils import _get_func_signature | |||
from .utils import _get_model_device | |||
from .utils import _move_model_to_device | |||
from ._parallel_utils import _model_contains_inner_module | |||
class Trainer(object): | |||
@@ -367,8 +390,8 @@ class Trainer(object): | |||
要指定以哪个指标为准。另外有些指标是越小效果越好,比如语言模型的困惑度,这种情况下,在key前面增加一个'-'来表 | |||
明验证时,值越小越好(比如: "-ppl")。仅在传入dev_data时有效。 | |||
:param int validate_every: 多少个step在验证集上验证一次; 如果为-1,则每个epoch结束验证一次。仅在传入dev_data时有效。 | |||
:param str,None save_path: 将模型保存路径。如果为None,则不保存模型。如果dev_data为None,则保存最后一次迭代的模型。 | |||
保存的时候不仅保存了参数,还保存了模型结构。即便使用DataParallel,这里也只保存模型。 | |||
:param str,None save_path: 将模型保存路径,如果路径不存在,将自动创建文件夹。如果为None,则不保存模型。如果dev_data为None,则保存 | |||
最后一次迭代的模型。保存的时候不仅保存了参数,还保存了模型结构。即便使用DataParallel,这里也只保存模型。 | |||
:param bool use_tqdm: 是否使用tqdm来显示训练进度; 如果为False,则将loss打印在终端中。 | |||
:param str,int,torch.device,list(int) device: 将模型load到哪个设备。默认为None,即Trainer不对模型 | |||
的计算位置进行管理。支持以下的输入: | |||
@@ -408,23 +431,23 @@ class Trainer(object): | |||
super(Trainer, self).__init__() | |||
if not isinstance(model, nn.Module): | |||
raise TypeError(f"The type of model must be torch.nn.Module, got {type(model)}.") | |||
# check metrics and dev_data | |||
if (not metrics) and dev_data is not None: | |||
raise ValueError("No metric for dev_data evaluation.") | |||
if metrics and (dev_data is None): | |||
raise ValueError("No dev_data for evaluations, pass dev_data or set metrics to None. ") | |||
# check update every | |||
assert update_every >= 1, "update_every must be no less than 1." | |||
self.update_every = int(update_every) | |||
# check save_path | |||
if not (save_path is None or isinstance(save_path, str)): | |||
raise ValueError("save_path can only be None or `str`.") | |||
# prepare evaluate | |||
metrics = _prepare_metrics(metrics) | |||
# parse metric_key | |||
# increase_better is True. It means the exp result gets better if the indicator increases. | |||
# It is true by default. | |||
@@ -436,28 +459,69 @@ class Trainer(object): | |||
self.metric_key = None | |||
# prepare loss | |||
losser = _prepare_losser(loss) | |||
# sampler check | |||
if sampler is not None and not isinstance(sampler, Sampler): | |||
raise ValueError("The type of sampler should be fastNLP.BaseSampler, got {}.".format(type(sampler))) | |||
if sampler is None: | |||
sampler = RandomSampler() | |||
if isinstance(train_data, BatchIter): | |||
if sampler is not None: | |||
warnings.warn("sampler is ignored when train_data is a BatchIter.") | |||
if num_workers>0: | |||
warnings.warn("num_workers is ignored when train_data is BatchIter.") | |||
if drop_last: | |||
warnings.warn("drop_last is ignored when train_data is BatchIter.") | |||
if isinstance(model, nn.parallel.DistributedDataParallel): # 如果是分布式的 | |||
# device为None | |||
if device is not None: | |||
warnings.warn("device is ignored when model is nn.parallel.DistributedDataParallel.") | |||
device = None | |||
# Sampler要是分布式的 | |||
if sampler is None: | |||
sampler = torch.utils.data.DistributedSampler(train_data) | |||
elif not isinstance(sampler, torch.utils.data.DistributedSampler): | |||
raise TypeError("When using nn.parallel.DistributedDataParallel, " | |||
"sampler must be None or torch.utils.data.DistributedSampler.") | |||
# 不能保存模型 | |||
if save_path: | |||
raise RuntimeError("Saving model in Distributed situation is not allowed right now.") | |||
else: | |||
# sampler check | |||
if sampler is not None and not isinstance(sampler, (Sampler, torch.utils.data.Sampler)): | |||
raise ValueError(f"The type of sampler should be fastNLP.BaseSampler or pytorch's Sampler, got {type(sampler)}") | |||
if sampler is None: | |||
sampler = RandomSampler() | |||
elif hasattr(sampler, 'set_batch_size'): | |||
sampler.set_batch_size(batch_size) | |||
if isinstance(train_data, DataSet): | |||
self.data_iterator = DataSetIter( | |||
dataset=train_data, batch_size=batch_size, num_workers=num_workers, sampler=sampler, drop_last=drop_last) | |||
elif isinstance(train_data, BatchIter): | |||
self.data_iterator = train_data | |||
train_data = train_data.dataset | |||
else: | |||
raise TypeError("train_data type {} not support".format(type(train_data))) | |||
if check_code_level > -1 and isinstance(self.data_iterator, DataSetIter): | |||
_check_code(dataset=train_data, model=model, losser=losser, metrics=metrics, dev_data=dev_data, | |||
metric_key=self.metric_key, check_level=check_code_level, | |||
batch_size=min(batch_size, DEFAULT_CHECK_BATCH_SIZE)) | |||
# _check_code 是 fastNLP 帮助你检查代码是否正确的方法 。如果你在错误栈中看到这行注释,请认真检查你的代码 | |||
self.model = _move_model_to_device(model, device=device) | |||
if _model_contains_inner_module(self.model): | |||
self._forward_func = self.model.module.forward | |||
else: | |||
self._forward_func = self.model.forward | |||
if check_code_level > -1: | |||
# _check_code 是 fastNLP 帮助你检查代码是否正确的方法 。如果你在错误栈中看到这行注释,请认真检查你的field名与模型的输入 | |||
# 名是否匹配 | |||
dev_dataset = dev_data | |||
if isinstance(dev_data, BatchIter): | |||
dev_dataset = None | |||
warnings.warn("dev_data is of BatchIter type, ignore validation checking.") | |||
check_batch_size = min(batch_size, DEFAULT_CHECK_BATCH_SIZE) | |||
if isinstance(self.model, nn.DataParallel): | |||
_num_devices = len(self.model.device_ids) | |||
if batch_size//_num_devices>1: # 如果多卡是每个卡可以分多个数据的,则用每个卡给两个sample | |||
check_batch_size = max(len(self.model.device_ids)*2, check_batch_size) | |||
else: | |||
check_batch_size = max(len(self.model.device_ids), check_batch_size) | |||
_check_code(dataset=train_data, model=self.model, losser=losser, forward_func=self._forward_func, metrics=metrics, | |||
dev_data=dev_dataset, metric_key=self.metric_key, check_level=check_code_level, | |||
batch_size=check_batch_size) | |||
self.train_data = train_data | |||
self.dev_data = dev_data # If None, No validation. | |||
@@ -472,8 +536,7 @@ class Trainer(object): | |||
self.best_dev_epoch = None | |||
self.best_dev_step = None | |||
self.best_dev_perf = None | |||
self.n_steps = (len(self.train_data) // self.batch_size + int( | |||
len(self.train_data) % self.batch_size != 0)) * int(drop_last==0) * self.n_epochs | |||
self.n_steps = len(self.data_iterator) * self.n_epochs | |||
if isinstance(optimizer, torch.optim.Optimizer): | |||
self.optimizer = optimizer | |||
@@ -483,7 +546,7 @@ class Trainer(object): | |||
self.optimizer = torch.optim.Adam(self.model.parameters(), lr=4e-3) | |||
else: | |||
raise TypeError("optimizer can only be torch.optim.Optimizer type, not {}.".format(type(optimizer))) | |||
self.use_tqdm = use_tqdm | |||
self.pbar = None | |||
self.print_every = abs(self.print_every) | |||
@@ -494,11 +557,12 @@ class Trainer(object): | |||
metrics=self.metrics, | |||
batch_size=self.batch_size, | |||
device=None, # 由上面的部分处理device | |||
verbose=0) | |||
verbose=0, | |||
use_tqdm=self.use_tqdm) | |||
self.step = 0 | |||
self.start_time = None # start timestamp | |||
self.callback_manager = CallbackManager(env={"trainer": self}, | |||
callbacks=callbacks) | |||
@@ -534,7 +598,7 @@ class Trainer(object): | |||
self.start_time = str(datetime.now().strftime('%Y-%m-%d-%H-%M-%S')) | |||
start_time = time.time() | |||
print("training epochs started " + self.start_time, flush=True) | |||
try: | |||
self.callback_manager.on_train_begin() | |||
self._train() | |||
@@ -547,7 +611,7 @@ class Trainer(object): | |||
raise e | |||
elif on_exception == 'raise': | |||
raise e | |||
if self.dev_data is not None and self.best_dev_perf is not None: | |||
print( | |||
"\nIn Epoch:{}/Step:{}, got best dev performance:".format(self.best_dev_epoch, self.best_dev_step) + | |||
@@ -565,21 +629,17 @@ class Trainer(object): | |||
finally: | |||
pass | |||
results['seconds'] = round(time.time() - start_time, 2) | |||
return results | |||
def _train(self): | |||
if not self.use_tqdm: | |||
from fastNLP.core.utils import _pseudo_tqdm as inner_tqdm | |||
from .utils import _pseudo_tqdm as inner_tqdm | |||
else: | |||
inner_tqdm = tqdm | |||
self.step = 0 | |||
self.epoch = 0 | |||
start = time.time() | |||
if isinstance(self.model, nn.DataParallel): | |||
self._forward_func = self.model.module.forward | |||
else: | |||
self._forward_func = self.model.forward | |||
with inner_tqdm(total=self.n_steps, postfix='loss:{0:<6.5f}', leave=False, dynamic_ncols=True) as pbar: | |||
self.pbar = pbar | |||
avg_loss = 0 | |||
@@ -597,21 +657,21 @@ class Trainer(object): | |||
# negative sampling; replace unknown; re-weight batch_y | |||
self.callback_manager.on_batch_begin(batch_x, batch_y, indices) | |||
prediction = self._data_forward(self.model, batch_x) | |||
# edit prediction | |||
self.callback_manager.on_loss_begin(batch_y, prediction) | |||
loss = self._compute_loss(prediction, batch_y).mean() | |||
avg_loss += loss.item() | |||
loss = loss / self.update_every | |||
# Is loss NaN or inf? requires_grad = False | |||
self.callback_manager.on_backward_begin(loss) | |||
self._grad_backward(loss) | |||
self.callback_manager.on_backward_end() | |||
self._update() | |||
self.callback_manager.on_step_end() | |||
if self.step % self.print_every == 0: | |||
avg_loss = float(avg_loss) / self.print_every | |||
if self.use_tqdm: | |||
@@ -625,7 +685,7 @@ class Trainer(object): | |||
pbar.set_postfix_str(print_output) | |||
avg_loss = 0 | |||
self.callback_manager.on_batch_end() | |||
if ((self.validate_every > 0 and self.step % self.validate_every == 0) or | |||
(self.validate_every < 0 and self.step % len(data_iterator) == 0)) \ | |||
and self.dev_data is not None: | |||
@@ -634,20 +694,20 @@ class Trainer(object): | |||
self.n_steps) + \ | |||
self.tester._format_eval_results(eval_res) | |||
pbar.write(eval_str + '\n') | |||
# ================= mini-batch end ==================== # | |||
# lr decay; early stopping | |||
self.callback_manager.on_epoch_end() | |||
# =============== epochs end =================== # | |||
pbar.close() | |||
self.pbar = None | |||
# ============ tqdm end ============== # | |||
def _do_validation(self, epoch, step): | |||
self.callback_manager.on_valid_begin() | |||
res = self.tester.test() | |||
is_better_eval = False | |||
if self._better_eval_result(res): | |||
if self.save_path is not None: | |||
@@ -662,7 +722,7 @@ class Trainer(object): | |||
# get validation results; adjust optimizer | |||
self.callback_manager.on_valid_end(res, self.metric_key, self.optimizer, is_better_eval) | |||
return res | |||
def _mode(self, model, is_test=False): | |||
"""Train mode or Test mode. This is for PyTorch currently. | |||
@@ -674,14 +734,14 @@ class Trainer(object): | |||
model.eval() | |||
else: | |||
model.train() | |||
def _update(self): | |||
"""Perform weight update on a model. | |||
""" | |||
if self.step % self.update_every == 0: | |||
self.optimizer.step() | |||
def _data_forward(self, network, x): | |||
x = _build_args(self._forward_func, **x) | |||
y = network(**x) | |||
@@ -689,7 +749,7 @@ class Trainer(object): | |||
raise TypeError( | |||
f"The return value of {_get_func_signature(self._forward_func)} should be dict, got {type(y)}.") | |||
return y | |||
def _grad_backward(self, loss): | |||
"""Compute gradient with link rules. | |||
@@ -700,7 +760,7 @@ class Trainer(object): | |||
if (self.step-1) % self.update_every == 0: | |||
self.model.zero_grad() | |||
loss.backward() | |||
def _compute_loss(self, predict, truth): | |||
"""Compute loss given prediction and ground truth. | |||
@@ -709,7 +769,7 @@ class Trainer(object): | |||
:return: a scalar | |||
""" | |||
return self.losser(predict, truth) | |||
def _save_model(self, model, model_name, only_param=False): | |||
""" 存储不含有显卡信息的state_dict或model | |||
:param model: | |||
@@ -721,7 +781,7 @@ class Trainer(object): | |||
model_path = os.path.join(self.save_path, model_name) | |||
if not os.path.exists(self.save_path): | |||
os.makedirs(self.save_path, exist_ok=True) | |||
if isinstance(model, nn.DataParallel): | |||
if _model_contains_inner_module(model): | |||
model = model.module | |||
if only_param: | |||
state_dict = model.state_dict() | |||
@@ -732,7 +792,7 @@ class Trainer(object): | |||
model.cpu() | |||
torch.save(model, model_path) | |||
model.to(self._model_device) | |||
def _load_model(self, model, model_name, only_param=False): | |||
# 返回bool值指示是否成功reload模型 | |||
if self.save_path is not None: | |||
@@ -741,7 +801,7 @@ class Trainer(object): | |||
states = torch.load(model_path) | |||
else: | |||
states = torch.load(model_path).state_dict() | |||
if isinstance(model, nn.DataParallel): | |||
if _model_contains_inner_module(model): | |||
model.module.load_state_dict(states) | |||
else: | |||
model.load_state_dict(states) | |||
@@ -750,7 +810,7 @@ class Trainer(object): | |||
else: | |||
return False | |||
return True | |||
def _better_eval_result(self, metrics): | |||
"""Check if the current epoch yields better validation results. | |||
@@ -776,6 +836,9 @@ class Trainer(object): | |||
is_better = False | |||
return is_better | |||
@property | |||
def is_master(self): | |||
return True | |||
DEFAULT_CHECK_BATCH_SIZE = 2 | |||
DEFAULT_CHECK_NUM_BATCH = 2 | |||
@@ -797,14 +860,15 @@ def _get_value_info(_dict): | |||
strs.append(_str) | |||
return strs | |||
from numbers import Number | |||
from .batch import _to_tensor | |||
def _check_code(dataset, model, losser, metrics, batch_size=DEFAULT_CHECK_BATCH_SIZE, | |||
dev_data=None, metric_key=None, | |||
check_level=0): | |||
def _check_code(dataset, model, losser, metrics, forward_func, batch_size=DEFAULT_CHECK_BATCH_SIZE, | |||
dev_data=None, metric_key=None, check_level=0): | |||
# check get_loss 方法 | |||
model_devcie = _get_model_device(model=model) | |||
model_device = _get_model_device(model=model) | |||
def _iter(): | |||
start_idx = 0 | |||
while start_idx<len(dataset): | |||
@@ -825,7 +889,7 @@ def _check_code(dataset, model, losser, metrics, batch_size=DEFAULT_CHECK_BATCH_ | |||
start_idx += batch_size | |||
for batch_count, (batch_x, batch_y) in enumerate(_iter()): | |||
_move_dict_value_to_device(batch_x, batch_y, device=model_devcie) | |||
_move_dict_value_to_device(batch_x, batch_y, device=model_device) | |||
# forward check | |||
if batch_count == 0: | |||
info_str = "" | |||
@@ -844,15 +908,11 @@ def _check_code(dataset, model, losser, metrics, batch_size=DEFAULT_CHECK_BATCH_ | |||
else: | |||
info_str += 'There is no target field.' | |||
print(info_str) | |||
_check_forward_error(forward_func=model.forward, dataset=dataset, | |||
_check_forward_error(forward_func=forward_func, dataset=dataset, | |||
batch_x=batch_x, check_level=check_level) | |||
if isinstance(model, nn.DataParallel): | |||
forward_func = model.module.forward | |||
else: | |||
forward_func = model.forward | |||
refined_batch_x = _build_args(forward_func, **batch_x) | |||
pred_dict = model(**refined_batch_x) | |||
func_signature = _get_func_signature(model.forward) | |||
func_signature = _get_func_signature(forward_func) | |||
if not isinstance(pred_dict, dict): | |||
raise TypeError(f"The return value of {func_signature} should be `dict`, not `{type(pred_dict)}`.") | |||
@@ -872,7 +932,7 @@ def _check_code(dataset, model, losser, metrics, batch_size=DEFAULT_CHECK_BATCH_ | |||
loss.backward() | |||
except _CheckError as e: | |||
# TODO: another error raised if _CheckError caught | |||
pre_func_signature = _get_func_signature(model.forward) | |||
pre_func_signature = _get_func_signature(forward_func) | |||
_check_loss_evaluate(prev_func_signature=pre_func_signature, func_signature=e.func_signature, | |||
check_res=e.check_res, pred_dict=pred_dict, target_dict=batch_y, | |||
dataset=dataset, check_level=check_level) | |||
@@ -4,7 +4,6 @@ utils模块实现了 fastNLP 内部和外部所需的很多工具。其中用户 | |||
__all__ = [ | |||
"cache_results", | |||
"seq_len_to_mask", | |||
"Option", | |||
] | |||
import _pickle | |||
@@ -24,26 +23,27 @@ _CheckRes = namedtuple('_CheckRes', ['missing', 'unused', 'duplicated', 'require | |||
class Option(dict): | |||
"""a dict can treat keys as attributes""" | |||
def __getattr__(self, item): | |||
try: | |||
return self.__getitem__(item) | |||
except KeyError: | |||
raise AttributeError(item) | |||
def __setattr__(self, key, value): | |||
if key.startswith('__') and key.endswith('__'): | |||
raise AttributeError(key) | |||
self.__setitem__(key, value) | |||
def __delattr__(self, item): | |||
try: | |||
self.pop(item) | |||
except KeyError: | |||
raise AttributeError(item) | |||
def __getstate__(self): | |||
return self | |||
def __setstate__(self, state): | |||
self.update(state) | |||
@@ -62,7 +62,6 @@ def _prepare_cache_filepath(filepath): | |||
os.makedirs(cache_dir) | |||
# TODO 可以保存下缓存时的参数,如果load的时候发现参数不一致,发出警告。 | |||
def cache_results(_cache_fp, _refresh=False, _verbose=1): | |||
""" | |||
别名::class:`fastNLP.cache_results` :class:`fastNLP.core.uitls.cache_results` | |||
@@ -163,6 +162,7 @@ def cache_results(_cache_fp, _refresh=False, _verbose=1): | |||
return wrapper_ | |||
def _save_model(model, model_name, save_dir, only_param=False): | |||
""" 存储不含有显卡信息的state_dict或model | |||
:param model: | |||
@@ -187,50 +187,6 @@ def _save_model(model, model_name, save_dir, only_param=False): | |||
torch.save(model, model_path) | |||
model.to(_model_device) | |||
# def save_pickle(obj, pickle_path, file_name): | |||
# """Save an object into a pickle file. | |||
# | |||
# :param obj: an object | |||
# :param pickle_path: str, the directory where the pickle file is to be saved | |||
# :param file_name: str, the name of the pickle file. In general, it should be ended by "pkl". | |||
# """ | |||
# if not os.path.exists(pickle_path): | |||
# os.mkdir(pickle_path) | |||
# print("make dir {} before saving pickle file".format(pickle_path)) | |||
# with open(os.path.join(pickle_path, file_name), "wb") as f: | |||
# _pickle.dump(obj, f) | |||
# print("{} saved in {}".format(file_name, pickle_path)) | |||
# | |||
# | |||
# def load_pickle(pickle_path, file_name): | |||
# """Load an object from a given pickle file. | |||
# | |||
# :param pickle_path: str, the directory where the pickle file is. | |||
# :param file_name: str, the name of the pickle file. | |||
# :return obj: an object stored in the pickle | |||
# """ | |||
# with open(os.path.join(pickle_path, file_name), "rb") as f: | |||
# obj = _pickle.load(f) | |||
# print("{} loaded from {}".format(file_name, pickle_path)) | |||
# return obj | |||
# | |||
# | |||
# def pickle_exist(pickle_path, pickle_name): | |||
# """Check if a given pickle file exists in the directory. | |||
# | |||
# :param pickle_path: the directory of target pickle file | |||
# :param pickle_name: the filename of target pickle file | |||
# :return: True if file exists else False | |||
# """ | |||
# if not os.path.exists(pickle_path): | |||
# os.makedirs(pickle_path) | |||
# file_name = os.path.join(pickle_path, pickle_name) | |||
# if os.path.exists(file_name): | |||
# return True | |||
# else: | |||
# return False | |||
def _move_model_to_device(model, device): | |||
""" | |||
将model移动到device | |||
@@ -253,8 +209,8 @@ def _move_model_to_device(model, device): | |||
:return: torch.nn.DataParallel or torch.nn.Module | |||
""" | |||
if isinstance(model, torch.nn.parallel.DistributedDataParallel): | |||
raise RuntimeError("model of `torch.nn.parallel.DistributedDataParallel` is not supported right now.") | |||
# if isinstance(model, torch.nn.parallel.DistributedDataParallel): | |||
# raise RuntimeError("model of `torch.nn.parallel.DistributedDataParallel` is not supported right now.") | |||
if device is None: | |||
if isinstance(model, torch.nn.DataParallel): | |||
@@ -351,7 +307,6 @@ def _map_args(maps: dict, **kwargs): | |||
output.update({name: val}) | |||
for keys in maps.keys(): | |||
if keys not in output.keys(): | |||
# TODO: add UNUSED warning. | |||
pass | |||
return output | |||
@@ -569,18 +524,6 @@ def _check_loss_evaluate(prev_func_signature: str, func_signature: str, check_re | |||
else: | |||
_tmp = f'Provide `{_miss}` in DataSet or output of {prev_func_signature}.' | |||
suggestions.append(_tmp) | |||
# for _miss in unmapped_missing: | |||
# if _miss in dataset: | |||
# suggestions.append(f"Set `{_miss}` as target.") | |||
# else: | |||
# _tmp = '' | |||
# if check_res.unused: | |||
# _tmp = f"Specify your assignment for `{input_func_map.get(_miss, _miss)}` when initialize {module_name}." | |||
# if _tmp: | |||
# _tmp += f' Or provide `{_miss}` in DataSet or output of {prev_func_signature}.' | |||
# else: | |||
# _tmp = f'Provide `{_miss}` in output of {prev_func_signature} or DataSet.' | |||
# suggestions.append(_tmp) | |||
if check_res.duplicated: | |||
errs.append(f"\tduplicated param: {check_res.duplicated}.") | |||
@@ -673,7 +616,7 @@ def seq_len_to_mask(seq_len, max_len=None): | |||
将一个表示sequence length的一维数组转换为二维的mask,不包含的位置为0。 | |||
转变 1-d seq_len到2-d mask. | |||
Example:: | |||
.. code-block:: | |||
>>> seq_len = torch.arange(2, 16) | |||
>>> mask = seq_len_to_mask(seq_len) | |||
@@ -691,7 +634,7 @@ def seq_len_to_mask(seq_len, max_len=None): | |||
:param np.ndarray,torch.LongTensor seq_len: shape将是(B,) | |||
:param int max_len: 将长度pad到这个长度。默认(None)使用的是seq_len中最长的长度。但在nn.DataParallel的场景下可能不同卡的seq_len会有 | |||
区别,所以需要传入一个max_len使得mask的长度是pad到该长度。 | |||
:return: np.ndarray or torch.Tensor, shape将是(B, max_length)。 元素类似为bool或torch.uint8 | |||
:return: np.ndarray, torch.Tensor 。shape将是(B, max_length), 元素类似为bool或torch.uint8 | |||
""" | |||
if isinstance(seq_len, np.ndarray): | |||
assert len(np.shape(seq_len)) == 1, f"seq_len can only have one dimension, got {len(np.shape(seq_len))}." | |||
@@ -737,7 +680,8 @@ class _pseudo_tqdm: | |||
def __exit__(self, exc_type, exc_val, exc_tb): | |||
del self | |||
def iob2(tags:List[str])->List[str]: | |||
def iob2(tags: List[str]) -> List[str]: | |||
""" | |||
检查数据是否是合法的IOB数据,如果是IOB1会被自动转换为IOB2。两者的差异见 | |||
https://datascience.stackexchange.com/questions/37824/difference-between-iob-and-iob2-format | |||
@@ -760,7 +704,8 @@ def iob2(tags:List[str])->List[str]: | |||
tags[i] = "B" + tag[1:] | |||
return tags | |||
def iob2bioes(tags:List[str])->List[str]: | |||
def iob2bioes(tags: List[str]) -> List[str]: | |||
""" | |||
将iob的tag转换为bioes编码 | |||
:param tags: List[str]. 编码需要是大写的。 | |||
@@ -773,15 +718,15 @@ def iob2bioes(tags:List[str])->List[str]: | |||
else: | |||
split = tag.split('-')[0] | |||
if split == 'B': | |||
if i+1!=len(tags) and tags[i+1].split('-')[0] == 'I': | |||
if i + 1 != len(tags) and tags[i + 1].split('-')[0] == 'I': | |||
new_tags.append(tag) | |||
else: | |||
new_tags.append(tag.replace('B-', 'S-')) | |||
elif split == 'I': | |||
if i + 1<len(tags) and tags[i+1].split('-')[0] == 'I': | |||
if i + 1 < len(tags) and tags[i + 1].split('-')[0] == 'I': | |||
new_tags.append(tag) | |||
else: | |||
new_tags.append(tag.replace('I-', 'E-')) | |||
else: | |||
raise TypeError("Invalid IOB format.") | |||
return new_tags | |||
return new_tags |
@@ -10,6 +10,7 @@ from .utils import Option | |||
from functools import partial | |||
import numpy as np | |||
class VocabularyOption(Option): | |||
def __init__(self, | |||
max_size=None, | |||
@@ -92,7 +93,7 @@ class Vocabulary(object): | |||
self.rebuild = True | |||
# 用于承载不需要单独创建entry的词语,具体见from_dataset()方法 | |||
self._no_create_word = Counter() | |||
@_check_build_status | |||
def update(self, word_lst, no_create_entry=False): | |||
"""依次增加序列中词在词典中的出现频率 | |||
@@ -107,6 +108,7 @@ class Vocabulary(object): | |||
""" | |||
self._add_no_create_entry(word_lst, no_create_entry) | |||
self.word_count.update(word_lst) | |||
return self | |||
@_check_build_status | |||
def add(self, word, no_create_entry=False): | |||
@@ -123,7 +125,8 @@ class Vocabulary(object): | |||
""" | |||
self._add_no_create_entry(word, no_create_entry) | |||
self.word_count[word] += 1 | |||
return self | |||
def _add_no_create_entry(self, word, no_create_entry): | |||
""" | |||
在新加入word时,检查_no_create_word的设置。 | |||
@@ -139,7 +142,7 @@ class Vocabulary(object): | |||
self._no_create_word[w] += 1 | |||
elif not no_create_entry and w in self._no_create_word: | |||
self._no_create_word.pop(w) | |||
@_check_build_status | |||
def add_word(self, word, no_create_entry=False): | |||
""" | |||
@@ -169,6 +172,7 @@ class Vocabulary(object): | |||
则这个词将认为是需要创建单独的vector的。 | |||
""" | |||
self.update(word_lst, no_create_entry=no_create_entry) | |||
return self | |||
def build_vocab(self): | |||
""" | |||
@@ -193,13 +197,15 @@ class Vocabulary(object): | |||
self.word2idx.update({w: i + start_idx for i, (w, _) in enumerate(words)}) | |||
self.build_reverse_vocab() | |||
self.rebuild = False | |||
return self | |||
def build_reverse_vocab(self): | |||
""" | |||
基于 "word to index" dict, 构建 "index to word" dict. | |||
基于 `word to index` dict, 构建 `index to word` dict. | |||
""" | |||
self.idx2word = {i: w for w, i in self.word2idx.items()} | |||
return self | |||
@_check_build_vocab | |||
def __len__(self): | |||
@@ -250,9 +256,9 @@ class Vocabulary(object): | |||
# remember to use `field_name` | |||
vocab.index_dataset(train_data, dev_data, test_data, field_name='words') | |||
:param datasets: 需要转index的 class:`~fastNLP.DataSet` , 支持一个或多个(list) | |||
:param ~fastNLP.DataSet,List[~fastNLP.DataSet] datasets: 需要转index的一个或多个数据集 | |||
:param str field_name: 需要转index的field, 若有多个 DataSet, 每个DataSet都必须有此 field. | |||
目前仅支持 ``str`` , ``list(str)`` , ``list(list(str))`` | |||
目前仅支持 ``str`` , ``List[str]`` , ``List[List[str]]`` | |||
:param str new_field_name: 保存结果的field_name. 若为 ``None`` , 将覆盖原field. | |||
Default: ``None`` | |||
""" | |||
@@ -285,11 +291,12 @@ class Vocabulary(object): | |||
raise e | |||
else: | |||
raise RuntimeError("Only DataSet type is allowed.") | |||
return self | |||
@property | |||
def _no_create_word_length(self): | |||
return len(self._no_create_word) | |||
def from_dataset(self, *datasets, field_name, no_create_entry_dataset=None): | |||
""" | |||
使用dataset的对应field中词构建词典:: | |||
@@ -297,11 +304,11 @@ class Vocabulary(object): | |||
# remember to use `field_name` | |||
vocab.from_dataset(train_data1, train_data2, field_name='words') | |||
:param datasets: 需要转index的 class:`~fastNLP.DataSet` , 支持一个或多个(list) | |||
:param field_name: 可为 ``str`` 或 ``list(str)`` . | |||
:param ~fastNLP.DataSet,List[~fastNLP.DataSet] datasets: 需要转index的一个或多个数据集 | |||
:param str,List[str] field_name: 可为 ``str`` 或 ``List[str]`` . | |||
构建词典所使用的 field(s), 支持一个或多个field | |||
若有多个 DataSet, 每个DataSet都必须有这些field. | |||
目前仅支持的field结构: ``str`` , ``list(str)`` , ``list(list(str))`` | |||
目前仅支持的field结构: ``str`` , ``List[str]`` , ``list[List[str]]`` | |||
:param no_create_entry_dataset: 可以传入DataSet, List[DataSet]或者None(默认),该选项用在接下来的模型会使用pretrain | |||
的embedding(包括glove, word2vec, elmo与bert)且会finetune的情况。如果仅使用来自于train的数据建立vocabulary,会导致test与dev | |||
中的数据无法充分利用到来自于预训练embedding的信息,所以在建立词表的时候将test与dev考虑进来会使得最终的结果更好。 | |||
@@ -331,7 +338,7 @@ class Vocabulary(object): | |||
for words in field: | |||
for word in words: | |||
self.add_word(word, no_create_entry=no_create_entry) | |||
for idx, dataset in enumerate(datasets): | |||
if isinstance(dataset, DataSet): | |||
try: | |||
@@ -341,7 +348,7 @@ class Vocabulary(object): | |||
raise e | |||
else: | |||
raise TypeError("Only DataSet type is allowed.") | |||
if no_create_entry_dataset is not None: | |||
partial_construct_vocab = partial(construct_vocab, no_create_entry=True) | |||
if isinstance(no_create_entry_dataset, DataSet): | |||
@@ -352,7 +359,7 @@ class Vocabulary(object): | |||
raise TypeError("Only DataSet type is allowed.") | |||
dataset.apply(partial_construct_vocab) | |||
return self | |||
def _is_word_no_create_entry(self, word): | |||
""" | |||
判断当前的word是否是不需要创建entry的,具体参见from_dataset的说明 | |||
@@ -360,11 +367,10 @@ class Vocabulary(object): | |||
:return: bool | |||
""" | |||
return word in self._no_create_word | |||
def to_index(self, w): | |||
""" | |||
将词转为数字. 若词不再词典中被记录, 将视为 unknown, 若 ``unknown=None`` , 将抛出 | |||
``ValueError``:: | |||
将词转为数字. 若词不再词典中被记录, 将视为 unknown, 若 ``unknown=None`` , 将抛出``ValueError``:: | |||
index = vocab.to_index('abc') | |||
# equals to | |||
@@ -416,6 +422,7 @@ class Vocabulary(object): | |||
self.idx2word = None | |||
self.rebuild = True | |||
self._no_create_word.clear() | |||
return self | |||
def __getstate__(self): | |||
"""Use to prepare data for pickle. | |||
@@ -0,0 +1,26 @@ | |||
""" | |||
embeddings 模块主要用于从各种预训练的模型中获取词语的分布式表示,目前支持的预训练模型包括word2vec, glove, ELMO, BERT等。这里所有 | |||
embedding的forward输入都是形状为 ``(batch_size, max_len)`` 的torch.LongTensor,输出都是 ``(batch_size, max_len, embedding_dim)`` 的 | |||
torch.FloatTensor。所有的embedding都可以使用 `self.num_embedding` 获取最大的输入index范围, 用 `self.embeddig_dim` 或 `self.embed_size` 获取embedding的 | |||
输出维度。 | |||
""" | |||
__all__ = [ | |||
"Embedding", | |||
"StaticEmbedding", | |||
"ElmoEmbedding", | |||
"BertEmbedding", | |||
"StackEmbedding", | |||
"LSTMCharEmbedding", | |||
"CNNCharEmbedding", | |||
"get_embeddings" | |||
] | |||
from .embedding import Embedding | |||
from .static_embedding import StaticEmbedding | |||
from .elmo_embedding import ElmoEmbedding | |||
from .bert_embedding import BertEmbedding | |||
from .char_embedding import CNNCharEmbedding, LSTMCharEmbedding | |||
from .stack_embedding import StackEmbedding | |||
from .utils import get_embeddings |
@@ -0,0 +1,376 @@ | |||
import os | |||
import collections | |||
from torch import nn | |||
import torch | |||
import numpy as np | |||
from itertools import chain | |||
from ..core.vocabulary import Vocabulary | |||
from ..io.file_utils import _get_base_url, cached_path, PRETRAINED_BERT_MODEL_DIR | |||
from ..modules.encoder.bert import _WordPieceBertModel, BertModel, BertTokenizer | |||
from .contextual_embedding import ContextualEmbedding | |||
class BertEmbedding(ContextualEmbedding): | |||
""" | |||
别名::class:`fastNLP.embeddings.BertEmbedding` :class:`fastNLP.embeddings.bert_embedding.BertEmbedding` | |||
使用BERT对words进行编码的Embedding。建议将输入的words长度限制在430以内,而不要使用512(根据预训练模型参数,可能有变化)。这是由于 | |||
预训练的bert模型长度限制为512个token,而因为输入的word是未进行word piece分割的(word piece的分割有BertEmbedding在输入word | |||
时切分),在分割之后长度可能会超过最大长度限制。 | |||
BertEmbedding可以支持自动下载权重,当前支持的模型有以下的几种(待补充): | |||
Example:: | |||
>>> import torch | |||
>>> from fastNLP import Vocabulary | |||
>>> vocab = Vocabulary().add_word_lst("The whether is good .".split()) | |||
>>> embed = BertEmbedding(vocab, model_dir_or_name='en-base-uncased', requires_grad=False, layers='4,-2,-1') | |||
>>> words = torch.LongTensor([[vocab.to_index(word) for word in "The whether is good .".split()]]) | |||
>>> outputs = embed(words) | |||
>>> outputs.size() | |||
>>> # torch.Size([1, 5, 2304]) | |||
:param ~fastNLP.Vocabulary vocab: 词表 | |||
:param str model_dir_or_name: 模型所在目录或者模型的名称。当传入模型所在目录时,目录中应该包含一个词表文件(以.txt作为后缀名), | |||
权重文件(以.bin作为文件后缀名), 配置文件(以.json作为后缀名)。 | |||
:param str layers: 输出embedding表示来自于哪些层,不同层的结果按照layers中的顺序在最后一维concat起来。以','隔开层数,层的序号是 | |||
从0开始,可以以负数去索引倒数几层。 | |||
:param str pool_method: 因为在bert中,每个word会被表示为多个word pieces, 当获取一个word的表示的时候,怎样从它的word pieces | |||
中计算得到它对应的表示。支持 ``last`` , ``first`` , ``avg`` , ``max``。 | |||
:param float word_dropout: 以多大的概率将一个词替换为unk。这样既可以训练unk也是一定的regularize。 | |||
:param float dropout: 以多大的概率对embedding的表示进行Dropout。0.1即随机将10%的值置为0。 | |||
:param bool include_cls_sep: bool,在bert计算句子的表示的时候,需要在前面加上[CLS]和[SEP], 是否在结果中保留这两个内容。 这样 | |||
会使得word embedding的结果比输入的结果长两个token。如果该值为True,则在使用 :class::StackEmbedding 可能会与其它类型的 | |||
embedding长度不匹配。 | |||
:param bool pooled_cls: 返回的[CLS]是否使用预训练中的BertPool映射一下,仅在include_cls_sep时有效。如果下游任务只取[CLS]做预测, | |||
一般该值为True。 | |||
:param bool requires_grad: 是否需要gradient以更新Bert的权重。 | |||
:param bool auto_truncate: 当句子words拆分为word pieces长度超过bert最大允许长度(一般为512), 自动截掉拆分后的超过510个 | |||
word pieces后的内容,并将第512个word piece置为[SEP]。超过长度的部分的encode结果直接全部置零。一般仅有只使用[CLS] | |||
来进行分类的任务将auto_truncate置为True。 | |||
""" | |||
def __init__(self, vocab: Vocabulary, model_dir_or_name: str='en-base-uncased', layers: str='-1', | |||
pool_method: str='first', word_dropout=0, dropout=0, include_cls_sep: bool=False, | |||
pooled_cls=True, requires_grad: bool=False, auto_truncate:bool=False): | |||
super(BertEmbedding, self).__init__(vocab, word_dropout=word_dropout, dropout=dropout) | |||
# 根据model_dir_or_name检查是否存在并下载 | |||
if model_dir_or_name.lower() in PRETRAINED_BERT_MODEL_DIR: | |||
PRETRAIN_URL = _get_base_url('bert') | |||
model_name = PRETRAINED_BERT_MODEL_DIR[model_dir_or_name] | |||
model_url = PRETRAIN_URL + model_name | |||
model_dir = cached_path(model_url) | |||
# 检查是否存在 | |||
elif os.path.isdir(os.path.expanduser(os.path.abspath(model_dir_or_name))): | |||
model_dir = os.path.expanduser(os.path.abspath(model_dir_or_name)) | |||
else: | |||
raise ValueError(f"Cannot recognize {model_dir_or_name}.") | |||
self.model = _WordBertModel(model_dir=model_dir, vocab=vocab, layers=layers, | |||
pool_method=pool_method, include_cls_sep=include_cls_sep, | |||
pooled_cls=pooled_cls, auto_truncate=auto_truncate) | |||
self.requires_grad = requires_grad | |||
self._embed_size = len(self.model.layers)*self.model.encoder.hidden_size | |||
def _delete_model_weights(self): | |||
del self.model | |||
def forward(self, words): | |||
""" | |||
计算words的bert embedding表示。计算之前会在每句话的开始增加[CLS]在结束增加[SEP], 并根据include_cls_sep判断要不要 | |||
删除这两个token的表示。 | |||
:param torch.LongTensor words: [batch_size, max_len] | |||
:return: torch.FloatTensor. batch_size x max_len x (768*len(self.layers)) | |||
""" | |||
words = self.drop_word(words) | |||
outputs = self._get_sent_reprs(words) | |||
if outputs is not None: | |||
return self.dropout(words) | |||
outputs = self.model(words) | |||
outputs = torch.cat([*outputs], dim=-1) | |||
return self.dropout(outputs) | |||
@property | |||
def requires_grad(self): | |||
""" | |||
Embedding的参数是否允许优化。True: 所有参数运行优化; False: 所有参数不允许优化; None: 部分允许优化、部分不允许 | |||
:return: | |||
""" | |||
requires_grads = set([param.requires_grad for name, param in self.named_parameters() | |||
if 'word_pieces_lengths' not in name]) | |||
if len(requires_grads) == 1: | |||
return requires_grads.pop() | |||
else: | |||
return None | |||
@requires_grad.setter | |||
def requires_grad(self, value): | |||
for name, param in self.named_parameters(): | |||
if 'word_pieces_lengths' in name: # 这个不能加入到requires_grad中 | |||
continue | |||
param.requires_grad = value | |||
class BertWordPieceEncoder(nn.Module): | |||
""" | |||
读取bert模型,读取之后调用index_dataset方法在dataset中生成word_pieces这一列。 | |||
:param str model_dir_or_name: 模型所在目录或者模型的名称。默认值为 ``en-base-uncased`` | |||
:param str layers: 最终结果中的表示。以','隔开层数,可以以负数去索引倒数几层 | |||
:param bool pooled_cls: 返回的句子开头的[CLS]是否使用预训练中的BertPool映射一下,仅在include_cls_sep时有效。如果下游任务只取 | |||
[CLS]做预测,一般该值为True。 | |||
:param bool requires_grad: 是否需要gradient。 | |||
""" | |||
def __init__(self, model_dir_or_name: str='en-base-uncased', layers: str='-1', | |||
pooled_cls: bool = False, requires_grad: bool=False): | |||
super().__init__() | |||
if model_dir_or_name in PRETRAINED_BERT_MODEL_DIR: | |||
PRETRAIN_URL = _get_base_url('bert') | |||
model_name = PRETRAINED_BERT_MODEL_DIR[model_dir_or_name] | |||
model_url = PRETRAIN_URL + model_name | |||
model_dir = cached_path(model_url) | |||
# 检查是否存在 | |||
elif os.path.isdir(os.path.expanduser(os.path.abspath(model_dir_or_name))): | |||
model_dir = model_dir_or_name | |||
else: | |||
raise ValueError(f"Cannot recognize {model_dir_or_name}.") | |||
self.model = _WordPieceBertModel(model_dir=model_dir, layers=layers, pooled_cls=pooled_cls) | |||
self._embed_size = len(self.model.layers) * self.model.encoder.hidden_size | |||
self.requires_grad = requires_grad | |||
@property | |||
def requires_grad(self): | |||
""" | |||
Embedding的参数是否允许优化。True: 所有参数运行优化; False: 所有参数不允许优化; None: 部分允许优化、部分不允许 | |||
:return: | |||
""" | |||
requires_grads = set([param.requires_grad for name, param in self.named_parameters()]) | |||
if len(requires_grads) == 1: | |||
return requires_grads.pop() | |||
else: | |||
return None | |||
@requires_grad.setter | |||
def requires_grad(self, value): | |||
for name, param in self.named_parameters(): | |||
param.requires_grad = value | |||
@property | |||
def embed_size(self): | |||
return self._embed_size | |||
@property | |||
def embedding_dim(self): | |||
return self._embed_size | |||
@property | |||
def num_embedding(self): | |||
return self.model.encoder.config.vocab_size | |||
def index_datasets(self, *datasets, field_name, add_cls_sep=True): | |||
""" | |||
使用bert的tokenizer新生成word_pieces列加入到datasets中,并将他们设置为input,且将word_pieces这一列的pad value设置为了 | |||
bert的pad value。 | |||
:param DataSet datasets: DataSet对象 | |||
:param str field_name: 基于哪一列的内容生成word_pieces列。这一列中每个数据应该是List[str]的形式。 | |||
:param bool add_cls_sep: 如果首尾不是[CLS]与[SEP]会在首尾额外加入[CLS]与[SEP]。 | |||
:return: | |||
""" | |||
self.model.index_dataset(*datasets, field_name=field_name, add_cls_sep=add_cls_sep) | |||
def forward(self, word_pieces, token_type_ids=None): | |||
""" | |||
计算words的bert embedding表示。传入的words中应该自行包含[CLS]与[SEP]的tag。 | |||
:param words: batch_size x max_len | |||
:param token_type_ids: batch_size x max_len, 用于区分前一句和后一句话 | |||
:return: torch.FloatTensor. batch_size x max_len x (768*len(self.layers)) | |||
""" | |||
outputs = self.model(word_pieces, token_type_ids) | |||
outputs = torch.cat([*outputs], dim=-1) | |||
return outputs | |||
class _WordBertModel(nn.Module): | |||
def __init__(self, model_dir:str, vocab:Vocabulary, layers:str='-1', pool_method:str='first', | |||
include_cls_sep:bool=False, pooled_cls:bool=False, auto_truncate:bool=False): | |||
super().__init__() | |||
self.tokenzier = BertTokenizer.from_pretrained(model_dir) | |||
self.encoder = BertModel.from_pretrained(model_dir) | |||
self._max_position_embeddings = self.encoder.config.max_position_embeddings | |||
# 检查encoder_layer_number是否合理 | |||
encoder_layer_number = len(self.encoder.encoder.layer) | |||
self.layers = list(map(int, layers.split(','))) | |||
for layer in self.layers: | |||
if layer<0: | |||
assert -layer<=encoder_layer_number, f"The layer index:{layer} is out of scope for " \ | |||
f"a bert model with {encoder_layer_number} layers." | |||
else: | |||
assert layer<encoder_layer_number, f"The layer index:{layer} is out of scope for " \ | |||
f"a bert model with {encoder_layer_number} layers." | |||
assert pool_method in ('avg', 'max', 'first', 'last') | |||
self.pool_method = pool_method | |||
self.include_cls_sep = include_cls_sep | |||
self.pooled_cls = pooled_cls | |||
self.auto_truncate = auto_truncate | |||
# 将所有vocab中word的wordpiece计算出来, 需要额外考虑[CLS]和[SEP] | |||
print("Start to generating word pieces for word.") | |||
# 第一步统计出需要的word_piece, 然后创建新的embed和word_piece_vocab, 然后填入值 | |||
word_piece_dict = {'[CLS]':1, '[SEP]':1} # 用到的word_piece以及新增的 | |||
found_count = 0 | |||
for word, index in vocab: | |||
if index == vocab.padding_idx: # pad是个特殊的符号 | |||
word = '[PAD]' | |||
elif index == vocab.unknown_idx: | |||
word = '[UNK]' | |||
word_pieces = self.tokenzier.wordpiece_tokenizer.tokenize(word) | |||
if len(word_pieces)==1: | |||
if not vocab._is_word_no_create_entry(word): # 如果是train中的值, 但是却没有找到 | |||
if index!=vocab.unknown_idx and word_pieces[0]=='[UNK]': # 说明这个词不在原始的word里面 | |||
word_piece_dict[word] = 1 # 新增一个值 | |||
continue | |||
for word_piece in word_pieces: | |||
word_piece_dict[word_piece] = 1 | |||
found_count += 1 | |||
original_embed = self.encoder.embeddings.word_embeddings.weight.data | |||
# 特殊词汇要特殊处理 | |||
embed = nn.Embedding(len(word_piece_dict), original_embed.size(1)) # 新的embed | |||
new_word_piece_vocab = collections.OrderedDict() | |||
for index, token in enumerate(['[PAD]', '[UNK]']): | |||
word_piece_dict.pop(token, None) | |||
embed.weight.data[index] = original_embed[self.tokenzier.vocab[token]] | |||
new_word_piece_vocab[token] = index | |||
for token in word_piece_dict.keys(): | |||
if token in self.tokenzier.vocab: | |||
embed.weight.data[len(new_word_piece_vocab)] = original_embed[self.tokenzier.vocab[token]] | |||
else: | |||
embed.weight.data[len(new_word_piece_vocab)] = original_embed[self.tokenzier.vocab['[UNK]']] | |||
new_word_piece_vocab[token] = len(new_word_piece_vocab) | |||
self.tokenzier._reinit_on_new_vocab(new_word_piece_vocab) | |||
self.encoder.embeddings.word_embeddings = embed | |||
word_to_wordpieces = [] | |||
word_pieces_lengths = [] | |||
for word, index in vocab: | |||
if index == vocab.padding_idx: # pad是个特殊的符号 | |||
word = '[PAD]' | |||
elif index == vocab.unknown_idx: | |||
word = '[UNK]' | |||
word_pieces = self.tokenzier.wordpiece_tokenizer.tokenize(word) | |||
word_pieces = self.tokenzier.convert_tokens_to_ids(word_pieces) | |||
word_to_wordpieces.append(word_pieces) | |||
word_pieces_lengths.append(len(word_pieces)) | |||
print("Found(Or seg into word pieces) {} words out of {}.".format(found_count, len(vocab))) | |||
self._cls_index = self.tokenzier.vocab['[CLS]'] | |||
self._sep_index = self.tokenzier.vocab['[SEP]'] | |||
self._pad_index = vocab.padding_idx | |||
self._wordpiece_pad_index = self.tokenzier.vocab['[PAD]'] # 需要用于生成word_piece | |||
self.word_to_wordpieces = np.array(word_to_wordpieces) | |||
self.word_pieces_lengths = nn.Parameter(torch.LongTensor(word_pieces_lengths), requires_grad=False) | |||
print("Successfully generate word pieces.") | |||
def forward(self, words): | |||
""" | |||
:param words: torch.LongTensor, batch_size x max_len | |||
:return: num_layers x batch_size x max_len x hidden_size或者num_layers x batch_size x (max_len+2) x hidden_size | |||
""" | |||
batch_size, max_word_len = words.size() | |||
seq_len = words.ne(self._pad_index).sum(dim=-1) | |||
batch_word_pieces_length = self.word_pieces_lengths[words] # batch_size x max_len | |||
word_pieces_lengths = batch_word_pieces_length.sum(dim=-1) | |||
max_word_piece_length = word_pieces_lengths.max().item() | |||
real_max_word_piece_length = max_word_piece_length # 表示没有截断的word piece的长度 | |||
if max_word_piece_length+2>self._max_position_embeddings: | |||
if self.auto_truncate: | |||
word_pieces_lengths = word_pieces_lengths.masked_fill(word_pieces_lengths+2>self._max_position_embeddings, | |||
self._max_position_embeddings-2) | |||
max_word_piece_length = self._max_position_embeddings-2 | |||
else: | |||
raise RuntimeError("After split words into word pieces, the lengths of word pieces are longer than the " | |||
f"maximum allowed sequence length:{self._max_position_embeddings} of bert.") | |||
# +2是由于需要加入[CLS]与[SEP] | |||
word_pieces = words.new_full((batch_size, max_word_piece_length+2), fill_value=self._wordpiece_pad_index) | |||
word_pieces[:, 0].fill_(self._cls_index) | |||
batch_indexes = torch.arange(batch_size).to(words) | |||
word_pieces[batch_indexes, word_pieces_lengths+1] = self._sep_index | |||
attn_masks = torch.zeros_like(word_pieces) | |||
# 1. 获取words的word_pieces的id,以及对应的span范围 | |||
word_indexes = words.tolist() | |||
for i in range(batch_size): | |||
word_pieces_i = list(chain(*self.word_to_wordpieces[word_indexes[i]])) | |||
if self.auto_truncate and len(word_pieces_i)>self._max_position_embeddings-2: | |||
word_pieces_i = word_pieces_i[:self._max_position_embeddings-2] | |||
word_pieces[i, 1:len(word_pieces_i)+1] = torch.LongTensor(word_pieces_i) | |||
attn_masks[i, :len(word_pieces_i)+2].fill_(1) | |||
# TODO 截掉长度超过的部分。 | |||
# 2. 获取hidden的结果,根据word_pieces进行对应的pool计算 | |||
# all_outputs: [batch_size x max_len x hidden_size, batch_size x max_len x hidden_size, ...] | |||
bert_outputs, pooled_cls = self.encoder(word_pieces, token_type_ids=None, attention_mask=attn_masks, | |||
output_all_encoded_layers=True) | |||
# output_layers = [self.layers] # len(self.layers) x batch_size x max_word_piece_length x hidden_size | |||
if self.include_cls_sep: | |||
outputs = bert_outputs[-1].new_zeros(len(self.layers), batch_size, max_word_len + 2, | |||
bert_outputs[-1].size(-1)) | |||
s_shift = 1 | |||
else: | |||
outputs = bert_outputs[-1].new_zeros(len(self.layers), batch_size, max_word_len, | |||
bert_outputs[-1].size(-1)) | |||
s_shift = 0 | |||
batch_word_pieces_cum_length = batch_word_pieces_length.new_zeros(batch_size, max_word_len + 1) | |||
batch_word_pieces_cum_length[:, 1:] = batch_word_pieces_length.cumsum(dim=-1) # batch_size x max_len | |||
for l_index, l in enumerate(self.layers): | |||
output_layer = bert_outputs[l] | |||
if real_max_word_piece_length > max_word_piece_length: # 如果实际上是截取出来的 | |||
paddings = output_layer.new_zeros(batch_size, | |||
real_max_word_piece_length-max_word_piece_length, | |||
output_layer.size(2)) | |||
output_layer = torch.cat((output_layer, paddings), dim=1).contiguous() | |||
# 从word_piece collapse到word的表示 | |||
truncate_output_layer = output_layer[:, 1:-1] # 删除[CLS]与[SEP] batch_size x len x hidden_size | |||
outputs_seq_len = seq_len + s_shift | |||
if self.pool_method == 'first': | |||
for i in range(batch_size): | |||
i_word_pieces_cum_length = batch_word_pieces_cum_length[i, :seq_len[i]] # 每个word的start位置 | |||
outputs[l_index, i, s_shift:outputs_seq_len[i]] = truncate_output_layer[i, i_word_pieces_cum_length] # num_layer x batch_size x len x hidden_size | |||
elif self.pool_method == 'last': | |||
for i in range(batch_size): | |||
i_word_pieces_cum_length = batch_word_pieces_cum_length[i, 1:seq_len[i]+1] - 1 # 每个word的end | |||
outputs[l_index, i, s_shift:outputs_seq_len[i]] = truncate_output_layer[i, i_word_pieces_cum_length] | |||
elif self.pool_method == 'max': | |||
for i in range(batch_size): | |||
for j in range(seq_len[i]): | |||
start, end = batch_word_pieces_cum_length[i, j], batch_word_pieces_cum_length[i, j+1] | |||
outputs[l_index, i, j+s_shift], _ = torch.max(truncate_output_layer[i, start:end], dim=-2) | |||
else: | |||
for i in range(batch_size): | |||
for j in range(seq_len[i]): | |||
start, end = batch_word_pieces_cum_length[i, j], batch_word_pieces_cum_length[i, j+1] | |||
outputs[l_index, i, j+s_shift] = torch.mean(truncate_output_layer[i, start:end], dim=-2) | |||
if self.include_cls_sep: | |||
if l in (len(bert_outputs)-1, -1) and self.pooled_cls: | |||
outputs[l_index, :, 0] = pooled_cls | |||
else: | |||
outputs[l_index, :, 0] = output_layer[:, 0] | |||
outputs[l_index, batch_indexes, seq_len+s_shift] = output_layer[batch_indexes, seq_len+s_shift] | |||
# 3. 最终的embedding结果 | |||
return outputs | |||
@@ -0,0 +1,295 @@ | |||
""" | |||
该文件中主要包含的是character的Embedding,包括基于CNN与LSTM的character Embedding。与其它Embedding一样,这里的Embedding输入也是 | |||
词的index而不需要使用词语中的char的index来获取表达。 | |||
""" | |||
import torch | |||
import torch.nn as nn | |||
import torch.nn.functional as F | |||
from typing import List | |||
from ..modules.encoder.lstm import LSTM | |||
from ..core.vocabulary import Vocabulary | |||
from .embedding import TokenEmbedding | |||
from .utils import _construct_char_vocab_from_vocab | |||
class CNNCharEmbedding(TokenEmbedding): | |||
""" | |||
别名::class:`fastNLP.embeddings.CNNCharEmbedding` :class:`fastNLP.embeddings.char_embedding.CNNCharEmbedding` | |||
使用CNN生成character embedding。CNN的结构为, embed(x) -> Dropout(x) -> CNN(x) -> activation(x) -> pool -> fc -> Dropout. | |||
不同的kernel大小的fitler结果是concat起来然后通过一层fully connected layer, 然后输出word的表示。 | |||
Example:: | |||
>>> vocab = Vocabulary().add_word_lst("The whether is good .".split()) | |||
>>> embed = CNNCharEmbedding(vocab, embed_size=50) | |||
>>> words = torch.LongTensor([[vocab.to_index(word) for word in "The whether is good .".split()]]) | |||
>>> outputs = embed(words) | |||
>>> outputs.size() | |||
>>> # torch.Size([1, 5,50]) | |||
:param vocab: 词表 | |||
:param embed_size: 该word embedding的大小,默认值为50. | |||
:param char_emb_size: character的embed的大小。character是从vocab中生成的。默认值为50. | |||
:param float word_dropout: 以多大的概率将一个词替换为unk。这样既可以训练unk也是一定的regularize。 | |||
:param float dropout: 以多大的概率drop分布式表示与char embedding的输出。 | |||
:param filter_nums: filter的数量. 长度需要和kernels一致。默认值为[40, 30, 20]. | |||
:param kernel_sizes: kernel的大小. 默认值为[5, 3, 1]. | |||
:param pool_method: character的表示在合成一个表示时所使用的pool方法,支持'avg', 'max'. | |||
:param activation: CNN之后使用的激活方法,支持'relu', 'sigmoid', 'tanh' 或者自定义函数. | |||
:param min_char_freq: character的最少出现次数。默认值为2. | |||
""" | |||
def __init__(self, vocab: Vocabulary, embed_size: int=50, char_emb_size: int=50, word_dropout:float=0, | |||
dropout:float=0.5, filter_nums: List[int]=(40, 30, 20), kernel_sizes: List[int]=(5, 3, 1), | |||
pool_method: str='max', activation='relu', min_char_freq: int=2): | |||
super(CNNCharEmbedding, self).__init__(vocab, word_dropout=word_dropout, dropout=dropout) | |||
for kernel in kernel_sizes: | |||
assert kernel % 2 == 1, "Only odd kernel is allowed." | |||
assert pool_method in ('max', 'avg') | |||
self.dropout = nn.Dropout(dropout) | |||
self.pool_method = pool_method | |||
# activation function | |||
if isinstance(activation, str): | |||
if activation.lower() == 'relu': | |||
self.activation = F.relu | |||
elif activation.lower() == 'sigmoid': | |||
self.activation = F.sigmoid | |||
elif activation.lower() == 'tanh': | |||
self.activation = F.tanh | |||
elif activation is None: | |||
self.activation = lambda x: x | |||
elif callable(activation): | |||
self.activation = activation | |||
else: | |||
raise Exception( | |||
"Undefined activation function: choose from: [relu, tanh, sigmoid, or a callable function]") | |||
print("Start constructing character vocabulary.") | |||
# 建立char的词表 | |||
self.char_vocab = _construct_char_vocab_from_vocab(vocab, min_freq=min_char_freq) | |||
self.char_pad_index = self.char_vocab.padding_idx | |||
print(f"In total, there are {len(self.char_vocab)} distinct characters.") | |||
# 对vocab进行index | |||
max_word_len = max(map(lambda x: len(x[0]), vocab)) | |||
self.words_to_chars_embedding = nn.Parameter(torch.full((len(vocab), max_word_len), | |||
fill_value=self.char_pad_index, dtype=torch.long), | |||
requires_grad=False) | |||
self.word_lengths = nn.Parameter(torch.zeros(len(vocab)).long(), requires_grad=False) | |||
for word, index in vocab: | |||
# if index!=vocab.padding_idx: # 如果是pad的话,直接就为pad_value了。修改为不区分pad, 这样所有的<pad>也是同一个embed | |||
self.words_to_chars_embedding[index, :len(word)] = \ | |||
torch.LongTensor([self.char_vocab.to_index(c) for c in word]) | |||
self.word_lengths[index] = len(word) | |||
self.char_embedding = nn.Embedding(len(self.char_vocab), char_emb_size) | |||
self.convs = nn.ModuleList([nn.Conv1d( | |||
char_emb_size, filter_nums[i], kernel_size=kernel_sizes[i], bias=True, padding=kernel_sizes[i] // 2) | |||
for i in range(len(kernel_sizes))]) | |||
self._embed_size = embed_size | |||
self.fc = nn.Linear(sum(filter_nums), embed_size) | |||
self.reset_parameters() | |||
def forward(self, words): | |||
""" | |||
输入words的index后,生成对应的words的表示。 | |||
:param words: [batch_size, max_len] | |||
:return: [batch_size, max_len, embed_size] | |||
""" | |||
words = self.drop_word(words) | |||
batch_size, max_len = words.size() | |||
chars = self.words_to_chars_embedding[words] # batch_size x max_len x max_word_len | |||
word_lengths = self.word_lengths[words] # batch_size x max_len | |||
max_word_len = word_lengths.max() | |||
chars = chars[:, :, :max_word_len] | |||
# 为1的地方为mask | |||
chars_masks = chars.eq(self.char_pad_index) # batch_size x max_len x max_word_len 如果为0, 说明是padding的位置了 | |||
chars = self.char_embedding(chars) # batch_size x max_len x max_word_len x embed_size | |||
chars = self.dropout(chars) | |||
reshaped_chars = chars.reshape(batch_size*max_len, max_word_len, -1) | |||
reshaped_chars = reshaped_chars.transpose(1, 2) # B' x E x M | |||
conv_chars = [conv(reshaped_chars).transpose(1, 2).reshape(batch_size, max_len, max_word_len, -1) | |||
for conv in self.convs] | |||
conv_chars = torch.cat(conv_chars, dim=-1).contiguous() # B x max_len x max_word_len x sum(filters) | |||
conv_chars = self.activation(conv_chars) | |||
if self.pool_method == 'max': | |||
conv_chars = conv_chars.masked_fill(chars_masks.unsqueeze(-1), float('-inf')) | |||
chars, _ = torch.max(conv_chars, dim=-2) # batch_size x max_len x sum(filters) | |||
else: | |||
conv_chars = conv_chars.masked_fill(chars_masks.unsqueeze(-1), 0) | |||
chars = torch.sum(conv_chars, dim=-2)/chars_masks.eq(0).sum(dim=-1, keepdim=True).float() | |||
chars = self.fc(chars) | |||
return self.dropout(chars) | |||
@property | |||
def requires_grad(self): | |||
""" | |||
Embedding的参数是否允许优化。True: 所有参数运行优化; False: 所有参数不允许优化; None: 部分允许优化、部分不允许 | |||
:return: | |||
""" | |||
params = [] | |||
for name, param in self.named_parameters(): | |||
if 'words_to_chars_embedding' not in name and 'word_lengths' not in name: | |||
params.append(param.requires_grad) | |||
requires_grads = set(params) | |||
if len(requires_grads) == 1: | |||
return requires_grads.pop() | |||
else: | |||
return None | |||
@requires_grad.setter | |||
def requires_grad(self, value): | |||
for name, param in self.named_parameters(): | |||
if 'words_to_chars_embedding' in name or 'word_lengths' in name: # 这个不能加入到requires_grad中 | |||
continue | |||
param.requires_grad = value | |||
def reset_parameters(self): | |||
for name, param in self.named_parameters(): | |||
if 'words_to_chars_embedding' in name or 'word_lengths' in name: # 这个不能reset | |||
continue | |||
if param.data.dim()>1: | |||
nn.init.xavier_uniform_(param, 1) | |||
else: | |||
nn.init.uniform_(param, -1, 1) | |||
class LSTMCharEmbedding(TokenEmbedding): | |||
""" | |||
别名::class:`fastNLP.embeddings.LSTMCharEmbedding` :class:`fastNLP.embeddings.char_embedding.LSTMCharEmbedding` | |||
使用LSTM的方式对character进行encode. embed(x) -> Dropout(x) -> LSTM(x) -> activation(x) -> pool -> Dropout | |||
Example:: | |||
>>> vocab = Vocabulary().add_word_lst("The whether is good .".split()) | |||
>>> embed = LSTMCharEmbedding(vocab, embed_size=50) | |||
>>> words = torch.LongTensor([[vocab.to_index(word) for word in "The whether is good .".split()]]) | |||
>>> outputs = embed(words) | |||
>>> outputs.size() | |||
>>> # torch.Size([1, 5,50]) | |||
:param vocab: 词表 | |||
:param embed_size: embedding的大小。默认值为50. | |||
:param char_emb_size: character的embedding的大小。默认值为50. | |||
:param float word_dropout: 以多大的概率将一个词替换为unk。这样既可以训练unk也是一定的regularize。 | |||
:param dropout: 以多大概率drop character embedding的输出以及最终的word的输出。 | |||
:param hidden_size: LSTM的中间hidden的大小,如果为bidirectional的,hidden会除二,默认为50. | |||
:param pool_method: 支持'max', 'avg'。 | |||
:param activation: 激活函数,支持'relu', 'sigmoid', 'tanh', 或者自定义函数. | |||
:param min_char_freq: character的最小出现次数。默认值为2. | |||
:param bidirectional: 是否使用双向的LSTM进行encode。默认值为True。 | |||
""" | |||
def __init__(self, vocab: Vocabulary, embed_size: int=50, char_emb_size: int=50, word_dropout:float=0, | |||
dropout:float=0.5, hidden_size=50,pool_method: str='max', activation='relu', min_char_freq: int=2, | |||
bidirectional=True): | |||
super(LSTMCharEmbedding, self).__init__(vocab) | |||
assert hidden_size % 2 == 0, "Only even kernel is allowed." | |||
assert pool_method in ('max', 'avg') | |||
self.pool_method = pool_method | |||
self.dropout = nn.Dropout(dropout) | |||
# activation function | |||
if isinstance(activation, str): | |||
if activation.lower() == 'relu': | |||
self.activation = F.relu | |||
elif activation.lower() == 'sigmoid': | |||
self.activation = F.sigmoid | |||
elif activation.lower() == 'tanh': | |||
self.activation = F.tanh | |||
elif activation is None: | |||
self.activation = lambda x: x | |||
elif callable(activation): | |||
self.activation = activation | |||
else: | |||
raise Exception( | |||
"Undefined activation function: choose from: [relu, tanh, sigmoid, or a callable function]") | |||
print("Start constructing character vocabulary.") | |||
# 建立char的词表 | |||
self.char_vocab = _construct_char_vocab_from_vocab(vocab, min_freq=min_char_freq) | |||
self.char_pad_index = self.char_vocab.padding_idx | |||
print(f"In total, there are {len(self.char_vocab)} distinct characters.") | |||
# 对vocab进行index | |||
self.max_word_len = max(map(lambda x: len(x[0]), vocab)) | |||
self.words_to_chars_embedding = nn.Parameter(torch.full((len(vocab), self.max_word_len), | |||
fill_value=self.char_pad_index, dtype=torch.long), | |||
requires_grad=False) | |||
self.word_lengths = nn.Parameter(torch.zeros(len(vocab)).long(), requires_grad=False) | |||
for word, index in vocab: | |||
# if index!=vocab.padding_idx: # 如果是pad的话,直接就为pad_value了. 修改为不区分pad与否 | |||
self.words_to_chars_embedding[index, :len(word)] = \ | |||
torch.LongTensor([self.char_vocab.to_index(c) for c in word]) | |||
self.word_lengths[index] = len(word) | |||
self.char_embedding = nn.Embedding(len(self.char_vocab), char_emb_size) | |||
self.fc = nn.Linear(hidden_size, embed_size) | |||
hidden_size = hidden_size // 2 if bidirectional else hidden_size | |||
self.lstm = LSTM(char_emb_size, hidden_size, bidirectional=bidirectional, batch_first=True) | |||
self._embed_size = embed_size | |||
self.bidirectional = bidirectional | |||
def forward(self, words): | |||
""" | |||
输入words的index后,生成对应的words的表示。 | |||
:param words: [batch_size, max_len] | |||
:return: [batch_size, max_len, embed_size] | |||
""" | |||
words = self.drop_word(words) | |||
batch_size, max_len = words.size() | |||
chars = self.words_to_chars_embedding[words] # batch_size x max_len x max_word_len | |||
word_lengths = self.word_lengths[words] # batch_size x max_len | |||
max_word_len = word_lengths.max() | |||
chars = chars[:, :, :max_word_len] | |||
# 为mask的地方为1 | |||
chars_masks = chars.eq(self.char_pad_index) # batch_size x max_len x max_word_len 如果为0, 说明是padding的位置了 | |||
chars = self.char_embedding(chars) # batch_size x max_len x max_word_len x embed_size | |||
chars = self.dropout(chars) | |||
reshaped_chars = chars.reshape(batch_size * max_len, max_word_len, -1) | |||
char_seq_len = chars_masks.eq(0).sum(dim=-1).reshape(batch_size * max_len) | |||
lstm_chars = self.lstm(reshaped_chars, char_seq_len)[0].reshape(batch_size, max_len, max_word_len, -1) | |||
# B x M x M x H | |||
lstm_chars = self.activation(lstm_chars) | |||
if self.pool_method == 'max': | |||
lstm_chars = lstm_chars.masked_fill(chars_masks.unsqueeze(-1), float('-inf')) | |||
chars, _ = torch.max(lstm_chars, dim=-2) # batch_size x max_len x H | |||
else: | |||
lstm_chars = lstm_chars.masked_fill(chars_masks.unsqueeze(-1), 0) | |||
chars = torch.sum(lstm_chars, dim=-2) / chars_masks.eq(0).sum(dim=-1, keepdim=True).float() | |||
chars = self.fc(chars) | |||
return self.dropout(chars) | |||
@property | |||
def requires_grad(self): | |||
""" | |||
Embedding的参数是否允许优化。True: 所有参数运行优化; False: 所有参数不允许优化; None: 部分允许优化、部分不允许 | |||
:return: | |||
""" | |||
params = [] | |||
for name, param in self.named_parameters(): | |||
if 'words_to_chars_embedding' not in name and 'word_lengths' not in name: | |||
params.append(param) | |||
requires_grads = set(params) | |||
if len(requires_grads) == 1: | |||
return requires_grads.pop() | |||
else: | |||
return None | |||
@requires_grad.setter | |||
def requires_grad(self, value): | |||
for name, param in self.named_parameters(): | |||
if 'words_to_chars_embedding' in name or 'word_lengths' in name: # 这个不能加入到requires_grad中 | |||
continue | |||
param.requires_grad = value |
@@ -0,0 +1,100 @@ | |||
from abc import abstractmethod | |||
import torch | |||
from ..core.vocabulary import Vocabulary | |||
from ..core.dataset import DataSet | |||
from ..core.batch import DataSetIter | |||
from ..core.sampler import SequentialSampler | |||
from ..core.utils import _move_model_to_device, _get_model_device | |||
from .embedding import TokenEmbedding | |||
class ContextualEmbedding(TokenEmbedding): | |||
def __init__(self, vocab: Vocabulary, word_dropout:float=0.0, dropout:float=0.0): | |||
super(ContextualEmbedding, self).__init__(vocab, word_dropout=word_dropout, dropout=dropout) | |||
def add_sentence_cache(self, *datasets, batch_size=32, device='cpu', delete_weights: bool=True): | |||
""" | |||
由于动态embedding生成比较耗时,所以可以把每句话embedding缓存下来,这样就不需要每次都运行生成过程。 | |||
:param datasets: DataSet对象 | |||
:param batch_size: int, 生成cache的sentence表示时使用的batch的大小 | |||
:param device: 参考 :class::fastNLP.Trainer 的device | |||
:param delete_weights: 似乎在生成了cache之后删除权重,在不需要finetune动态模型的情况下,删除权重会大量减少内存占用。 | |||
:return: | |||
""" | |||
for index, dataset in enumerate(datasets): | |||
try: | |||
assert isinstance(dataset, DataSet), "Only fastNLP.DataSet object is allowed." | |||
assert 'words' in dataset.get_input_name(), "`words` field has to be set as input." | |||
except Exception as e: | |||
print(f"Exception happens at {index} dataset.") | |||
raise e | |||
sent_embeds = {} | |||
_move_model_to_device(self, device=device) | |||
device = _get_model_device(self) | |||
pad_index = self._word_vocab.padding_idx | |||
print("Start to calculate sentence representations.") | |||
with torch.no_grad(): | |||
for index, dataset in enumerate(datasets): | |||
try: | |||
batch = DataSetIter(dataset, batch_size=batch_size, sampler=SequentialSampler()) | |||
for batch_x, batch_y in batch: | |||
words = batch_x['words'].to(device) | |||
words_list = words.tolist() | |||
seq_len = words.ne(pad_index).sum(dim=-1) | |||
max_len = words.size(1) | |||
# 因为有些情况可能包含CLS, SEP, 从后面往前计算比较安全。 | |||
seq_len_from_behind = (max_len - seq_len).tolist() | |||
word_embeds = self(words).detach().cpu().numpy() | |||
for b in range(words.size(0)): | |||
length = seq_len_from_behind[b] | |||
if length==0: | |||
sent_embeds[tuple(words_list[b][:seq_len[b]])] = word_embeds[b] | |||
else: | |||
sent_embeds[tuple(words_list[b][:seq_len[b]])] = word_embeds[b, :-length] | |||
except Exception as e: | |||
print(f"Exception happens at {index} dataset.") | |||
raise e | |||
print("Finish calculating sentence representations.") | |||
self.sent_embeds = sent_embeds | |||
if delete_weights: | |||
self._delete_model_weights() | |||
def _get_sent_reprs(self, words): | |||
""" | |||
获取sentence的表示,如果有缓存,则返回缓存的值; 没有缓存则返回None | |||
:param words: torch.LongTensor | |||
:return: | |||
""" | |||
if hasattr(self, 'sent_embeds'): | |||
words_list = words.tolist() | |||
seq_len = words.ne(self._word_pad_index).sum(dim=-1) | |||
_embeds = [] | |||
for b in range(len(words)): | |||
words_i = tuple(words_list[b][:seq_len[b]]) | |||
embed = self.sent_embeds[words_i] | |||
_embeds.append(embed) | |||
max_sent_len = max(map(len, _embeds)) | |||
embeds = words.new_zeros(len(_embeds), max_sent_len, self.embed_size, dtype=torch.float, | |||
device=words.device) | |||
for i, embed in enumerate(_embeds): | |||
embeds[i, :len(embed)] = torch.FloatTensor(embed).to(words.device) | |||
return embeds | |||
return None | |||
@abstractmethod | |||
def _delete_model_weights(self): | |||
"""删除计算表示的模型以节省资源""" | |||
raise NotImplementedError | |||
def remove_sentence_cache(self): | |||
""" | |||
删除缓存的句子表示. 删除之后如果模型权重没有被删除,将开始使用动态计算权重。 | |||
:return: | |||
""" | |||
del self.sent_embeds |
@@ -0,0 +1,337 @@ | |||
import os | |||
import torch | |||
import torch.nn as nn | |||
import torch.nn.functional as F | |||
import json | |||
import codecs | |||
from ..core.vocabulary import Vocabulary | |||
from ..io.file_utils import cached_path, _get_base_url, PRETRAINED_ELMO_MODEL_DIR | |||
from ..modules.encoder._elmo import ElmobiLm, ConvTokenEmbedder | |||
from .contextual_embedding import ContextualEmbedding | |||
class ElmoEmbedding(ContextualEmbedding): | |||
""" | |||
别名::class:`fastNLP.embeddings.ElmoEmbedding` :class:`fastNLP.embeddings.elmo_embedding.ElmoEmbedding` | |||
使用ELMo的embedding。初始化之后,只需要传入words就可以得到对应的embedding。当前支持的使用名称初始化的模型有以下的这些(待补充) | |||
Example:: | |||
>>> vocab = Vocabulary().add_word_lst("The whether is good .".split()) | |||
>>> # 使用不同层的concat的结果 | |||
>>> embed = ElmoEmbedding(vocab, model_dir_or_name='en', layers='1,2', requires_grad=False) | |||
>>> words = torch.LongTensor([[vocab.to_index(word) for word in "The whether is good .".split()]]) | |||
>>> outputs = embed(words) | |||
>>> outputs.size() | |||
>>> # torch.Size([1, 5, 2048]) | |||
>>> # 使用不同层的weighted sum。 | |||
>>> embed = ElmoEmbedding(vocab, model_dir_or_name='en', layers='mix', requires_grad=False) | |||
>>> embed.set_mix_weights_requires_grad() # 使得weighted的权重是可以学习的,但ELMO的LSTM部分是不更新 | |||
:param vocab: 词表 | |||
:param model_dir_or_name: 可以有两种方式调用预训练好的ELMo embedding:第一种是传入ELMo所在文件夹,该文件夹下面应该有两个文件, | |||
其中一个是以json为后缀的配置文件,另一个是以pkl为后缀的权重文件;第二种是传入ELMo版本的名称,将自动查看缓存中是否存在该模型, | |||
没有的话将自动下载并缓存。 | |||
:param layers: str, 指定返回的层数(从0开始), 以,隔开不同的层。如果要返回第二层的结果'2', 返回后两层的结果'1,2'。不同的层的结果 | |||
按照这个顺序concat起来,默认为'2'。'mix'会使用可学习的权重结合不同层的表示(权重是否可训练与requires_grad保持一致, | |||
初始化权重对三层结果进行mean-pooling, 可以通过ElmoEmbedding.set_mix_weights_requires_grad()方法只将mix weights设置为可学习。) | |||
:param requires_grad: bool, 该层是否需要gradient, 默认为False. | |||
:param float word_dropout: 以多大的概率将一个词替换为unk。这样既可以训练unk也是一定的regularize。 | |||
:param float dropout: 以多大的概率对embedding的表示进行Dropout。0.1即随机将10%的值置为0。 | |||
:param cache_word_reprs: 可以选择对word的表示进行cache; 设置为True的话,将在初始化的时候为每个word生成对应的embedding, | |||
并删除character encoder,之后将直接使用cache的embedding。默认为False。 | |||
""" | |||
def __init__(self, vocab: Vocabulary, model_dir_or_name: str = 'en', layers: str = '2', requires_grad: bool = False, | |||
word_dropout=0.0, dropout=0.0, cache_word_reprs: bool = False): | |||
super(ElmoEmbedding, self).__init__(vocab, word_dropout=word_dropout, dropout=dropout) | |||
# 根据model_dir_or_name检查是否存在并下载 | |||
if model_dir_or_name.lower() in PRETRAINED_ELMO_MODEL_DIR: | |||
PRETRAIN_URL = _get_base_url('elmo') | |||
model_name = PRETRAINED_ELMO_MODEL_DIR[model_dir_or_name] | |||
model_url = PRETRAIN_URL + model_name | |||
model_dir = cached_path(model_url) | |||
# 检查是否存在 | |||
elif os.path.isdir(os.path.expanduser(os.path.abspath(model_dir_or_name))): | |||
model_dir = model_dir_or_name | |||
else: | |||
raise ValueError(f"Cannot recognize {model_dir_or_name}.") | |||
self.model = _ElmoModel(model_dir, vocab, cache_word_reprs=cache_word_reprs) | |||
if layers == 'mix': | |||
self.layer_weights = nn.Parameter(torch.zeros(self.model.config['lstm']['n_layers'] + 1), | |||
requires_grad=requires_grad) | |||
self.gamma = nn.Parameter(torch.ones(1), requires_grad=requires_grad) | |||
self._get_outputs = self._get_mixed_outputs | |||
self._embed_size = self.model.config['lstm']['projection_dim'] * 2 | |||
else: | |||
layers = list(map(int, layers.split(','))) | |||
assert len(layers) > 0, "Must choose one output" | |||
for layer in layers: | |||
assert 0 <= layer <= 2, "Layer index should be in range [0, 2]." | |||
self.layers = layers | |||
self._get_outputs = self._get_layer_outputs | |||
self._embed_size = len(self.layers) * self.model.config['lstm']['projection_dim'] * 2 | |||
self.requires_grad = requires_grad | |||
def _get_mixed_outputs(self, outputs): | |||
# outputs: num_layers x batch_size x max_len x hidden_size | |||
# return: batch_size x max_len x hidden_size | |||
weights = F.softmax(self.layer_weights + 1 / len(outputs), dim=0).to(outputs) | |||
outputs = torch.einsum('l,lbij->bij', weights, outputs) | |||
return self.gamma.to(outputs) * outputs | |||
def set_mix_weights_requires_grad(self, flag=True): | |||
""" | |||
当初始化ElmoEmbedding时layers被设置为mix时,可以通过调用该方法设置mix weights是否可训练。如果layers不是mix,调用 | |||
该方法没有用。 | |||
:param bool flag: 混合不同层表示的结果是否可以训练。 | |||
:return: | |||
""" | |||
if hasattr(self, 'layer_weights'): | |||
self.layer_weights.requires_grad = flag | |||
self.gamma.requires_grad = flag | |||
def _get_layer_outputs(self, outputs): | |||
if len(self.layers) == 1: | |||
outputs = outputs[self.layers[0]] | |||
else: | |||
outputs = torch.cat(tuple([*outputs[self.layers]]), dim=-1) | |||
return outputs | |||
def forward(self, words: torch.LongTensor): | |||
""" | |||
计算words的elmo embedding表示。根据elmo文章中介绍的ELMO实际上是有2L+1层结果,但是为了让结果比较容易拆分,token的 | |||
被重复了一次,使得实际上layer=0的结果是[token_embedding;token_embedding], 而layer=1的结果是[forward_hiddens; | |||
backward_hiddens]. | |||
:param words: batch_size x max_len | |||
:return: torch.FloatTensor. batch_size x max_len x (512*len(self.layers)) | |||
""" | |||
words = self.drop_word(words) | |||
outputs = self._get_sent_reprs(words) | |||
if outputs is not None: | |||
return self.dropout(outputs) | |||
outputs = self.model(words) | |||
outputs = self._get_outputs(outputs) | |||
return self.dropout(outputs) | |||
def _delete_model_weights(self): | |||
for name in ['layers', 'model', 'layer_weights', 'gamma']: | |||
if hasattr(self, name): | |||
delattr(self, name) | |||
@property | |||
def requires_grad(self): | |||
""" | |||
Embedding的参数是否允许优化。True: 所有参数运行优化; False: 所有参数不允许优化; None: 部分允许优化、部分不允许 | |||
:return: | |||
""" | |||
requires_grads = set([param.requires_grad for name, param in self.named_parameters() | |||
if 'words_to_chars_embedding' not in name and 'words_to_words' not in name]) | |||
if len(requires_grads) == 1: | |||
return requires_grads.pop() | |||
else: | |||
return None | |||
@requires_grad.setter | |||
def requires_grad(self, value): | |||
for name, param in self.named_parameters(): | |||
if 'words_to_chars_embedding' in name or 'words_to_words' in name: # 这个不能加入到requires_grad中 | |||
continue | |||
param.requires_grad = value | |||
class _ElmoModel(nn.Module): | |||
""" | |||
该Module是ElmoEmbedding中进行所有的heavy lifting的地方。做的工作,包括 | |||
(1) 根据配置,加载模型; | |||
(2) 根据vocab,对模型中的embedding进行调整. 并将其正确初始化 | |||
(3) 保存一个words与chars的对应转换,获取时自动进行相应的转换 | |||
(4) 设计一个保存token的embedding,允许缓存word的表示。 | |||
""" | |||
def __init__(self, model_dir: str, vocab: Vocabulary = None, cache_word_reprs: bool = False): | |||
super(_ElmoModel, self).__init__() | |||
self.model_dir = model_dir | |||
dir = os.walk(self.model_dir) | |||
config_file = None | |||
weight_file = None | |||
config_count = 0 | |||
weight_count = 0 | |||
for path, dir_list, file_list in dir: | |||
for file_name in file_list: | |||
if file_name.__contains__(".json"): | |||
config_file = file_name | |||
config_count += 1 | |||
elif file_name.__contains__(".pkl"): | |||
weight_file = file_name | |||
weight_count += 1 | |||
if config_count > 1 or weight_count > 1: | |||
raise Exception(f"Multiple config files(*.json) or weight files(*.hdf5) detected in {model_dir}.") | |||
elif config_count == 0 or weight_count == 0: | |||
raise Exception(f"No config file or weight file found in {model_dir}") | |||
with open(os.path.join(model_dir, config_file), 'r') as config_f: | |||
config = json.load(config_f) | |||
self.weight_file = os.path.join(model_dir, weight_file) | |||
self.config = config | |||
OOV_TAG = '<oov>' | |||
PAD_TAG = '<pad>' | |||
BOS_TAG = '<bos>' | |||
EOS_TAG = '<eos>' | |||
BOW_TAG = '<bow>' | |||
EOW_TAG = '<eow>' | |||
# For the model trained with character-based word encoder. | |||
char_lexicon = {} | |||
with codecs.open(os.path.join(model_dir, 'char.dic'), 'r', encoding='utf-8') as fpi: | |||
for line in fpi: | |||
tokens = line.strip().split('\t') | |||
if len(tokens) == 1: | |||
tokens.insert(0, '\u3000') | |||
token, i = tokens | |||
char_lexicon[token] = int(i) | |||
# 做一些sanity check | |||
for special_word in [PAD_TAG, OOV_TAG, BOW_TAG, EOW_TAG]: | |||
assert special_word in char_lexicon, f"{special_word} not found in char.dic." | |||
# 从vocab中构建char_vocab | |||
char_vocab = Vocabulary(unknown=OOV_TAG, padding=PAD_TAG) | |||
# 需要保证<bow>与<eow>在里面 | |||
char_vocab.add_word_lst([BOW_TAG, EOW_TAG, BOS_TAG, EOS_TAG]) | |||
for word, index in vocab: | |||
char_vocab.add_word_lst(list(word)) | |||
self.bos_index, self.eos_index, self._pad_index = len(vocab), len(vocab) + 1, vocab.padding_idx | |||
# 根据char_lexicon调整, 多设置一位,是预留给word padding的(该位置的char表示为全0表示) | |||
char_emb_layer = nn.Embedding(len(char_vocab) + 1, int(config['char_cnn']['embedding']['dim']), | |||
padding_idx=len(char_vocab)) | |||
# 读入预训练权重 这里的elmo_model 包含char_cnn和 lstm 的 state_dict | |||
elmo_model = torch.load(os.path.join(self.model_dir, weight_file), map_location='cpu') | |||
char_embed_weights = elmo_model["char_cnn"]['char_emb_layer.weight'] | |||
found_char_count = 0 | |||
for char, index in char_vocab: # 调整character embedding | |||
if char in char_lexicon: | |||
index_in_pre = char_lexicon.get(char) | |||
found_char_count += 1 | |||
else: | |||
index_in_pre = char_lexicon[OOV_TAG] | |||
char_emb_layer.weight.data[index] = char_embed_weights[index_in_pre] | |||
print(f"{found_char_count} out of {len(char_vocab)} characters were found in pretrained elmo embedding.") | |||
# 生成words到chars的映射 | |||
max_chars = config['char_cnn']['max_characters_per_token'] | |||
self.words_to_chars_embedding = nn.Parameter(torch.full((len(vocab) + 2, max_chars), | |||
fill_value=len(char_vocab), | |||
dtype=torch.long), | |||
requires_grad=False) | |||
for word, index in list(iter(vocab)) + [(BOS_TAG, len(vocab)), (EOS_TAG, len(vocab) + 1)]: | |||
if len(word) + 2 > max_chars: | |||
word = word[:max_chars - 2] | |||
if index == self._pad_index: | |||
continue | |||
elif word == BOS_TAG or word == EOS_TAG: | |||
char_ids = [char_vocab.to_index(BOW_TAG)] + [char_vocab.to_index(word)] + [ | |||
char_vocab.to_index(EOW_TAG)] | |||
char_ids += [char_vocab.to_index(PAD_TAG)] * (max_chars - len(char_ids)) | |||
else: | |||
char_ids = [char_vocab.to_index(BOW_TAG)] + [char_vocab.to_index(c) for c in word] + [ | |||
char_vocab.to_index(EOW_TAG)] | |||
char_ids += [char_vocab.to_index(PAD_TAG)] * (max_chars - len(char_ids)) | |||
self.words_to_chars_embedding[index] = torch.LongTensor(char_ids) | |||
self.char_vocab = char_vocab | |||
self.token_embedder = ConvTokenEmbedder( | |||
config, self.weight_file, None, char_emb_layer) | |||
elmo_model["char_cnn"]['char_emb_layer.weight'] = char_emb_layer.weight | |||
self.token_embedder.load_state_dict(elmo_model["char_cnn"]) | |||
self.output_dim = config['lstm']['projection_dim'] | |||
# lstm encoder | |||
self.encoder = ElmobiLm(config) | |||
self.encoder.load_state_dict(elmo_model["lstm"]) | |||
if cache_word_reprs: | |||
if config['char_cnn']['embedding']['dim'] > 0: # 只有在使用了chars的情况下有用 | |||
print("Start to generate cache word representations.") | |||
batch_size = 320 | |||
# bos eos | |||
word_size = self.words_to_chars_embedding.size(0) | |||
num_batches = word_size // batch_size + \ | |||
int(word_size % batch_size != 0) | |||
self.cached_word_embedding = nn.Embedding(word_size, | |||
config['lstm']['projection_dim']) | |||
with torch.no_grad(): | |||
for i in range(num_batches): | |||
words = torch.arange(i * batch_size, | |||
min((i + 1) * batch_size, word_size)).long() | |||
chars = self.words_to_chars_embedding[words].unsqueeze(1) # batch_size x 1 x max_chars | |||
word_reprs = self.token_embedder(words.unsqueeze(1), | |||
chars).detach() # batch_size x 1 x config['encoder']['projection_dim'] | |||
self.cached_word_embedding.weight.data[words] = word_reprs.squeeze(1) | |||
print("Finish generating cached word representations. Going to delete the character encoder.") | |||
del self.token_embedder, self.words_to_chars_embedding | |||
else: | |||
print("There is no need to cache word representations, since no character information is used.") | |||
def forward(self, words): | |||
""" | |||
:param words: batch_size x max_len | |||
:return: num_layers x batch_size x max_len x hidden_size | |||
""" | |||
# 扩展<bos>, <eos> | |||
batch_size, max_len = words.size() | |||
expanded_words = words.new_zeros(batch_size, max_len + 2) # 因为pad一定为0, | |||
seq_len = words.ne(self._pad_index).sum(dim=-1) | |||
expanded_words[:, 1:-1] = words | |||
expanded_words[:, 0].fill_(self.bos_index) | |||
expanded_words[torch.arange(batch_size).to(words), seq_len + 1] = self.eos_index | |||
seq_len = seq_len + 2 | |||
zero_tensor = expanded_words.new_zeros(expanded_words.shape) | |||
mask = (expanded_words == zero_tensor).unsqueeze(-1) | |||
if hasattr(self, 'cached_word_embedding'): | |||
token_embedding = self.cached_word_embedding(expanded_words) | |||
else: | |||
if hasattr(self, 'words_to_chars_embedding'): | |||
chars = self.words_to_chars_embedding[expanded_words] | |||
else: | |||
chars = None | |||
token_embedding = self.token_embedder(expanded_words, chars) # batch_size x max_len x embed_dim | |||
encoder_output = self.encoder(token_embedding, seq_len) | |||
if encoder_output.size(2) < max_len + 2: | |||
num_layers, _, output_len, hidden_size = encoder_output.size() | |||
dummy_tensor = encoder_output.new_zeros(num_layers, batch_size, | |||
max_len + 2 - output_len, hidden_size) | |||
encoder_output = torch.cat((encoder_output, dummy_tensor), 2) | |||
sz = encoder_output.size() # 2, batch_size, max_len, hidden_size | |||
token_embedding = token_embedding.masked_fill(mask, 0) | |||
token_embedding = torch.cat((token_embedding, token_embedding), dim=2).view(1, sz[1], sz[2], sz[3]) | |||
encoder_output = torch.cat((token_embedding, encoder_output), dim=0) | |||
# 删除<eos>, <bos>. 这里没有精确地删除,但应该也不会影响最后的结果了。 | |||
encoder_output = encoder_output[:, :, 1:-1] | |||
return encoder_output |
@@ -0,0 +1,200 @@ | |||
""" | |||
该模块中的Embedding主要用于随机初始化的embedding(更推荐使用 :class:`fastNLP.embeddings.StaticEmbedding` ),或按照预训练权重初始化Embedding。 | |||
""" | |||
import torch.nn as nn | |||
from abc import abstractmethod | |||
import torch | |||
from .utils import get_embeddings | |||
class Embedding(nn.Module): | |||
""" | |||
别名::class:`fastNLP.embeddings.Embedding` :class:`fastNLP.embeddings.embedding.Embedding` | |||
词向量嵌入,支持输入多种方式初始化. 可以通过self.num_embeddings获取词表大小; self.embedding_dim获取embedding的维度. | |||
Example:: | |||
>>> import numpy as np | |||
>>> init_embed = (2000, 100) | |||
>>> embed = Embedding(init_embed) # 随机初始化一个具有2000个词,每个词表示为100维的词向量 | |||
>>> init_embed = np.zeros((2000, 100)) | |||
>>> embed = Embedding(init_embed) # 使用numpy.ndarray的值作为初始化值初始化一个Embedding | |||
:param tuple(int,int),torch.FloatTensor,nn.Embedding,numpy.ndarray init_embed: 支持传入Embedding的大小(传入tuple(int, int), | |||
第一个int为vocab_zie, 第二个int为embed_dim); 或传入Tensor, Embedding, numpy.ndarray等则直接使用该值初始化Embedding; | |||
:param float word_dropout: 按照一定概率随机将word设置为unk_index,这样可以使得unk这个token得到足够的训练, 且会对网络有 | |||
一定的regularize的作用。设置该值时,必须同时设置unk_index | |||
:param float dropout: 对Embedding的输出的dropout。 | |||
:param int unk_index: drop word时替换为的index。fastNLP的Vocabulary的unk_index默认为1。 | |||
""" | |||
def __init__(self, init_embed, word_dropout=0, dropout=0.0, unk_index=None): | |||
super(Embedding, self).__init__() | |||
self.embed = get_embeddings(init_embed) | |||
self.dropout = nn.Dropout(dropout) | |||
if not isinstance(self.embed, TokenEmbedding): | |||
if hasattr(self.embed, 'embed_size'): | |||
self._embed_size = self.embed.embed_size | |||
elif hasattr(self.embed, 'embedding_dim'): | |||
self._embed_size = self.embed.embedding_dim | |||
else: | |||
self._embed_size = self.embed.weight.size(1) | |||
if word_dropout>0 and not isinstance(unk_index, int): | |||
raise ValueError("When drop word is set, you need to pass in the unk_index.") | |||
else: | |||
self._embed_size = self.embed.embed_size | |||
unk_index = self.embed.get_word_vocab().unknown_idx | |||
self.unk_index = unk_index | |||
self.word_dropout = word_dropout | |||
def forward(self, words): | |||
""" | |||
:param torch.LongTensor words: [batch, seq_len] | |||
:return: torch.Tensor : [batch, seq_len, embed_dim] | |||
""" | |||
if self.word_dropout>0 and self.training: | |||
mask = torch.ones_like(words).float() * self.word_dropout | |||
mask = torch.bernoulli(mask).byte() # dropout_word越大,越多位置为1 | |||
words = words.masked_fill(mask, self.unk_index) | |||
words = self.embed(words) | |||
return self.dropout(words) | |||
@property | |||
def num_embedding(self)->int: | |||
if isinstance(self.embed, nn.Embedding): | |||
return self.embed.weight.size(0) | |||
else: | |||
return self.embed.num_embedding | |||
def __len__(self): | |||
return len(self.embed) | |||
@property | |||
def embed_size(self) -> int: | |||
return self._embed_size | |||
@property | |||
def embedding_dim(self) -> int: | |||
return self._embed_size | |||
@property | |||
def requires_grad(self): | |||
""" | |||
Embedding的参数是否允许优化。True: 所有参数运行优化; False: 所有参数不允许优化; None: 部分允许优化、部分不允许 | |||
:return: | |||
""" | |||
if not isinstance(self.embed, TokenEmbedding): | |||
return self.embed.weight.requires_grad | |||
else: | |||
return self.embed.requires_grad | |||
@requires_grad.setter | |||
def requires_grad(self, value): | |||
if not isinstance(self.embed, TokenEmbedding): | |||
self.embed.weight.requires_grad = value | |||
else: | |||
self.embed.requires_grad = value | |||
@property | |||
def size(self): | |||
if isinstance(self.embed, TokenEmbedding): | |||
return self.embed.size | |||
else: | |||
return self.embed.weight.size() | |||
class TokenEmbedding(nn.Module): | |||
def __init__(self, vocab, word_dropout=0.0, dropout=0.0): | |||
super(TokenEmbedding, self).__init__() | |||
if vocab.rebuild: | |||
vocab.build_vocab() | |||
assert vocab.padding is not None, "Vocabulary must have a padding entry." | |||
self._word_vocab = vocab | |||
self._word_pad_index = vocab.padding_idx | |||
if word_dropout>0: | |||
assert vocab.unknown is not None, "Vocabulary must have unknown entry when you want to drop a word." | |||
self.word_dropout = word_dropout | |||
self._word_unk_index = vocab.unknown_idx | |||
self.dropout_layer = nn.Dropout(dropout) | |||
def drop_word(self, words): | |||
""" | |||
按照设定随机将words设置为unknown_index。 | |||
:param torch.LongTensor words: batch_size x max_len | |||
:return: | |||
""" | |||
if self.word_dropout > 0 and self.training: | |||
mask = torch.ones_like(words).float() * self.word_dropout | |||
mask = torch.bernoulli(mask).byte() # dropout_word越大,越多位置为1 | |||
words = words.masked_fill(mask, self._word_unk_index) | |||
return words | |||
def dropout(self, words): | |||
""" | |||
对embedding后的word表示进行drop。 | |||
:param torch.FloatTensor words: batch_size x max_len x embed_size | |||
:return: | |||
""" | |||
return self.dropout_layer(words) | |||
@property | |||
def requires_grad(self): | |||
""" | |||
Embedding的参数是否允许优化。True: 所有参数运行优化; False: 所有参数不允许优化; None: 部分允许优化、部分不允许 | |||
:return: | |||
""" | |||
requires_grads = set([param.requires_grad for param in self.parameters()]) | |||
if len(requires_grads) == 1: | |||
return requires_grads.pop() | |||
else: | |||
return None | |||
@requires_grad.setter | |||
def requires_grad(self, value): | |||
for param in self.parameters(): | |||
param.requires_grad = value | |||
def __len__(self): | |||
return len(self._word_vocab) | |||
@property | |||
def embed_size(self) -> int: | |||
return self._embed_size | |||
@property | |||
def embedding_dim(self) -> int: | |||
return self._embed_size | |||
@property | |||
def num_embedding(self) -> int: | |||
""" | |||
这个值可能会大于实际的embedding矩阵的大小。 | |||
:return: | |||
""" | |||
return len(self._word_vocab) | |||
def get_word_vocab(self): | |||
""" | |||
返回embedding的词典。 | |||
:return: Vocabulary | |||
""" | |||
return self._word_vocab | |||
@property | |||
def size(self): | |||
return torch.Size(self.num_embedding, self._embed_size) | |||
@abstractmethod | |||
def forward(self, words): | |||
raise NotImplementedError |