项目作者: luopeixiang

项目描述 :
TextClf :基于Pytorch/Sklearn的文本分类框架,包括逻辑回归、SVM、TextCNN、TextRNN、TextRCNN、DRNN、DPCNN、Bert等多种模型,通过简单配置即可完成数据处理、模型训练、测试等过程。
高级语言: Python
项目地址: git://github.com/luopeixiang/textclf.git


License

目录:

TextClf简介

前言

TextClf 是一个面向文本分类场景的工具箱,它的目标是可以通过配置文件快速尝试多种分类算法模型、调整参数、搭建baseline,从而让使用者能有更多精力关注于数据本身的特点,做针对性改进优化。

TextClf有以下这些特性:

  • 同时支持机器学习模型如逻辑回归、线性向量机与深度学习模型如TextCNN、TextRNN、TextRCNN、DRNN、DPCNN、Bert等等。
  • 支持多种优化方法,如AdamAdamWAdamaxRMSprop等等
  • 支持多种学习率调整的方式,如ReduceLROnPlateauStepLRMultiStepLR
  • 支持多种损失函数,如CrossEntropyLossCrossEntropyLoss with label smoothingFocalLoss
  • 可以通过和程序交互生成配置,再通过修改配置文件快速调整参数。
  • 在训练深度学习模型时,支持使用对embedding层和classifier层分别使用不同的学习率进行训练
  • 支持从断点(checkpoint)重新训练
  • 具有清晰的代码结构,可以让你很方便的加入自己的模型,使用textclf,你可以不用去关注优化方法、数据加载等方面,可以把更多精力放在模型实现上。

与其他文本分类框架 NeuralClassifier 的比较:

  • NeuralClassifier不支持机器学习模型,也不支持Bert/Xlnet等深度的预训练模型。

  • TextClf会比NeuralClassifier对新手更加友好,清晰的代码结构也会使得你能方便地对它进行拓展。

  • 特别地,对于深度学习模型,TextClf将其看成两个部分,Embedding层和Classifier层。

    Embedding层可以是随机初始化的词向量,也可以是预训练好的静态词向量(word2vec、glove、fasttext),也可以是动态词向量如BertXlnet等等。

    Classifier层可以是MLP,CNN,将来也会支持RCNN,RNN with attention等各种模型。

    通过将embedding层和classifier层分开,在配置深度学习模型时,我们可以选择对embedding层和classifier层进行排列组合,比如Bert embedding + CNNword2vec + RCNN 等等。

    这样,通过比较少的代码实现,textclf就可以涵盖更多的模型组合的可能。

系统设计思路

TextClf将文本分类的流程看成预处理、模型训练、模型测试三个阶段。

预处理阶段做的事情主要是:

  • 读入原始数据,进行分词,构建词典
  • 分析标签分布等数据特点
  • 保存成二进制的形式方便快速读入

数据经过预处理之后,我们就可以在上面训练各种模型、比较模型的效果。

模型训练阶段负责的是:

  • 读入预处理过的数据
  • 根据配置初始化模型、优化器等训练模型必需的因素
  • 训练模型,根据需要最优模型

测试阶段的功能主要是:

  • 加载训练阶段保存的模型进行测试
  • 支持使用文件输入或者终端输入两种方式进行测试

为了方便地对预处理、模型训练、模型测试阶段进行控制,TextClf使用了json文件来对相关的参数(如预处理中指定原始文件的路径、模型训练阶段指定模型参数、优化器参数等等)进行配置。运行的时候,只要指定配置文件,TextClf就会根据文件中的参数完成预处理、训练或者测试等工作,详情可参见 快速开始 部分。

目录结构

textclf源代码目录下有六个子目录和两个文件,每项的作用如下所示:

  1. ├── config # 包括预处理、模型训练、模型测试的各种参数及其默认设置
  2. ├── data # 数据预处理、数据加载的代码
  3. ├── models # 主要包括深度学习模型的实现
  4. ├── tester # 负责加载模型进行测试
  5. ├── __init__.py # 模块的初始化文件
  6. ├── main.py # textclf的接口文件,运行textclf会调用该文件中的main函数
  7. ├── trainer # 负责模型的训练
  8. └── utils # 包含各种工具函数

安装

依赖环境:python >=3.6

使用pip安装:

  1. pip install textclf

安装成功之后就可以使用textclf了!

快速开始

下面我们看一下如何使用textclf训练模型进行文本分类。

在目录examples/toutiao 下有以下文件:

  1. 3900 train.csv
  2. 600 valid.csv
  3. 600 test.csv
  4. 5100 total

这些数据来自
今日头条新闻分类数据集
在这里用作演示。

文件的格式如下:

  1. 下周一(5.7日)手上持有这些股的要小心 news_finance
  2. 猪伪狂犬苗的免疫方案怎么做? news_edu
  3. 小米7未到!这两款小米手机目前性价比最高,米粉:可惜买不到 news_tech
  4. 任何指望技术来解决社会公正、公平的设想,都是幻想 news_tech
  5. 诸葛亮能借东风火烧曹营,为什么火烧司马懿却没料到会下雨? news_culture
  6. 福利几款旅行必备神器,便宜实用颜值高! news_travel
  7. 抵押车要怎样年审和购买保险? news_car
  8. 现在一万一平米的房子,十年后大概卖多少钱? news_house
  9. 第一位有中国国籍的外国人,留中国五十多年,死前留下这样的话! news_world
  10. 为什么A股投资者越保护越亏? stock

文件每一行由两个字段组成,分别是句子和对应的label,句子和label之间使用\t字符隔开。

预处理

第一步是预处理。预处理将会完成读入原始数据,进行分词,构建词典,保存成二进制的形式方便快速读入等工作。要对预处理的参数进行控制,需要相应的配置文件,textclf中的help-config功能可以帮助我们快速生成配置,运行:

  1. textclf help-config

输入0让系统为我们生成默认的PreprocessConfig,接着将它保存成preprocess.json文件:

  1. (textclf) luo@luo-pc:~/projects$ textclf help-config
  2. Config 有以下选择(Default: DLTrainerConfig):
  3. 0. PreprocessConfig 预处理的设置
  4. 1. DLTrainerConfig 训练深度学习模型的设置
  5. 2. DLTesterConfig 测试深度学习模型的设置
  6. 3. MLTrainerConfig 训练机器学习模型的设置
  7. 4. MLTesterConfig 测试机器学习模型的设置
  8. 输入您选择的ID (q to quit, enter for default):0
  9. Chooce value PreprocessConfig 预处理的设置
  10. 输入保存的文件名(Default: config.json): preprocess.json
  11. 已经将您的配置写入到 preprocess.json,你可以在该文件中查看、修改参数以便后续使用
  12. Bye!

打开文件preprocess.json,可以看到以下内容:

  1. {
  2. "__class__": "PreprocessConfig",
  3. "params": {
  4. "train_file": "train.csv",
  5. "valid_file": "valid.csv",
  6. "test_file": "test.csv",
  7. "datadir": "dataset",
  8. "tokenizer": "char",
  9. "nwords": -1,
  10. "min_word_count": 1
  11. }
  12. }

params中是我们可以进行设置的参数,这些字段的详细含义可以查看文档
这里我们只需要把datadir字段修改成toutiao目录即可
(最好使用绝对路径,若使用相对路径,要确保当前工作目录正确访问该路径。)

然后,就可以根据配置文件进行预处理了:

  1. textclf --config-file preprocess.json preprocess

如无错误,输出如下:

  1. (textclf) luo@V_PXLUO-NB2:~/textclf/test$ textclf --config-file config.json preprocess
  2. Tokenize text from /home/luo/textclf/textclf_source/examples/toutiao/train.csv...
  3. 3900it [00:00, 311624.35it/s]
  4. Tokenize text from /home/luo/textclf/textclf_source/examples/toutiao/valid.csv...
  5. 600it [00:00, 299700.18it/s]
  6. Tokenize text from /home/luo/textclf/textclf_source/examples/toutiao/test.csv...
  7. 600it [00:00, 289795.30it/s]
  8. Label Prob:
  9. +--------------------+-------------+-------------+------------+
  10. | | train.csv | valid.csv | test.csv |
  11. +====================+=============+=============+============+
  12. | news_finance | 0.0667 | 0.0667 | 0.0667 |
  13. +--------------------+-------------+-------------+------------+
  14. | news_edu | 0.0667 | 0.0667 | 0.0667 |
  15. +--------------------+-------------+-------------+------------+
  16. | news_tech | 0.0667 | 0.0667 | 0.0667 |
  17. +--------------------+-------------+-------------+------------+
  18. | news_culture | 0.0667 | 0.0667 | 0.0667 |
  19. +--------------------+-------------+-------------+------------+
  20. | news_travel | 0.0667 | 0.0667 | 0.0667 |
  21. +--------------------+-------------+-------------+------------+
  22. | news_car | 0.0667 | 0.0667 | 0.0667 |
  23. +--------------------+-------------+-------------+------------+
  24. | news_house | 0.0667 | 0.0667 | 0.0667 |
  25. +--------------------+-------------+-------------+------------+
  26. | news_world | 0.0667 | 0.0667 | 0.0667 |
  27. +--------------------+-------------+-------------+------------+
  28. | stock | 0.0667 | 0.0667 | 0.0667 |
  29. +--------------------+-------------+-------------+------------+
  30. | news_story | 0.0667 | 0.0667 | 0.0667 |
  31. +--------------------+-------------+-------------+------------+
  32. | news_agriculture | 0.0667 | 0.0667 | 0.0667 |
  33. +--------------------+-------------+-------------+------------+
  34. | news_entertainment | 0.0667 | 0.0667 | 0.0667 |
  35. +--------------------+-------------+-------------+------------+
  36. | news_military | 0.0667 | 0.0667 | 0.0667 |
  37. +--------------------+-------------+-------------+------------+
  38. | news_sports | 0.0667 | 0.0667 | 0.0667 |
  39. +--------------------+-------------+-------------+------------+
  40. | news_game | 0.0667 | 0.0667 | 0.0667 |
  41. +--------------------+-------------+-------------+------------+
  42. | Sum | 3900.0000 | 600.0000 | 600.0000 |
  43. +--------------------+-------------+-------------+------------+
  44. Dictionary Size: 2981
  45. Saving data to ./textclf.joblib...

预处理会打印每个数据集标签分布的信息。同时,处理过后的数据被保存到二进制文件./textclf.joblib中了。
(每个类别所含的样本数是相同的。)

预处理中的详细参数说明,请查看文档

训练一个逻辑回归模型

同样的,我们先使用textclf help-config生成train_lr.json配置文件,输入3 选择训练机器学习模型的配置。
根据提示分别选择CountVectorizer(文本向量化的方式)以及模型LR

  1. (textclf) luo@luo-pc:~/projects$ textclf help-config
  2. Config 有以下选择(Default: DLTrainerConfig):
  3. 0. PreprocessConfig 预处理的设置
  4. 1. DLTrainerConfig 训练深度学习模型的设置
  5. 2. DLTesterConfig 测试深度学习模型的设置
  6. 3. MLTrainerConfig 训练机器学习模型的设置
  7. 4. MLTesterConfig 测试机器学习模型的设置
  8. 输入您选择的ID (q to quit, enter for default):3
  9. Chooce value MLTrainerConfig 训练机器学习模型的设置
  10. 正在设置vectorizer
  11. vectorizer 有以下选择(Default: CountVectorizer):
  12. 0. CountVectorizer
  13. 1. TfidfVectorizer
  14. 输入您选择的ID (q to quit, enter for default):0
  15. Chooce value CountVectorizer
  16. 正在设置model
  17. model 有以下选择(Default: LogisticRegression):
  18. 0. LogisticRegression
  19. 1. LinearSVM
  20. 输入您选择的ID (q to quit, enter for default):0
  21. Chooce value LogisticRegression
  22. 输入保存的文件名(Default: config.json): train_lr.json
  23. 已经将您的配置写入到 train_lr.json,你可以在该文件中查看、修改参数以便后续使用
  24. Bye!

对于更细粒度的配置,如逻辑回归模型的参数,CountVectorizer的参数,可以在生成的train_lr.json中进行修改。这里使用默认的配置进行训练:

  1. textclf --config-file train_lr.json train

因为数据量比较小,所以应该马上就能看到结果。训练结束后,textclf会在测试集上测试模型效果,同时将模型保存在ckpts目录下。

机器学习模型训练中的详细参数说明,请查看文档

加载训练完毕的模型进行测试分析

首先使用help-config生成MLTesterConfig的默认设置到test_lr.json

  1. (textclf) luo@luo-pc:~/projects$ textclf help-config
  2. Config 有以下选择(Default: DLTrainerConfig):
  3. 0. PreprocessConfig 预处理的设置
  4. 1. DLTrainerConfig 训练深度学习模型的设置
  5. 2. DLTesterConfig 测试深度学习模型的设置
  6. 3. MLTrainerConfig 训练机器学习模型的设置
  7. 4. MLTesterConfig 测试机器学习模型的设置
  8. 输入您选择的ID (q to quit, enter for default):4
  9. Chooce value MLTesterConfig 测试机器学习模型的设置
  10. 输入保存的文件名(Default: config.json): test_lr.json
  11. 已经将您的配置写入到 test_lr.json,你可以在该文件中查看、修改参数以便后续使用
  12. Bye!

test_lr.json中的input_file字段修改成query_intent_toy_data/test.csv 的路径,然后进行测试:

  1. textclf --config-file test_lr.json test

测试结束,textclf将会打印出准确率、每个label的f1值:

  1. Writing predicted labels to predict.csv
  2. Acc in test file:66.67%
  3. Report:
  4. precision recall f1-score support
  5. news_agriculture 0.6970 0.5750 0.6301 40
  6. news_car 0.8056 0.7250 0.7632 40
  7. news_culture 0.7949 0.7750 0.7848 40
  8. news_edu 0.8421 0.8000 0.8205 40
  9. news_entertainment 0.6000 0.6000 0.6000 40
  10. news_finance 0.2037 0.2750 0.2340 40
  11. news_game 0.7111 0.8000 0.7529 40
  12. news_house 0.7805 0.8000 0.7901 40
  13. news_military 0.8750 0.7000 0.7778 40
  14. news_sports 0.7317 0.7500 0.7407 40
  15. news_story 0.7297 0.6750 0.7013 40
  16. news_tech 0.6522 0.7500 0.6977 40
  17. news_travel 0.6410 0.6250 0.6329 40
  18. news_world 0.6585 0.6750 0.6667 40
  19. stock 0.5000 0.4750 0.4872 40
  20. accuracy 0.6667 600
  21. macro avg 0.6815 0.6667 0.6720 600
  22. weighted avg 0.6815 0.6667 0.6720 600

关于机器学习模型测试中的详细参数,请查看文档

训练TextCNN模型

训练深度学习模型TextCNN的过程与训练逻辑回归的流程大体一致。

这里简单做一下说明。先通过help-config进行配置,根据提示,先选择DLTrainerConfig ,然后再先后选择Adam optimzer + ReduceLROnPlateau + StaticEmbeddingLayer + CNNClassifier + CrossEntropyLoss即可。

  1. (textclf) luo@V_PXLUO-NB2:~/textclf/test$ textclf help-config
  2. Config 有以下选择(Default: DLTrainerConfig):
  3. 0. PreprocessConfig 预处理的设置
  4. 1. DLTrainerConfig 训练深度学习模型的设置
  5. 2. DLTesterConfig 测试深度学习模型的设置
  6. 3. MLTrainerConfig 训练机器学习模型的设置
  7. 4. MLTesterConfig 测试机器学习模型的设置
  8. 输入您选择的ID (q to quit, enter for default):
  9. Chooce default value: DLTrainerConfig
  10. 正在设置optimizer
  11. optimizer 有以下选择(Default: Adam):
  12. 0. Adam
  13. 1. Adadelta
  14. 2. Adagrad
  15. 3. AdamW
  16. 4. Adamax
  17. 5. ASGD
  18. 6. RMSprop
  19. 7. Rprop
  20. 8. SGD
  21. 输入您选择的ID (q to quit, enter for default):
  22. Chooce default value: Adam
  23. 正在设置scheduler
  24. scheduler 有以下选择(Default: NoneScheduler):
  25. 0. NoneScheduler
  26. 1. ReduceLROnPlateau
  27. 2. StepLR
  28. 3. MultiStepLR
  29. 输入您选择的ID (q to quit, enter for default):
  30. Chooce default value: NoneScheduler
  31. 正在设置model
  32. 正在设置embedding_layer
  33. embedding_layer 有以下选择(Default: StaticEmbeddingLayer):
  34. 0. StaticEmbeddingLayer
  35. 1. BertEmbeddingLayer
  36. 输入您选择的ID (q to quit, enter for default):
  37. Chooce default value: StaticEmbeddingLayer
  38. 正在设置classifier
  39. classifier 有以下选择(Default: CNNClassifier):
  40. 0. CNNClassifier
  41. 1. LinearClassifier
  42. 2. RNNClassifier
  43. 3. RCNNClassifier
  44. 4. DRNNClassifier
  45. 5. DPCNNClassifier
  46. 输入您选择的ID (q to quit, enter for default):0
  47. Chooce value CNNClassifier
  48. 正在设置data_loader
  49. 正在设置criterion
  50. criterion 有以下选择(Default: CrossEntropyLoss):
  51. 0. CrossEntropyLoss
  52. 1. FocalLoss
  53. 输入您选择的ID (q to quit, enter for default):q^Hq
  54. 请输入整数ID
  55. 输入您选择的ID (q to quit, enter for default):q
  56. Goodbye!
  57. (textclf) luo@V_PXLUO-NB2:~/textclf/test$
  58. (textclf) luo@V_PXLUO-NB2:~/textclf/test$ textclf help-config
  59. Config 有以下选择(Default: DLTrainerConfig):
  60. 0. PreprocessConfig 预处理的设置
  61. 1. DLTrainerConfig 训练深度学习模型的设置
  62. 2. DLTesterConfig 测试深度学习模型的设置
  63. 3. MLTrainerConfig 训练机器学习模型的设置
  64. 4. MLTesterConfig 测试机器学习模型的设置
  65. 输入您选择的ID (q to quit, enter for default):1
  66. Chooce value DLTrainerConfig 训练深度学习模型的设置
  67. 正在设置optimizer
  68. optimizer 有以下选择(Default: Adam):
  69. 0. Adam
  70. 1. Adadelta
  71. 2. Adagrad
  72. 3. AdamW
  73. 4. Adamax
  74. 5. ASGD
  75. 6. RMSprop
  76. 7. Rprop
  77. 8. SGD
  78. 输入您选择的ID (q to quit, enter for default):0
  79. Chooce value Adam
  80. 正在设置scheduler
  81. scheduler 有以下选择(Default: NoneScheduler):
  82. 0. NoneScheduler
  83. 1. ReduceLROnPlateau
  84. 2. StepLR
  85. 3. MultiStepLR
  86. 输入您选择的ID (q to quit, enter for default):0
  87. Chooce value NoneScheduler
  88. 正在设置model
  89. 正在设置embedding_layer
  90. embedding_layer 有以下选择(Default: StaticEmbeddingLayer):
  91. 0. StaticEmbeddingLayer
  92. 1. BertEmbeddingLayer
  93. 输入您选择的ID (q to quit, enter for default):0
  94. Chooce value StaticEmbeddingLayer
  95. 正在设置classifier
  96. classifier 有以下选择(Default: CNNClassifier):
  97. 0. CNNClassifier
  98. 1. LinearClassifier
  99. 2. RNNClassifier
  100. 3. RCNNClassifier
  101. 4. DRNNClassifier
  102. 5. DPCNNClassifier
  103. 输入您选择的ID (q to quit, enter for default):0
  104. Chooce value CNNClassifier
  105. 正在设置data_loader
  106. 正在设置criterion
  107. criterion 有以下选择(Default: CrossEntropyLoss):
  108. 0. CrossEntropyLoss
  109. 1. FocalLoss
  110. 输入您选择的ID (q to quit, enter for default):0
  111. Chooce value CrossEntropyLoss
  112. 输入保存的文件名(Default: config.json): train_cnn.json
  113. 已经将您的配置写入到 train_cnn.json,你可以在该文件中查看、修改参数以便后续使用
  114. Bye!

然后运行:

  1. textclf --config-file train_cnn.json train

即可开始训练我们配置好的textcnn模型。

当然,在训练结束之后,我们也可以通过DLTesterConfig配置来测试模型效果。而且,如果你想使用预训练的静态embedding如word2vec、glove只需要修改配置文件即可。

上述就是TextCNN的训练过程。如果你想尝试更多的模型,比如Bert,只需要在设置DLTrainerConfig时将EmbeddingLayer设置为 BertEmbeddingLayer,并且在生成的配置文件中手动设置一下预训练Bert模型的路径。这里就不再赘述了。

本节的相关文档:

训练深度学习模型的详细参数说明

测试深度学习模型的详细参数说明

textclf文档

TODO

  • 加入多模型集成评估和预测
  • 加载训练好的模型,提供api服务
  • 自动调参(?)

参考

DeepText/NeuralClassifier

pytext