├── .gitignore ├── LICENSE ├── README.md ├── __init__.py ├── keras_textclassification ├── __init__.py ├── base │ ├── __init__.py │ ├── embedding.py │ └── graph.py ├── conf │ ├── __init__.py │ ├── logger_config.py │ └── path_config.py ├── data │ ├── __init__.py │ ├── baidu_qa_2019 │ │ ├── baike_qa_train.csv │ │ └── baike_qa_valid.csv │ ├── byte_multi_news │ │ ├── labels.csv │ │ ├── readme.md │ │ ├── train.csv │ │ └── valid.csv │ ├── embeddings │ │ ├── albert_base_zh │ │ │ └── __init__.py │ │ ├── chinese_L-12_H-768_A-12 │ │ │ └── __init__.py │ │ ├── chinese_xlnet_mid_L-24_H-768_A-12 │ │ │ └── __init__.py │ │ ├── term_char.txt │ │ ├── term_word.txt │ │ ├── w2v_model_merge_short.vec │ │ └── w2v_model_wiki_char.vec │ ├── model │ │ ├── __init__.py │ │ └── fast_text │ │ │ └── __init__.py │ └── sim_webank │ │ ├── test.csv │ │ ├── train.csv │ │ └── valid.csv ├── data_preprocess │ ├── __init__.py │ ├── data_split.py │ ├── generator_preprocess.py │ └── text_preprocess.py ├── keras_layers │ ├── __init__.py │ ├── __pycache__ │ │ ├── Attention_self.cpython-36.pyc │ │ └── __init__.cpython-36.pyc │ ├── albert │ │ ├── __init__.py │ │ └── albert.py │ ├── attention_dot.py │ ├── attention_self.py │ ├── capsule.py │ ├── highway.py │ ├── k_max_pooling.py │ ├── keras_lookahead.py │ ├── keras_radam.py │ ├── non_mask_layer.py │ ├── transformer.py │ └── transformer_utils │ │ ├── __init__.py │ │ ├── embedding.py │ │ ├── feedforward.py │ │ ├── layer_normalization.py │ │ ├── multi_head_attention.py │ │ ├── readme.md │ │ ├── scale_dot_product_attention.py │ │ └── triangle_position_embedding.py ├── m00_Albert │ ├── __init__.py │ ├── graph.py │ ├── predict.py │ └── train.py ├── m00_Bert │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-36.pyc │ │ └── graph.cpython-36.pyc │ ├── graph.py │ ├── predict.py │ └── train.py ├── m00_Xlnet │ ├── __init__.py │ ├── graph.py │ ├── predict.py │ └── train.py ├── m01_FastText │ ├── __init__.py │ ├── graph.py │ ├── predict.py │ └── train.py ├── m02_TextCNN │ ├── __init__.py │ ├── graph.py │ ├── predict.py │ └── train.py ├── m03_CharCNN │ ├── __init__.py │ ├── graph_yoon_kim.py │ ├── graph_zhang.py │ ├── predict.py │ ├── train.py │ └── train_zhang.py ├── m04_TextRNN │ ├── __init__.py │ ├── graph.py │ ├── predict.py │ └── train.py ├── m05_TextRCNN │ ├── __init__.py │ ├── graph.py │ ├── predict.py │ └── train.py ├── m06_TextDCNN │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-36.pyc │ │ └── graph.cpython-36.pyc │ ├── graph.py │ ├── predict.py │ └── train.py ├── m07_TextDPCNN │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-36.pyc │ │ └── graph.cpython-36.pyc │ ├── graph.py │ ├── predict.py │ └── train.py ├── m08_TextVDCNN │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-36.pyc │ │ └── graph.cpython-36.pyc │ ├── graph.py │ ├── predict.py │ └── train.py ├── m09_TextCRNN │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-36.pyc │ │ └── graph.cpython-36.pyc │ ├── graph.py │ ├── predict.py │ └── train.py ├── m10_DeepMoji │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-36.pyc │ │ └── graph.cpython-36.pyc │ ├── graph.py │ ├── predict.py │ └── train.py ├── m11_SelfAttention │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-35.pyc │ │ ├── __init__.cpython-36.pyc │ │ ├── graph.cpython-35.pyc │ │ └── graph.cpython-36.pyc │ ├── graph.py │ ├── predict.py │ └── train.py ├── m12_HAN │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-35.pyc │ │ └── graph.cpython-35.pyc │ ├── graph.py │ ├── predict.py │ └── train.py ├── m13_CapsuleNet │ ├── __init__.py │ ├── graph.py │ ├── predict.py │ └── train.py ├── m14_Transformer │ ├── __init__.py │ ├── graph.py │ ├── predict.py │ └── train.py ├── m15_SWEM │ ├── __init__.py │ ├── graph.py │ ├── predict.py │ └── train.py ├── m16_LEAM │ ├── __init__.py │ ├── graph.py │ ├── predict.py │ └── train.py └── text_classification_api.py ├── requirements.txt ├── setup.py └── test ├── __init__.py ├── fit_generator ├── __init__.py ├── tet_fit_data_generator.py ├── tet_fit_data_generator_textcnn.py └── tet_predict_data_generator_textcnn.py ├── flask ├── __init__.py └── model_flask.py ├── multi_label_class ├── __init__.py ├── predict_multi.py └── train_multi.py ├── predict_bert_text_cnn.py ├── save2load └── estimator_ │ └── estimator_tst.py ├── sentence_similarity ├── __init__.py ├── predict.py └── train.py ├── tet_char_albert_embedding.py ├── tet_char_bert_embedding.py ├── tet_char_random_embedding.py ├── tet_char_word2vec_embedding.py ├── tet_char_xlnet_embedding.py ├── tet_train.py ├── tet_word_random_embedding.py ├── tet_word_word2vec_embedding.py └── tft_tensorflow_transformer ├── __init__.py └── graph.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | db.sqlite3 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # Environments 85 | .env 86 | .venv 87 | env/ 88 | venv/ 89 | ENV/ 90 | env.bak/ 91 | venv.bak/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 yongzhuo 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/3 10:50 4 | # @author :Mo 5 | # @function : -------------------------------------------------------------------------------- /keras_textclassification/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/13 16:13 4 | # @author :Mo 5 | # @function : 6 | 7 | 8 | import sys 9 | import os 10 | path_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) 11 | sys.path.append(path_root) 12 | from distutils.util import strtobool 13 | 14 | 15 | # gpu/tf日志的环境, 默认CPU 16 | os.environ["CUDA_VISIBLE_DEVICES"] = os.environ.get("CUDA_VISIBLE_DEVICES", "-1") # "0,1" 17 | os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" 18 | os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" 19 | # 自动化(默认AUTO), 即定义是不是高自由度, 如"CUSTOM"可以高度自定义, 网络架构embedding/graph/loss等均可高度自定义 20 | # 默认使用keras_textclassification.keras 21 | 22 | tf_keras = os.environ.get("TF_KERAS", "0") 23 | print(tf_keras) 24 | is_tf_keras = strtobool(tf_keras) 25 | 26 | 27 | if is_tf_keras: 28 | import tensorflow as tf 29 | # Python Import机制备忘-模块搜索路径(sys.path)、嵌套Import、package Import 30 | sys.modules["keras"] = tf.keras 31 | 32 | 33 | __version__ = "0.2.0" 34 | 35 | -------------------------------------------------------------------------------- /keras_textclassification/base/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/3 11:24 4 | # @author :Mo 5 | # @function : -------------------------------------------------------------------------------- /keras_textclassification/conf/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/5 21:04 4 | # @author :Mo 5 | # @function : -------------------------------------------------------------------------------- /keras_textclassification/conf/logger_config.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/7/28 0:24 4 | # @author :Mo 5 | # @function :logger 6 | 7 | 8 | from keras_textclassification.conf.path_config import path_root 9 | from logging.handlers import RotatingFileHandler 10 | import logging 11 | import time 12 | import os 13 | 14 | 15 | # log目录地址 16 | path_logs = path_root + '/logs' 17 | if not os.path.exists(path_logs): 18 | os.mkdir(path_logs) 19 | # 全局日志格式 20 | logging.basicConfig(level=logging.INFO, 21 | format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s') 22 | # 定义一个日志记录器 23 | logger = logging.getLogger("Keras-TextClassification") 24 | logger.setLevel(level = logging.INFO) 25 | # 日志文件名,为启动时的日期 26 | log_file_name = time.strftime('%Y-%m-%d', time.localtime(time.time())) + ".log" 27 | log_name_day = os.path.join(path_logs, log_file_name) 28 | # 文件输出, 定义一个RotatingFileHandler,最多备份32个日志文件,每个日志文件最大32K 29 | rHandler = RotatingFileHandler(log_name_day, maxBytes = 32*1024, backupCount = 32) 30 | rHandler.setLevel(logging.INFO) 31 | # 日志输出格式 32 | formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') 33 | rHandler.setFormatter(formatter) 34 | # 控制台输出 35 | console = logging.StreamHandler() 36 | console.setLevel(logging.INFO) 37 | console.setFormatter(formatter) 38 | # logger加到handel里边 39 | logger.addHandler(rHandler) 40 | logger.addHandler(console) 41 | # 所有文件共用一个logger 42 | def get_logger_root(): 43 | return logging.getLogger("Keras-TextClassification") 44 | 45 | 46 | if __name__ == '__main__': 47 | logger = get_logger_root() 48 | logger.info("test") 49 | -------------------------------------------------------------------------------- /keras_textclassification/conf/path_config.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/5 21:04 4 | # @author :Mo 5 | # @function :file of path 6 | 7 | import os 8 | 9 | # 项目的根目录 10 | path_root = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)) 11 | path_root = path_root.replace('\\', '/') 12 | 13 | # path of embedding 14 | path_embedding_random_char = path_root + '/data/embeddings/term_char.txt' 15 | path_embedding_random_word = path_root + '/data/embeddings/term_word.txt' 16 | path_embedding_bert = path_root + '/data/embeddings/chinese_L-12_H-768_A-12/' 17 | path_embedding_xlnet = path_root + '/data/embeddings/chinese_xlnet_base_L-12_H-768_A-12/' 18 | path_embedding_albert = path_root + '/data/embeddings/albert_base_zh' 19 | path_embedding_vector_word2vec_char = path_root + '/data/embeddings/w2v_model_wiki_char.vec' 20 | path_embedding_vector_word2vec_word = path_root + '/data/embeddings/w2v_model_merge_short.vec' 21 | 22 | # classify data of tnews 23 | path_tnews_train = path_root + '/data/tnews/train.csv' 24 | path_tnews_valid = path_root + '/data/tnews/dev.csv' 25 | 26 | # classify data of baidu qa 2019 27 | path_baidu_qa_2019_train = path_root + '/data/baidu_qa_2019/baike_qa_train.csv' 28 | path_baidu_qa_2019_valid = path_root + '/data/baidu_qa_2019/baike_qa_valid.csv' 29 | 30 | # 今日头条新闻多标签分类 31 | path_byte_multi_news_train = path_root + '/data/byte_multi_news/train.csv' 32 | path_byte_multi_news_valid = path_root + '/data/byte_multi_news/valid.csv' 33 | path_byte_multi_news_label = path_root + '/data/byte_multi_news/labels.csv' 34 | 35 | # classify data of baidu qa 2019 36 | path_sim_webank_train = path_root + '/data/sim_webank/train.csv' 37 | path_sim_webank_valid = path_root + '/data/sim_webank/valid.csv' 38 | path_sim_webank_test = path_root + '/data/sim_webank/test.csv' 39 | 40 | # fast_text config 41 | # 模型目录 42 | path_model_dir = path_root + "/data/model/fast_text/" 43 | # 语料地址 44 | path_model = path_root + '/data/model/fast_text/model_fast_text.h5' 45 | # 超参数保存地址 46 | path_hyper_parameters = path_root + '/data/model/fast_text/hyper_parameters.json' 47 | # embedding微调保存地址 48 | path_fineture = path_root + "/data/model/fast_text/embedding_trainable.h5" 49 | -------------------------------------------------------------------------------- /keras_textclassification/data/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/3 10:50 4 | # @author :Mo 5 | # @function : -------------------------------------------------------------------------------- /keras_textclassification/data/baidu_qa_2019/baike_qa_train.csv: -------------------------------------------------------------------------------- 1 | label,ques 2 | 教育,人站 在 地球 上 为什么 没有 头朝下 的 感觉 3 | 娱乐,我 的 小 baby 4 | 电脑,松本 面板 可以 配 什么 品牌 的 超五类 模块 5 | 生活,请教 怎么 能 很快 能 洗 干净 猪肠 有 什么 方法 6 | 健康,毛孔 粗大 怎么办 我 脸上 长 豆豆 出 油 额头 鼻子 上 脸上 都 有 毛孔 很 7 | 健康,黑河市 治疗 癫痫 最 权威 的 医院 有 哪些 8 | 健康,降压药 的 选择 不 知道 波依定 和 洛活 喜 两种 药 各有 什么 特点 适合 哪种 人服 9 | 游戏,有 6 区 无尽 之海众 神之子 工会 的 吗 你们 会 怎么 了 看不见 人 了 解散 了 10 | 商业,老师 好 青 青稞酒 明天 再 跌 就 可以 建仓 了 吗 谢谢 11 | 生活,邯郸市 哪里 有 卖纳威 沙发 12 | 社会,请 各位 老师 讲解 如图所示 A B 是 圆 的 直径 的 两端 小张 在 A 点 13 | 电脑,Word 文档 一页 半 文字 怎样 调整 使 其 真 好 布满 两页 14 | 娱乐,出 大事 了 出 大事 了 你 知道 吗 武汉 江夏 公安分局 接到 群众 举报电话 说 在 天 15 | 教育,简单 的 地理 基础知识 填空 要 100 正确 一 考点 知识 清单 一 地图 1 16 | 健康,下体 很痒 怎么回事 是 什么 原因 呢 长 了 一些 像 疹子 一样 的 东西 正好 我 17 | 电子,为什么 手机 连不上 wifi 我 的 手机 型号 是 lephone1800 18 | 电子,华为 手机 芯片 19 | 健康,请问 吃 紧急 避孕药 月经 推迟 多久 才 是 正常 的 我 因为 吃 了 那药 月经 已经 20 | 健康,霉菌性 阴道炎 会上 行 感染 胎儿 吗 目前 未确定 怀孕 但 怀孕 可能性 较大 我 1 21 | 教育,公鸡 和 母鸡 是 怎么 交配 的 如何 受精 产生 小鸡 22 | 电脑,word 中想 只 插入 一个 键 箭头 如何 居中 我 在 word 中 我 想 打 一个 23 | 健康,怎样 快点 长高 我 160 想长 高 5 厘米 怎么 可以 长高 24 | 娱乐,根据 我 的 中文名 来 取个 英文名 苏金凤 根据 我 的 中文名 来 取个 英文名 本人 苏 25 | 生活,16 个 月 男 宝宝 长 8 颗 牙齿 我家 宝宝 16 个 月 1 才 长 8 颗 牙齿 26 | 娱乐,求解 这是 什么 东西 啊 27 | 游戏,DZ 怎么 才能 在 大 战场 立脚 我 的 盗贼 无 BUFF3700 血 为了 拿 2 把 28 | 育儿,宝宝 腹泻 一周 吃 了 药 不 见效 用换 腹泻 奶粉 吗 已有 宝宝 年龄 1 岁 2 29 | 教育,一元 一次方程 车间 有 28 名 工人 生产 一种 螺栓 和 螺帽 一个 螺栓 的 两 30 | 娱乐,电影票房 是 怎样 计算 的 31 | 教育,将 SO2 气体 分别 通入 什么 溶液 中 能 出现 下述 现象 紫色 变 红色 紫 32 | 社会,请问 什么 工作 或 职业 最 赚钱 33 | 健康,重庆 哪里 可以 治疗 尖锐湿疣 能 不 复发 34 | 教育,西方 经济学 论文 代发 怎么样 各位 都 有 这方面 的 经验 吗 都 尽量 说 说 吧 35 | 游戏,上古 运动会 有人 作弊 吗 我 知道 上古 运动会 的 时间 是 下午 的 3 点 5 点 和 7 点 36 | 汽车,大纳智捷 生活馆 是 怎样 看车 的 37 | 娱乐,期任 九 108 元 初单 欢迎 指教 1 年轻人 vs 利物浦 2 乌迪内 vs 安 38 | 游戏,真有 这么 巧 的 事 建立 个小弓 和 一 转前 的 武器 前 4 手上 了 3 个 G10 老婆 39 | 电脑,怎么 安装 双系统 知道 的 进 高分 我 现在 用 的 是 XP 系统 但是 我 还 想安 40 | 烦恼,九年 级 相似 图形 在 梯形 ABCD 中 AD BC E 是 AB 上 的 一点 41 | 商业,华夏 公司 网上交易 使用 的 广发卡 是 广发 理财 通卡 吗 如 题 广发 理财 通卡 42 | 文化,历史 上 西施 活 了 多少岁 43 | 社会,我 儿子 从 高一上 学期 与 班 中 的 一位 女 体育 特长生 关系密切 后 发现 他 对学 44 | 游戏,请问 11 服 的 钢铁 原石值 多少 钱 呀 45 | 生活,宝宝 这是 鼻炎 吗 宝宝 鼻塞 半个 月 刚 开始 的 鼻涕 是 白色 带 黄 后来 是 黄 46 | 生活,用 了 祛痘 洗面奶 反而 脸上 长痘痘 了 怎么回事 啊 47 | 文化,项链 的 作者 是 谁 48 | 生活,不 睡 枕头 对 颈椎病 好 吗 他们 说 有 颈椎病 的 人 最好 不 睡 枕头 49 | 烦恼,怎样才能 使 自己 的 内心 强大 起来 50 | 烦恼,他 这样 是 爱我吗 我们 是 经人介绍 认识 认识 到 现在 已经 有 三个 月 了 自 51 | 教育,竹炭 煮水 的 好处 在 水壶 里 放 两大片 洗净 的 竹 碳 坐水时 一起 煮 这样 的 开 52 | 健康,上海 哪家 医院 治疗 输卵管 堵塞 好 53 | 生活,冬天 进补 好 呢 还是 夏天 好 54 | 生活,夏季 如何 进行 饮食 调养 养生 55 | 教育,请问 钨 钼 钨 铝丝 的 居里点 是 多少 56 | 游戏,我 写 了 我 的 姓名 和 身份证 号码 通过 哪个 未成年 许可 怎么 像是 没 反应 的 啊 57 | 健康,为什么 会得 癔症 58 | 健康,形成 胆结石 的 原因 是 59 | 生活,外贸服装 哪里 进货 像 第一 街 署光里 那些 外贸服装 都 从 哪里 进货 60 | 医疗,辐射 防护 该 怎么 做 呢 61 | 烦恼,我 好 心疼 哦 我 听说 喜欢 的 人 已经 有 心上人 了 我 好 心疼 哦 你们 可 62 | 商业,我 就 贷款 买 基金 了 今年 贷款 买 了 好多 的 基金 啊 收益 25 还 多 从 八月 到 63 | 教育,鬣狗 和 野狗 的 外观 和 毛色 都 差不多 为何 名称 不同 64 | 商业,同花顺 2007 标准版 和 同花顺 盛大 密宝 有 什么 区别 同花顺 里 有 同花顺 2 65 | 社会,T 66 | 电脑,主板 启动 电脑 想 问 一下 在 主机 开关 出现 故障 时 直接 利用 主板 如何 启动 67 | 生活,的 鼻子 很大 而且 没有 鼻梁 难看 死 了 有没有 办法 变小 或者 鼻梁 变挺 68 | 健康,老是 感到 胸闷 是 怎么回事 我 40 岁 老是 感到 胸闷 喘 不过 气来 . 有 69 | 生活,今天 我 MM 被 诊断 为 肺炎 虽然 她 确实 高烧 可是 并 没有 咳嗽 症状 这个 70 | 游戏,电信 1 黄金 车身 1 型 的 价位 在 多少 71 | 电脑,通过 qq 如何 控制 对方 电脑 72 | 商业,这 两天 嘉实 300 和 南方 稳健 都 要 大 比例 分红 了 . 分完 净值 都 在 1 左右 了 73 | 教育,穷 在 句 中 的 意思 穷追猛打 中穷 是 极端 的 意思 还是 彻底 的 意思 74 | 电脑,电子词典 选 什么 牌子 的 五一 想 入手 一款 电子词典 该选 什么 牌子 的 要 75 | 游戏,谁 帮 我 捉 1 只 火暴 萝卜 和 1 个 火爆 樱桃 是 火暴 的 76 | 健康,女人体 香是 怎么回事 77 | 商业,有关 专利发明 奖金 是否 要 缴纳 个人所得税 哪位 大仙 知道 公司 对 职务 发明 78 | 文化,请问 这句 莫名其妙 的 诗句 是 什么 意思 完整 的 如下 太窥门 夹豆 丫洗 盆 79 | ,微博 是不是 可以 有个 类似 于 qq 空间 的 功能 谁 来 微博 主页 了 就 发个 消息 80 | 游戏,55 级 的 菩提 宝杖 从 哪 打 出来 的 81 | 游戏,都 是 新手 问题 帮助 新手 的 非常简单 新手 请 回答 问题 一 说出 一个 怪 82 | 社会,什么 是 社会主义 社会主义 的 本质 是 什么 83 | 健康,重庆 大坪 医院 打胎 大概 多少 钱 84 | 游戏,3 个 战场 的 双倍 声望 时间 请 说 的 详细 些 85 | 生活,从 上海 森勤 国际 大酒店 到 上海 维也纳 国际 大酒店 有多远 86 | 游戏,淡谈 真三武名 系统 取消 后 的 波澜 关于 这次 武名 系统 取消 同意 的 占 大多数 87 | 生活,为什么 上海 地铁 单单 只有 上海 马戏 城站 的 站台 上 有门 同 标题 88 | 商业,关于 基金 啥 叫 前端 申购 代码 后 端 申购 代码 . 有 啥 区别 . 有 甚么 作用 . 89 | 娱乐,小 联赛 足彩 延期 开奖 推迟 比赛 或 310 全算 对 新浪 体育讯 北京 时间 12 90 | 游戏,进入 易玩通 网站 怎么 看不见 我 还有 多少 点 呀 还是 0 点 去 哪能 看到 91 | 生活,北京 哪里 礼物 便宜 毛绒玩具 哦 质量 也 要 好 92 | 娱乐,大家 都 买 了 多少 钱 93 | 游戏,级敏白 妖 加点 问题 我 是 级敏 妖 拿 刀 请问 那个 点 是 加 什么 好 呢 94 | ,不 知道 什么 意思 95 | ,GDA 96 | ,NAN 类 97 | 体育,去 打 篮球 吧 98 | 体育,科比 在 NBA 打 篮球 99 | 体育,世界杯 怎么 我 想 跑步 100 | 资源,稀土 中国 不行 101 | 资源,石油 很贵 中石油 102 | -------------------------------------------------------------------------------- /keras_textclassification/data/baidu_qa_2019/baike_qa_valid.csv: -------------------------------------------------------------------------------- 1 | label,ques 2 | 烦恼,请问 深入骨髓 地 喜欢 一个 人 怎么办 我 不能 确定 对方 是不是 喜欢 我 我 却 想 3 | 游戏,我 登陆 诛仙 2 时 总 说 我 账号密码 错误 但是 我 打 的 是 正确 的 就算 不 对 我 4 | 游戏,斩 魔仙 者 称号 怎么 得来 的 5 | 商业,有 哪位 好心人 上传 一份 女 衬衫 的 加拿大 海关 发票 给 我 看 一下 塞 多谢 了 6 | 娱乐,想 去 澳州 看 亲戚 二个 星期 怎么 去 求教 7 | 生活,送 男生 什么 生日礼物 好 呢 思考 8 | 教育,英语 音节 划分 问题 在 重读 和 非重 读音节 的 相邻 处 只有 一个 辅 字组 时 如果 9 | 教育,厂房 内有 吊车 起吊 高度 怎么 定 厂房 内有 吊车 牛腿 高度 怎么 定 根据 10 | 育儿,你好 请问 有 疼痛 晕厥 史 的 产妇 可以 顺产 吗 11 | 商业,投资 个人 理财产品 需注意 哪些 问题 12 | 健康,女性 经常 有作 乳房 自查 是否 不用 每年 上 医院 作 体检 了 经常 自查 乳房 的 13 | 文化,我爱你 古文 怎么 说 14 | 教育,为什么 没有 副 总书记 一职 15 | 教育,已知 a b 都 是 锐角 tana 4 3 tanb 1 7 求 a 16 | 娱乐,请教 一下 这是 什么 植物 谢谢 17 | 游戏,家族 建立 必须 等级 我 看 新浪 任务 说 家族 建立 的 必须 条件 是 LV50 18 | 健康,牙龈 包住 牙齿 怎么办 19 | 教育,加强 调 的 着重号 有 什么 作用 列宁 指出 物质 是 标志 客观实在 的 哲 20 | 电脑,请问 这样 一个 配置 需要 多大 的 电源 cpu AMD 羿龙 X38450 21 | 教育,翻译 3Shedescribestheexperienceof15 22 | 娱乐,网络 上 真的 没有 帅哥美女 吗 突然 间 想到 的 以前 在 哪里 看到 过 是 这么 23 | 生活,耳朵 怎么 了 宝宝 晚上 睡觉 总是 翻来覆去 的 仿佛 睡 不 塌实 而且 每次 翻身 24 | 生活,北京 房产证 过户 手续 怎么办 夫妻 两人 一人先 走 房产 过户 另 一个 人 手 25 | 健康,面烧糊 了 还 能 吃 吗 糊味 明显 吃 了 对 健康 影响 大 吗 26 | 社会,刚 毕业 的 大学生 怎样 考 职称 吗 求教 刚 毕业 的 大学生 可以 怎样 考 职称 27 | 娱乐,求 好看 的 动漫 28 | 游戏,为什么 我起 名字 老是 不 合法 这个 游戏 不 可以 起 带有 特殊符号 的 名字 吗 29 | 健康,你 相信 这个 世上 有 真 爱 吗 我 觉得 人 在 一起 久 了 就 会 有 感情 你们 说 呢 30 | 教育,我家 公猫 为什么 晚上 乱叫 呀 31 | 健康,你好 我家 宝宝 7 多月 这 几天 拉肚子 去 医院 检查 说 是 细菌 感染 肠炎 吃 32 | 游戏,关于 安装 台服 的 问题 等 CWOW 遥遥无期 鄙人 也 花 了 一天 时间 下载 了 台 33 | 娱乐,李克勤 什么 歌 好听 34 | 健康,血压 140 105 我 18 岁 征兵 体检 时 发现 有 高血压 30 岁 时 偶尔 会 35 | 生活,有人 知道 宝宝 补锌 产品 排行榜 么 知道 的 可以 说 说 建议 上面 什么 产品 比 36 | 生活,春装 秋装 区别 我 想 知道 春装 和 秋装 的 区别 要 详细 地说 37 | 生活,全国 的 邮政 小包 价格 一样 吗 38 | 商业,广发 货币基金 转聚丰 需要 几天 39 | 生活,上海 简单 有效 的 祛斑 方法 祛斑 需要 多少 钱 40 | 游戏,怀旧 我 想 打 阿鲁巴 斯 要 拿 护士 帽 吗 怎么 个 流程 话 说 我 玩 这么久 没直 41 | 电子,为什么 低端 的 数码相机 采用 CMOS 传感器 高级 一点 采用 CCD 而 更 42 | 游戏,攻击 别国 占领 陆地 的 结果 是 如何 计算 的 攻击 别国 占领 陆地 的 结果 是 如何 43 | 电脑,XP 关机时 出现 结束 SAMPLE 程序 对话框 怎么回事 我 的 Wi 44 | 游戏,天府 情缘 出 问题 了 晚上 天府 都 进不去 了 给 个 说法 哦 我 还 在 杀怪 哈死 了 掉 45 | 娱乐,任九 让 我 优 让 我 喜 一次次 买彩 一次次 倾听 那 比分 一次 46 | 电脑,汉城 什么 时候 改名 为首 尔 为什么 47 | 电脑,UPS 电源 工作 原理 48 | 电脑,我 在 上 注册 在 中文 香港 界面 就 可以 用 用户名 登录 成功 在 英文 界面 就 说 49 | 烦恼,11 月 17 q 毖 稚齷了 U 50 | 商业,站 在 2995 以上 的 高岗 我 全副武装 满仓 站 在 2900 以上 的 高岗 51 | 教育,急需 afew 和 52 | 游戏,关于 BL 我们 队伍 平均 70 级 2 魔 1 传 1 弓 1 格 2 次 BL 都 过 不了 53 | 文化,歇后语 打破 脑壳 不 叫 痛 54 | 娱乐,大家 发现 了 一个 问题 了 吗 关于 中奖 江西 的 彩民 每期 的 投注额 绝 55 | 游戏,使命 召唤 2 的 问题 帮帮我 谢谢 了 从 新浪 下载 的 使命 召唤 2 使用 了 XEZ 56 | 游戏,回归 魔力 . 问 练功 点 . 回归 魔力 电信 时 长 巨蟹 的 . 请问 112 的 敏 魔 要 57 | 社会,有限公司 可以 不设 股东会 把 董事会 作为 权力 机构 吗 如 题 58 | 教育,2009 年 湖南 会计人员 继续 教育 是 什么 时候 59 | 育儿,我 的 奶水 不够 吃 怎么 增加 奶水 60 | 教育,英语 What sup 是 什么 意思 61 | 烦恼,jiaoyu 如何 培养 学生 阅读 能力 62 | 电脑,CAD 软件 的 角度 取值 为 整数 1 度 2 度 3 度 4 度 没有 2.1 度 63 | 社会,物流 公司 发货 不 按照 协议 发货 照成 货物 损坏 怎么 赔偿 64 | 社会,会 开车 的 好处 我 是 个 大学生 请问 有 驾驶证 对 以后 找 工作 帮助 大 吗 65 | 文化,何谓 普普 来历 66 | 游戏,问道 游戏 有 什么 办法 可以 快速 刷 友好度 的 67 | 生活,市区 哪里 还有 卖 北京 冰糖葫芦 的 抓狂 抓狂 抓狂 抓狂 68 | 游戏,50 级 最好 的 双手 武器 想 在 50 级 的 战场 呆 一段时间 所以 求个 50 69 | 商业,1 . 大宗 交易 的 金额 与 数量 有何 规定 一 A股 交易 数量 在 50 万股 70 | 生活,谁 用 过 水宜 生杯 真的 是 那么 有 作用 吗 我 看电视 上 的 宣传 广告 觉 71 | 商业,退税 营业税 城建税 教育费 附加 所得税 分别 怎么 做 帐 72 | 游戏,我 这样 的 配置 会 不会 卡 游戏 登 不 上去 没试 过 不 知道 XP2500 O 73 | 生活,深圳 至 赣州 怎样 走 请问 深圳 开车 到 赣州 应该 怎样 走 啊 请 各位 可以 详细 告 74 | 健康,遵义市 治疗 女性 癫痫 需要 注意 患者 的 哪些 75 | 游戏,牛 C 进来 回答 下 上次 在 4 区 看到 个 会后 中投 后 3 分 的 C 不 知道 怎么 会 的 76 | 商业,帮 分析 600527 江南 高纤 今天 是否 为 上涨 前 的 蓄势 调整 吗 77 | 体育,郝海东 现在 干什么 了 怎么 也 不 听 报道 了 78 | 健康,怀孕 什么 时候 能 感觉 到 初期 症状 都 有 什么 怀孕 什么 时候 能 感觉 到 初 79 | 生活,吃 什么 生精 比较 快 吃 什么 生精快 而且 易 食用 80 | 商业,清泉 点评 之 39 角度 与 变线 以前 是 准备 放在 80 讲 以后 进行 的 也 就 81 | 生活,有 谁 知道 妆点 一生 的 洗发水 去屑 效果 怎么样 82 | 电子,诺基亚 E63 最低 电量 指示 空格 还是 一 格 是不是 没 电 无法 开机 的 时候 摁 开 83 | 娱乐,256 元冲 14 场 火锅 而 去 01 切尔西 VS 维 拉 3102 西汉姆 VS 雷 84 | 生活,怎么 把 脸 洗 干净 我 怎么 觉得 每天 我 的 脸 洗完 后 还 不是 很 干净 皮肤 也 85 | 教育,35 年前 的 今天 一个 伟人 过世 了 请 您 在 此 说 一句 心里话 86 | 烦恼,初恋 小 毛孩 的 疑惑 她 答应 做 我 女朋友 却 不愿 公开 为什么 呢 是因为 怕 87 | 体育,请 输入您 的 问题 ... 山东 鲁能泰山 足球队 的 世界 俱乐部 排名 是 多少 88 | 健康,脖子 长 10CM 算长 还是 短 我 15 岁 男生 身高 167CM 脸圆 89 | 生活,求 推荐 减肥药 各位 泪 泪 泪 泪 90 | 娱乐,大家 帮 我 找 找 这 张图 就是 海贼王 里 的 银狐 篇 里 的 一集 路飞 一行 人 与 福 91 | 资源,煤 很 重要 92 | 资源,天然气 怎么样 93 | 资源,太阳能 怎么样 94 | ,NAN NAN 95 | ,什么 意思 96 | ,不 知道 97 | 医疗,姜医师 水平 如何 98 | 医疗,肾病 怎么 回事 99 | 医疗,心脏病 能 救得 起 不 100 | 汽车,比亚迪 怎么样 101 | 汽车,红旗 车 好 威风 102 | -------------------------------------------------------------------------------- /keras_textclassification/data/byte_multi_news/readme.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yongzhuo/Keras-TextClassification/af802f1dc6962cab2c47f93c123f18f169bacf1a/keras_textclassification/data/byte_multi_news/readme.md -------------------------------------------------------------------------------- /keras_textclassification/data/embeddings/albert_base_zh/__init__.py: -------------------------------------------------------------------------------- 1 | # !/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # @time : 2019/11/2 1:08 4 | # @author : Mo 5 | # @function: -------------------------------------------------------------------------------- /keras_textclassification/data/embeddings/chinese_L-12_H-768_A-12/__init__.py: -------------------------------------------------------------------------------- 1 | # !/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # @time : 2019/11/2 1:07 4 | # @author : Mo 5 | # @function: -------------------------------------------------------------------------------- /keras_textclassification/data/embeddings/chinese_xlnet_mid_L-24_H-768_A-12/__init__.py: -------------------------------------------------------------------------------- 1 | # !/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # @time : 2019/11/2 1:08 4 | # @author : Mo 5 | # @function: -------------------------------------------------------------------------------- /keras_textclassification/data/embeddings/term_word.txt: -------------------------------------------------------------------------------- 1 | 你 2 | 有 3 | 什么 4 | 可爱 5 | 之 6 | 处 7 | 能 8 | 让 9 | 大家 10 | 见识 11 | 么 12 | 娱乐 13 | 游戏 14 | 教育 15 | 社会 16 | 烦恼 17 | 生活 18 | 有氧 19 | 运动 20 | 无氧 21 | 运动 22 | 对 23 | 人 24 | 的 25 | 作用 26 | 和 27 | 适宜 28 | 的 29 | 人群 30 | 分别 31 | 是 32 | 什么 33 | 请问 34 | 还是 35 | 攻击 36 | 速度 37 | 山地 38 | 狮好 39 | 不看 40 | 外表 41 | 哪个 42 | 更好 43 | 用 44 | 找错 45 | 脚趾 46 | 痛 47 | 右脚 48 | 外侧 49 | 疼痛 50 | 已经 51 | -------------------------------------------------------------------------------- /keras_textclassification/data/model/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/8/28 2:35 4 | # @author :Mo 5 | # @function : -------------------------------------------------------------------------------- /keras_textclassification/data/model/fast_text/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/10/14 19:47 4 | # @author :Mo 5 | # @function : -------------------------------------------------------------------------------- /keras_textclassification/data/sim_webank/test.csv: -------------------------------------------------------------------------------- 1 | sentence1,sentence2,label 2 | 为什么我无法看到额度,为什么开通了却没有额度,0 3 | 为啥换不了,为两次还都提示失败呢,0 4 | 借了钱,但还没有通过,可以取消吗?,可否取消,1 5 | 为什么我申请额度输入密码就一直是那个页面,为什么要输入支付密码来验证,0 6 | 今天借 明天还款可以?,今天借明天还要手续费吗,0 7 | 你好!今下午咱没有扣我款?,你好 今天怎么没有扣款呢,1 8 | 所借的钱是否可以提现?,该笔借款可以提现吗!,1 9 | 不是邀请的客人就不能借款吗,一般什么样得人会受邀请,0 10 | 人脸失别不了,开不了户,我输入的资料都是正确的,为什么总说不符开户失败?,0 11 | 一天利息好多钱,1万利息一天是5元是吗,1 12 | 为啥还没开放啊,不是微粒贷客户,怎么可以受邀,0 13 | 开通.微粒贷,帮我开通,1 14 | 咋么才能收到邀请,为什么我6号扣还款的到现在还没,0 15 | 扣款时间是几点,无利息的还款时间是多久?,0 16 | 为什么借款总是不通过,为什么审请不通过,1 17 | 为什么我的无法查看额度,为什么我点进去没有额度呢,0 18 | 请问月息多少,2万块月息是多少,1 19 | 借钱可好取现,可以提现金?,1 20 | 可以开 结清证明吗?,还清钱后能继续借吗?,0 21 | 你好,我银行卡被法院封了,能否换我儿子的卡还款,换卡什么时候能换好,0 22 | 一般是什么时候自动扣款?,一般几点扣款,1 23 | 我想问什么时候会再打电话过来呢?,那什么时候打来电话?,1 24 | 请问有这个手机端的app吗,手机信号不好,0 25 | 开不了户,人脸失别不了,开不了户,0 26 | 不满足微众银行条件,“您未满足微众银行审批要求,无法查看额度”,这是为什么?什么原因呢,1 27 | 那我刚刚申请的贷款。。取消掉怎么操作,刚刚申请了贷款,可以取消吗?,1 28 | 什么时候发出邀请呢,借款没打电话,0 29 | 为什么提前还清所有借款不能再借呢?,提前还款利息怎么算,0 30 | 我换手机号了,如果我换手机怎么办?,1 31 | 为什么刚刚借钱要输入很多次验证码和支付密码是不是我手机问题还款就可以,借款连续输验证码和密码,1 32 | 不借了 不要打来了,不想借钱了,但是不小心按到借钱按钮了,1 33 | 需要提供什么借款材料,是不是苹果手机 都没开通啊,0 34 | 不小心挂断,不好意思,刚刚有事没有接听您的电话,现在可以打过来了,谢谢!,0 35 | 怎么关掉这个,如何退出微利贷,1 36 | QQ里的微粒贷怎么找不到了,图标在哪儿,0 37 | 13号扣款,今天怎么没有扣,您好,今天我没有扣款,你查查,1 38 | 亲,中奖的要怎样留地址呢?,要怎样充值?,0 39 | 为什么j借款未通过,我为什么借不起来,1 40 | QQ钱包没有入口是不是没绑定银行卡,qq微粒贷和微信微粒贷有什么不一样,0 41 | 咋么开通,可以申请吗 没有微粒贷帐号,0 42 | 如何更改手机号,如何更改绑定的手机号码?,1 43 | 为什么会申请失败?,但是审核不通过,0 44 | 如何解绑银行卡,如果解除银行卡绑定,1 45 | 怎么降低借款额度,额度降低了,0 46 | 您好 请把借款功能关闭,不要就说这个,0 47 | 借款时,银行验证电话没接到,没接到电话确认!什么时候在打,1 48 | 借钱了怎么还啊,18号还款日可以不凌晨扣款,我18日下午还款可以吗,0 49 | 你好,我绑定的银行卡掉了,能换过一张银行卡绑定吗,绑定的银行卡丢了怎么办 换卡 换扣款卡,1 50 | 手机号换了,怎么更改,我的手机号码换了怎么换?,1 51 | 如何提高借款额度,0.05/是多,0 52 | 我为什么木有额度,为什么我有朋友在这里没有额度?,1 53 | 我可以主动给银行打电话来确认吗,申请多少额度需要电话确认,0 54 | 如何解除,怎么样才能把微粒贷删掉,1 55 | 0开通,开通、借款,0 56 | 可以注销微众银行已经开户的了?,不要,0 57 | 为什么我卡有足够钱,但还款失败?,为什么帐户有钱,我提前还款,却显示还款失败!,0 58 | 上面提示我未满足借贷条件,不符合微银行的条件,1 59 | 多笔借贷利息,4:怎么计息,0 60 | 、怎么提额,开通 怎么开道,0 61 | 审核需要多长时间?,借款需要多长时间审核,1 62 | 如果获得权限,我要进入w贷,1 63 | 未满足银行审批,如何满足审批要求,0 64 | QQ上也显示借款失败,上面我能借2千5。现在借了5百,还有2千借不出来了?为什么?,0 65 | 手机号换了,怎么更改,怎样更改电话号码,1 66 | 关闭微粒货,没收到信息,0 67 | 为什么我借的钱还没到账?,一般多长时间到账,0 68 | 是不是苹果机子显示不了,必须是智能手机?,0 69 | 为满足微众银行审批要求是什么意思,为什么我不能用,1 70 | 微粒贷借钱页面显示未满足微众银行审批,农业银行,0 71 | 刚才我输错了身份验证,结果就这样了,你好我想借款昨天输入密码错误但是今天一直显示我密码输入错误次数过多要第二天尝试,0 72 | 说身份证号码多次输错无法借款,我已经把真确的身份证号码输进去了,为什么不可以借贷呀,0 73 | qq里面没有微粒米怎么办,但是QQ没有,1 74 | 我有那些未满足银行审批,未满足审批,1 75 | 名额没有,可以邀请我不?给我个名额,1 76 | 怎么才能算是邀请朋友,不是邀請的、要怎么样开通,0 77 | 为什么我在手机上打不开微粒贷,为什么别人手机有,1 78 | 刚刚不小心挂掉了你们打过来的电话了,错过审核电话,1 79 | 未满足于微众银行审批,未满足申请要求是什么,1 80 | 迟还款几天会影响信用,电话确认需要多久?,0 81 | 为什么电话审核不通过,刚刚审核了,怎么未通过?,1 82 | 不符合借款要求,不满足审核,1 83 | 显示我身份输入错误多,无法借款,我借款不成功怎么个情况?,0 84 | 借款可以借几次,一人可以借几次?,1 85 | 他说我身份信息输入错误次数过多怎么弄,为什么补充信息弄不了,0 86 | 如何获得 微粒贷,借了款,没显示,0 87 | 你好 微粒贷申请需要那些资料的了。,你好,我手机上怎么显示微粒贷还没有开通,0 88 | 能不能帮我查一下我这个月的账单是多少,借个月分期还账单,1 89 | 有电话我没接到没事吧,刚审核电话没有接到,1 90 | 为什么评估未通过,为什么有了微粒贷界面审核不通过,1 91 | 没有通过怎么办,为什么我不满足微众银行的审批标准?标准是什么呢,0 92 | 申请延期一天还款,逾期1天会记入个人征信吗?,0 93 | 10000若分5个月,1个月还完怎么计息,7天内不计息,怎解?,0 94 | 你好,我还款帐变更要如何更改,怎么更改分期还款,0 95 | 借款后银行没来电话怎么取消,不用提醒了我不借了,1 96 | 刚才没接到电话,回拔不成功,没接到电话确认!什么时候在打,1 97 | 晚一天还款 会逾期吗,逾期一天了,我该怎么还?,0 98 | 如果逾期了,利益怎么算,如果借了1000元逾期十天,1 99 | 在没,到现在也没到账啊,0 100 | 本期还款记录,我还款记录可以,0 101 | 我是为了这个评分的,说评分不足,0 102 | -------------------------------------------------------------------------------- /keras_textclassification/data/sim_webank/train.csv: -------------------------------------------------------------------------------- 1 | sentence1,sentence2,label 2 | 用微信都6年,微信没有微粒贷功能,4。 号码来微粒贷,0 3 | 微信消费算吗,还有多少钱没还,0 4 | 交易密码忘记了找回密码绑定的手机卡也掉了,怎么最近安全老是要改密码呢好麻烦,0 5 | 你好 我昨天晚上申请的没有打电话给我 今天之内一定会打吗?,什么时候可以到账,0 6 | "“微粒贷开通""",你好,我的微粒贷怎么没有开通呢,0 7 | 为什么借款后一直没有给我回拨电话,怎么申请借款后没有打电话过来呢!,1 8 | 为什么我每次都提前还款了最后却不给我贷款了,30号我一次性还清可以不,0 9 | 请问一天是否都是限定只能转入或转出都是五万。,微众多少可以赎回短期理财,0 10 | 微粒咨询电话号码多少,你们的人工客服电话是多少,1 11 | 已经在银行换了新预留号码。,我现在换了电话号码,这个需要更换吗,1 12 | 下周有什么好产品?,元月份有哪些理财产品,1 13 | 第一次使用,额度多少?,我的额度多少钱,1 14 | 我什么时候可以通过微粒贷借钱,提前还清贷款还能再借吗,0 15 | 借款后多长时间给打电话,借款后多久打电话啊,1 16 | 没看到微粒贷,我借那么久也没有提升啊,0 17 | 原来的手机号不用了,怎么换,手机号码没有更改,1 18 | 我想开通微粒贷 不知我应该做写什么准备材料呢,为何苹果手机显示微粒贷暂未开放?,0 19 | 能查帐单吗,可以查询帐单,1 20 | 日利率多少,息多少,1 21 | 微信6.2的版本没有微粒贷吗?,什么时候才会全面开放名额,0 22 | 0K,谢谢,还没有开通,开通为什么显示证件已被使用,0 23 | 综合评估为何过不了,为什么综合评分不能过?,1 24 | :请问下我可以提额,当月还清了,当月能提高额度吗,0 25 | 1000多少一天,10000借三天,总利息是163?,1 26 | 为什么会有短信说审核不通过,为什么借款回复是未通过了?,1 27 | 借款不能用于什么,借的款可以用来还信用卡吗?,1 28 | 还款银行怎么修改,怎么更改还款卡,1 29 | 卡里有钱为什么显示还款失败,为啥账户有钱却还款失败,1 30 | 4:借款期限,可以分期还款吗,0 31 | 一次性还款,qq怎么不提醒还款,0 32 | 1无法借款,qq有微立代,0 33 | 五点前还款失败,为什还款失败,1 34 | 什么时候可以使微敉贷,什么时候可以向微粒袋借钱,1 35 | 为什么卡的有钱,不自动扣钱呢。,我账户有足够存款怎么不会扣钱?,1 36 | 借款的钱能用来干什么?,借款成功后的钱只能用于日常什么消费,1 37 | 我换号码了,要更换电话号码,换手机号,1 38 | 借款需要什么证明?,不给开还发什么消息,0 39 | 电话更改了,电话号码可以更改吗,1 40 | 一般多久能收到审核电话?,一直都是等待电话通知,0 41 | 如果今天扣款不成功,会不会造成以后借款的问题,请帮我查看我刚才借贷500是否成功,0 42 | 我一点钟转钱进还款卡里了,现在过5点了,怎么还没自动扣款呢?,5点怎么没有扣款,,1 43 | 不是邀请的如何贷款?,我不是你们邀请的客人可以贷款吗?,1 44 | 如何满足微粒银行的审核,建设银行有微粒贷的资格吗,0 45 | QQ钱包里的微粒贷和微信里的有区别吗?,QQ钱包在那打开,0 46 | 可以取消借款么?,不可以取消借款吗,1 47 | 打开钱包没有微立贷,怎么拥有微粒贷,0 48 | 没接到电话可以给你们回电话吗,回访电话没接到,1 49 | 怎么才能成为微粒贷邀请的客户?,怎么不邀请我开通啊,0 50 | 已经还款,怎么还有逾期提醒,我已经还款,为何还会出现逾期提醒,1 51 | 如何修改自动还款银行卡,如何设置自动还快,0 52 | 息是多少?,我借40000元,十个月还,息恭是多少?,0 53 | 生份信息输入错误多了申请不了的啊?,关闭手机,重新打开,微粒贷的入口还是没有了,,0 54 | 为什么我的没通过,为什么贷款不成功,1 55 | 正月还款能延迟几天么,本金3000元逾期一天需要还多少钱,0 56 | "为什么借代不成功,",我想知道借款失败的原因,1 57 | 不知道什么时候才对我开放,都等到花都谢,几号开放,1 58 | 提前还款利息会少算吗,结清证明如何开,0 59 | 扣款银行卡,注销,你好,我不想借钱了,怎么才能撤销,0 60 | 全部结清是否还能再借款,提前还款了还可以在贷不,1 61 | 我想知道借款失败的原因,微粒贷失败的原因,0 62 | 1500分二十个月还完。一个月要还多少,一千一个应该还多少利息,0 63 | 你们没有扣款,你好 为什么没有扣款呢,1 64 | 我今天登陆不上了,它提示我网络没链接,但是我连上了,微信登录不了已经有一下多星期了,1 65 | 怎么我今天借款。到下个月18号就有50的利息。是怎么算出来的,上个月已经借了一千元,然后这个月再借两千元,利息怎么算?,1 66 | 您好,我想关闭微粒贷,可以吗?,给我关了微粒贷,谢谢,1 67 | 为什么我还显示不出微粒贷,为什么还款了没有额度,0 68 | 开通了都没有额度吗,开通无额度,1 69 | 5000日息0、05也就是多少钱,6000元一个月要多少息,0 70 | 我手机怎么不能,手机里面没有,1 71 | 活动,苹果7,0 72 | 未满足审批要求,怎么回事,怎么显示未达到微众银行审批要求,1 73 | 为什么今天自动还款还没有扣?,22日已存入农行卡中,为何扣款失败?,0 74 | 绑定的银行卡如何修改,怎样重新绑定,1 75 | 我注销过微信支付功能,现在微信里没有微粒贷图标咋办?,不能用做什么用途,0 76 | 你好,单笔只能借4万嘛?,一笔最多多少金额,1 77 | 还有问题呢。我不可以主动还款?,为什么我卡里有钱,但是提示自动扣款失败?,1 78 | 怎么五点前都没扣我钱,我的收款招商银行,5分钟了还没到账,平时都很快的,0 79 | 一般要等几天,一般几天会打电话给我,1 80 | 贷款合同,怎么查看合同,1 81 | 为什么会不支持借款,为什么我还有借款额度却借不出钱?,0 82 | .开通,我想申请,0 83 | 开通不,开通、借款、还款,0 84 | 为什么没有显示微利贷,微粒贷消失,1 85 | 亲,能不能部分还款,还款过后怎么金额没得改变,0 86 | 以前借了的,现在看不到额度了,为什么邀用户但是没额度,0 87 | 为什么我不能用微粒贷,咋不邀请我,1 88 | 如何获得微粒贷邀请,如何被微粒贷邀请,1 89 | 为什么会 为满足微众银行审批要求,为满足微众银行要求是为什么,1 90 | 怎么还不打电话我更换还款银行?,怎么变更还款,0 91 | 你好,我银行卡的预留电话已经变更,但为什么发验证码的时候还发到原来的号码哪里?,为啥我收到短信验证码以后一点下一步就卡出去了?,0 92 | 为什么我的没有开放?,为什么还是不能开通,1 93 | 我现在不能还款怎么办?,为何以前能借现在不能借了,我都准时还款没有逾期,0 94 | 要多旧才可以到账,正常要多久才到帐呢!亲,1 95 | 我要降低额度怎么操作,一笔钱全部还完额度会不会减少,0 96 | 综合评分不足,受邀了,却评分不足,0 97 | 如何换自动还款的卡号,2月7日会自动扣款吗,0 98 | 我要更换手机号,如何更改验证的电话号码?,1 99 | 两小时过去还没电话审核,一般什么时候能收到电话确认借款?,0 100 | 可以帮我打份贷款还清凭证吗?,如何开具结清证明?,0 101 | 为什么开通不了,为什么我今天借款失败?,1 102 | -------------------------------------------------------------------------------- /keras_textclassification/data/sim_webank/valid.csv: -------------------------------------------------------------------------------- 1 | sentence1,sentence2,label 2 | 不要借了我是试试看能否操作的,借款审核期间能否取消借款,0 3 | 亲怎样才能在钱包里有微粒货的图标呢,借不到,0 4 | 你好,我还款银行怎么更换,怎么更换绑定还款的卡,1 5 | 我的借贷额度,怎么减少了呢?,微粒贷额度怎么才能降低,0 6 | 什么时候可以知道借款成功,2.多笔借款,0 7 | 一般电话确认要等多久。,一般多久才会打电话来,1 8 | 我想问下如果我开始设定的借款是20个月,但是到10个月的时候提前还清,利息是算到什么时候的呢?,你好我想问一下 看你们还款周期设定了5个月 10个月的 能不能一个月内还呢?利息是怎么算的 还有申请额度是一定的么?会不会上调?,1 9 | 借到的款在微信钱包里,1何时邀请,0 10 | 我要关闭微粒贷这个功能,提示未满足条件,0 11 | 不借了怎么退点错了,不想贷款了怎么撤销,1 12 | 今天是还款日 今天内钱会存进去 保证今天能还 应该没什么事吧,今天放款今天就得还款?,0 13 | 借不到,不可贷款,1 14 | 借款具备条件,借款 申请,0 15 | 选择了还款期限,可以提前还吗,几天就还,这个借款是借几天算几天的吗,0 16 | 从零钱还行不行,从微信钱包扣除,1 17 | 我什么时候才可以有贷款?,今天借,过几天后还可以吗?,0 18 | 为什么我借了没有人联系我呢,什么时候回来电话?,1 19 | 请问为什么总提示我身份证输入错误次数过频呢?,提示:身份证信息输入次数过多,无法借款,1 20 | 为什么我手动还款不行啊,我卡掉了,现在用新卡还款,你们还不可以改,怎么还,0 21 | 帮我看看我的款扣了没这个月的,怎么会没扣成功,0 22 | 可以換其他银行卡吗?,分期的如何用别的银行卡还钱,1 23 | 我现在申请微粒货?,申请贷款,1 24 | 开通微粒贷,刚刚提交了借款申请。怎么还没到,0 25 | 延期一天,有多久免息期,0 26 | 前我已转入尾号:5088卡上了,为什么扣款失败呢?,为什么显示扣款失败?,1 27 | 申请了,显示说等电话确认,是多久打电话过来呢?,啥时候给我打电话,1 28 | 为什么我没有微里贷 可以“走后门”么,1 何时会邀请我使用微粒贷,0 29 | 额度不够怎么办,上面给我的额度明明是十万,为什么只能借一万呢,0 30 | 为什么我开通不了微粒代,微粒袋我开通不了?,1 31 | 借款后多久打电话我核实?,借款后多久收到电话,1 32 | 开通微,开通下谢谢,1 33 | 为什么我暂时无法查看额度,开通不了,0 34 | 怎么申请微粒货,开通要什么条件,0 35 | 微粒贷怎么消失了,微粒贷没了,1 36 | 一个人只可以办一张卡吗,为什么微众卡号绑定不了微信的银行卡呢,0 37 | 4000每天利息是多少?,4000的话一天是多少钱的利息,?,1 38 | 你让我干嘛我就干嘛。,菜单,0 39 | 借款1万用10个月的利息是多少,借款5个月多少利息?,1 40 | 苹果手机不支持这个功能吗,预留手机号更改,0 41 | 两个小时还没有等到确认电话怎么办?明天会继续联系嘛?,下次借款是否不需要电话确认,0 42 | 我可以贷吗?,能贷款的?,1 43 | 为什么没达到要求呢?,为什么要的手机微信里面没有微粒带,0 44 | 怎么更改还款卡,如何改还款卡,1 45 | 2万一天多少息,一万月息多少,0 46 | 我的微粒贷什么时候可以用,'我要开通微贷,0 47 | 无法查看额度是什么意思啊,无法查看额度是什么,1 48 | 可以向外转帐吗?,如何转款账户,0 49 | 想关闭微粒贷,请问我要注消微粒贷怎么注消,1 50 | 今晚都无法登陆什么原因啊,我是微众银行的客户,今天无法登陆,怎么办,1 51 | 1何时能用微粒贷,借款没有发,0 52 | 为什么分5期,为什么不可以不分期还呢,1 53 | 收不到短信验证码,借款时给我发验证码来了这个验证码怎么用,0 54 | 我银行预留电话已经更改,我的银行绑定电话应该怎么更改,1 55 | 为什么我没有勒,何时会激请我使用微粒贷 如何获得微粒贷,0 56 | 亲麻烦你我这月还款多少,8提前还款的利息怎么算啊,0 57 | 我现在可以用吗,怎么样变成客人,0 58 | 取消微粒贷借款,取消我的微粒贷,1 59 | 换卡绑定,我的银行卡怎么转你们平台有50000的限额啊?,0 60 | 一共几期?,为什么一借就是最低五个月!要是我只借了一天还会不会都把五个月的利息算进去了,0 61 | 我的还款日期是21号,请问什么时候自动扣款,明天是还款日最迟几点进账,1 62 | 为什么卡里有钱确显示还款失败,为什么我的还款卡里有钱说还款失败,1 63 | 我卡里有钱,为什么扣款会失败,请问如果还是自动扣款失败可以手动还款吗?,0 64 | 我是不是进黑名单了?,不会有逾期吧,0 65 | 是你们的付出,才有微粒贷的今天,咋我不能贷?,1 66 | 我什么时候可以借袋,本月未还清贷款,下个月还可以再贷款吗?,0 67 | 你好,微粒货业务怎么开通,我已经开通了,0 68 | 微粒袋入口不见了,邀请我好不好,家里装修房子欠4万多,都快过年了工人都还没结账。家里一分钱都没了,请你借我两万块,感谢微信感谢微粒贷。。。,0 69 | 如何注销微众账户?,如何注销已有微众银行,1 70 | 4天了都没打过电话来,一般大概什么时候会和我联系呢?我等会就想睡觉了啊,0 71 | 借款可以转账别的银行卡吗,我不是用绑定的银行卡还的,用的是另外一张,0 72 | 为什么反复让输入验证码和支付密码一直让输入没有个头啊,为什么我借款随后信息验证码发不到手机上,0 73 | 为什么我的借款审核不通过,为什么刚才我申请借款,却说我审批未通过?,1 74 | 请问日息10000元是每天多少钱?,如果我代1万元是日利多少,1 75 | 从新换卡,..想更换还款的银行卡。,1 76 | 微粒贷支持的银行,开通 微粒贷开通,0 77 | 为什么我无法贷款,为什么全额还款后,想再借出来,显示借款失败呀?,1 78 | 嘿嘿,试着申请了一笔,等待电话确认,电话会什么时候来电,1 79 | 换了预留号,电话修改,1 80 | 你好!本次还款是否成功怎么查询,我晚还了一天对后续借款有影响么,0 81 | 客服您好 能给我个结清证明吗 我买房贷款需要,可不可以提供个还清证明,,1 82 | 微信有微粒货吗,微信上看不到微粒贷图标,1 83 | 17点还没有扣款,如果扣款不成功 一天会扣几次,0 84 | 1500是多少罚息,罚息是按多少算的,1 85 | 一般会多长时间给回复,从新拨打一次,谢谢。,0 86 | 什么条件才是你们邀请的,借钱有要求吗,0 87 | 10000元,一天是要多少利息,10个月还清一起支付了多少利息,0 88 | 取消刚才的贷款,我现在借款没成功,客服也没致电我,我能不取消掉,1 89 | 突然不想借钱了,可不可以取消,取消借款申请,1 90 | 20号会把逾期的都还上,23日还款算不算逾期?,1 91 | 为啥我无法登录微众APP了?微信和QQ都不行!,你好,如何在微众app里面绑定qq,0 92 | 提示姓名,身份证绑定电话信息不符,开户不成功,香港身份证开不了户吗?,0 93 | 快点来钱,请尽快到账,0 94 | 从哪里查看电子借据,把帐单明细发过来,0 95 | 2:如何更换还款银行卡,..想更换还款的银行卡。,1 96 | 客服电话是多少,你们有电话吗,1 97 | 你好,我要房贷,需要你们出具还款结清凭证,如何开贷款的结清证明,0 98 | 我向您们的借款为什么会失败呢,,我怎么借不出来啊,1 99 | 微众银行转到其它银行卡有限额吗?,转入 额度,0 100 | 怎么填写资料,会泄漏个人信息吗?,0 101 | 为什么我qq上面没有 微粒贷 这个应用?,草,为什么这个我没名额没额度。麻痹的会员都开了好几年。连个微粒贷名额都不给爹。草。,0 102 | -------------------------------------------------------------------------------- /keras_textclassification/data_preprocess/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/3 10:50 4 | # @author :Mo 5 | # @function : -------------------------------------------------------------------------------- /keras_textclassification/keras_layers/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/22 7:33 4 | # @author :Mo 5 | # @function : -------------------------------------------------------------------------------- /keras_textclassification/keras_layers/__pycache__/Attention_self.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yongzhuo/Keras-TextClassification/af802f1dc6962cab2c47f93c123f18f169bacf1a/keras_textclassification/keras_layers/__pycache__/Attention_self.cpython-36.pyc -------------------------------------------------------------------------------- /keras_textclassification/keras_layers/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yongzhuo/Keras-TextClassification/af802f1dc6962cab2c47f93c123f18f169bacf1a/keras_textclassification/keras_layers/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /keras_textclassification/keras_layers/albert/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/10/14 9:46 4 | # @author :Mo 5 | # @function : -------------------------------------------------------------------------------- /keras_textclassification/keras_layers/attention_self.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/22 19:35 4 | # @author :Mo 5 | # @function :Attention of itself 6 | 7 | 8 | from keras.regularizers import L1L2, Regularizer 9 | # from keras.engine.topology import Layer 10 | from keras.layers import Layer 11 | from keras import backend as K 12 | 13 | 14 | class AttentionSelf(Layer): 15 | """ 16 | self attention, 17 | codes from: https://mp.weixin.qq.com/s/qmJnyFMkXVjYBwoR_AQLVA 18 | """ 19 | def __init__(self, output_dim, **kwargs): 20 | self.output_dim = output_dim 21 | super().__init__(**kwargs) 22 | 23 | def build(self, input_shape): 24 | # W、K and V 25 | self.kernel = self.add_weight(name='WKV', 26 | shape=(3, input_shape[2], self.output_dim), 27 | initializer='uniform', 28 | regularizer=L1L2(0.0000032), 29 | trainable=True) 30 | super().build(input_shape) 31 | 32 | def call(self, x): 33 | WQ = K.dot(x, self.kernel[0]) 34 | WK = K.dot(x, self.kernel[1]) 35 | WV = K.dot(x, self.kernel[2]) 36 | # print("WQ.shape",WQ.shape) 37 | # print("K.permute_dimensions(WK, [0, 2, 1]).shape",K.permute_dimensions(WK, [0, 2, 1]).shape) 38 | QK = K.batch_dot(WQ, K.permute_dimensions(WK, [0, 2, 1])) 39 | QK = QK / (64**0.5) 40 | QK = K.softmax(QK) 41 | # print("QK.shape",QK.shape) 42 | V = K.batch_dot(QK, WV) 43 | return V 44 | 45 | def compute_output_shape(self, input_shape): 46 | return (input_shape[0], input_shape[1], self.output_dim) 47 | 48 | 49 | if __name__=="__main__": 50 | att = AttentionSelf(300) 51 | 52 | -------------------------------------------------------------------------------- /keras_textclassification/keras_layers/highway.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/22 8:15 4 | # @author :Mo 5 | # @function : 6 | 7 | 8 | from keras.layers import Layer, Dense 9 | import keras 10 | 11 | 12 | class highway(Layer): 13 | """ 14 | # writter by my own 15 | # paper; Highway Network(http://arxiv.org/abs/1505.00387). 16 | # 公式 17 | # 1. s = sigmoid(Wx + b) 18 | # 2. z = s * relu(Wx + b) + (1 - s) * x 19 | # x shape : [N * time_depth, sum(filters)] 20 | 21 | # Table 1. CIFAR-10 test set accuracy of convolutional highway networks with 22 | # rectified linear activation and sigmoid gates. 23 | # For comparison, results reported by Romero et al. (2014) 24 | # using maxout networks are also shown. 25 | # Fitnets were trained using a two step training procedure using soft targets from the trained Teacher network, 26 | # which was trained using backpropagation. We trained all highway networks directly using backpropagation. 27 | # * indicates networks which were trained only on a set of 40K out of 50K examples in the training set. 28 | 29 | 30 | 31 | # Figure 2. Visualization of certain internals of the blocks in the best 50 hidden layer highway networks trained on MNIST 32 | # (top row) and CIFAR-100 (bottom row). The first hidden layer is a plain layer which changes the dimensionality of the representation to 50. Each of 33 | # the 49 highway layers (y-axis) consists of 50 blocks (x-axis). 34 | # The first column shows the transform gate biases, which were initialized to -2 and -4 respectively. 35 | # In the second column the mean output of the transform gate over 10,000 training examples is depicted. 36 | # The third and forth columns show the output of the transform gates and 37 | # the block outputs for a single random training sample. 38 | """ 39 | def __init__(self, **kwargs): 40 | super().__init__(**kwargs) 41 | 42 | def build(self, input_shape): 43 | super().build(input_shape) 44 | 45 | def call(self, x): 46 | gate_transform = Dense(units=K.int_shape(x)[1], 47 | activation='sigmoid', 48 | use_bias=True, 49 | kernel_initializer='glorot_uniform', 50 | bias_initializer=keras.initializers.Constant(value=-2))(x) 51 | gate_cross = 1 - gate_transform 52 | block_state = Dense(units=K.int_shape(x)[1], 53 | activation='relu', 54 | use_bias=True, 55 | kernel_initializer='glorot_uniform', 56 | bias_initializer='zero')(x) 57 | high_way = gate_transform * block_state + gate_cross * x 58 | return high_way 59 | 60 | def compute_output_shape(self, input_shape): 61 | return input_shape[0], input_shape[1], input_shape[-1] 62 | -------------------------------------------------------------------------------- /keras_textclassification/keras_layers/k_max_pooling.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/22 7:34 4 | # @author :Mo 5 | # @function : 6 | 7 | 8 | from keras.layers import Layer 9 | import tensorflow as tf 10 | 11 | 12 | class k_max_pooling(Layer): 13 | """ 14 | paper: http://www.aclweb.org/anthology/P14-1062 15 | paper title: A Convolutional Neural Network for Modelling Sentences 16 | Reference: https://stackoverflow.com/questions/51299181/how-to-implement-k-max-pooling-in-tensorflow-or-keras 17 | 动态K-max pooling 18 | k的选择为 k = max(k, s * (L-1) / L) 19 | 其中k为预先选定的设置的最大的K个值,s为文本最大长度,L为第几个卷积层的深度(单个卷积到连接层等) 20 | github tf实现可以参考: https://github.com/lpty/classifier/blob/master/a04_dcnn/model.py 21 | """ 22 | def __init__(self, top_k=8, **kwargs): 23 | self.top_k = top_k 24 | super().__init__(**kwargs) 25 | 26 | def build(self, input_shape): 27 | super().build(input_shape) 28 | 29 | def call(self, inputs): 30 | inputs_reshape = tf.transpose(inputs, perm=[0, 2, 1]) 31 | pool_top_k = tf.nn.top_k(input=inputs_reshape, k=self.top_k, sorted=False).values 32 | pool_top_k_reshape = tf.transpose(pool_top_k, perm=[0, 2, 1]) 33 | return pool_top_k_reshape 34 | 35 | def compute_output_shape(self, input_shape): 36 | return input_shape[0], self.top_k, input_shape[-1] 37 | -------------------------------------------------------------------------------- /keras_textclassification/keras_layers/keras_lookahead.py: -------------------------------------------------------------------------------- 1 | # !/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # @time : 2019/11/12 16:14 4 | # @author : Mo 5 | # @function: lookahead of keras 6 | # @codefrom: https://github.com/bojone/keras_lookahead 7 | 8 | 9 | from keras import backend as K 10 | 11 | 12 | class Lookahead(object): 13 | """Add the [Lookahead Optimizer](https://arxiv.org/abs/1907.08610) functionality for [keras](https://keras.io/). 14 | """ 15 | 16 | def __init__(self, k=5, alpha=0.5): 17 | self.k = k 18 | self.alpha = alpha 19 | self.count = 0 20 | 21 | def inject(self, model): 22 | """Inject the Lookahead algorithm for the given model. 23 | The following code is modified from keras's _make_train_function method. 24 | See: https://github.com/keras-team/keras/blob/master/keras/engine/training.py#L497 25 | """ 26 | if not hasattr(model, 'train_function'): 27 | raise RuntimeError('You must compile your model before using it.') 28 | 29 | model._check_trainable_weights_consistency() 30 | 31 | if model.train_function is None: 32 | inputs = (model._feed_inputs + 33 | model._feed_targets + 34 | model._feed_sample_weights) 35 | if model._uses_dynamic_learning_phase(): 36 | inputs += [K.learning_phase()] 37 | fast_params = model._collected_trainable_weights 38 | 39 | with K.name_scope('training'): 40 | with K.name_scope(model.optimizer.__class__.__name__): 41 | training_updates = model.optimizer.get_updates( 42 | params=fast_params, 43 | loss=model.total_loss) 44 | slow_params = [K.variable(p) for p in fast_params] 45 | fast_updates = (model.updates + 46 | training_updates + 47 | model.metrics_updates) 48 | 49 | slow_updates, copy_updates = [], [] 50 | for p, q in zip(fast_params, slow_params): 51 | slow_updates.append(K.update(q, q + self.alpha * (p - q))) 52 | copy_updates.append(K.update(p, q)) 53 | 54 | # Gets loss and metrics. Updates weights at each call. 55 | fast_train_function = K.function( 56 | inputs, 57 | [model.total_loss] + model.metrics_tensors, 58 | updates=fast_updates, 59 | name='fast_train_function', 60 | **model._function_kwargs) 61 | 62 | def F(inputs): 63 | self.count += 1 64 | R = fast_train_function(inputs) 65 | if self.count % self.k == 0: 66 | K.batch_get_value(slow_updates) 67 | K.batch_get_value(copy_updates) 68 | return R 69 | 70 | model.train_function = F 71 | 72 | if __name__ == '__main__': 73 | gg = 0 74 | # useage 75 | # model.compile(optimizer=Adam(1e-3), loss='mse') # Any optimizer 76 | # lookahead = Lookahead(k=5, alpha=0.5) # Initialize Lookahead 77 | # lookahead.inject(model) # add into model 78 | -------------------------------------------------------------------------------- /keras_textclassification/keras_layers/keras_radam.py: -------------------------------------------------------------------------------- 1 | # !/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # @time : 2019/11/12 16:12 4 | # @author : Mo 5 | # @function: radam of keras 6 | # @codefrom: https://github.com/bojone/keras_radam 7 | 8 | 9 | from keras.legacy import interfaces 10 | from keras.optimizers import Optimizer 11 | import keras.backend as K 12 | 13 | 14 | class RAdam(Optimizer): 15 | """RAdam optimizer. 16 | Default parameters follow those provided in the original Adam paper. 17 | # Arguments 18 | lr: float >= 0. Learning rate. 19 | beta_1: float, 0 < beta < 1. Generally close to 1. 20 | beta_2: float, 0 < beta < 1. Generally close to 1. 21 | epsilon: float >= 0. Fuzz factor. If `None`, defaults to `K.epsilon()`. 22 | decay: float >= 0. Learning rate decay over each update. 23 | amsgrad: boolean. Whether to apply the AMSGrad variant of this 24 | algorithm from the paper "On the Convergence of Adam and 25 | Beyond". 26 | # References 27 | - [RAdam - A Method for Stochastic Optimization] 28 | (https://arxiv.org/abs/1908.03265) 29 | - [On The Variance Of The Adaptive Learning Rate And Beyond] 30 | (https://arxiv.org/abs/1908.03265) 31 | """ 32 | 33 | def __init__(self, lr=0.001, beta_1=0.9, beta_2=0.999, 34 | epsilon=None, decay=0., **kwargs): 35 | super(RAdam, self).__init__(**kwargs) 36 | with K.name_scope(self.__class__.__name__): 37 | self.iterations = K.variable(0, dtype='int64', name='iterations') 38 | self.lr = K.variable(lr, name='lr') 39 | self.beta_1 = K.variable(beta_1, name='beta_1') 40 | self.beta_2 = K.variable(beta_2, name='beta_2') 41 | self.decay = K.variable(decay, name='decay') 42 | if epsilon is None: 43 | epsilon = K.epsilon() 44 | self.epsilon = epsilon 45 | self.initial_decay = decay 46 | 47 | @interfaces.legacy_get_updates_support 48 | def get_updates(self, loss, params): 49 | grads = self.get_gradients(loss, params) 50 | self.updates = [K.update_add(self.iterations, 1)] 51 | 52 | lr = self.lr 53 | if self.initial_decay > 0: 54 | lr = lr * (1. / (1. + self.decay * K.cast(self.iterations, 55 | K.dtype(self.decay)))) 56 | 57 | t = K.cast(self.iterations, K.floatx()) + 1 58 | beta_1_t = K.pow(self.beta_1, t) 59 | beta_2_t = K.pow(self.beta_2, t) 60 | rho = 2 / (1 - self.beta_2) - 1 61 | rho_t = rho - 2 * t * beta_2_t / (1 - beta_2_t) 62 | r_t = K.sqrt( 63 | K.relu(rho_t - 4) * K.relu(rho_t - 2) * rho / ((rho - 4) * (rho - 2) * rho_t) 64 | ) 65 | flag = K.cast(rho_t > 4, K.floatx()) 66 | 67 | ms = [K.zeros(K.int_shape(p), dtype=K.dtype(p)) for p in params] 68 | vs = [K.zeros(K.int_shape(p), dtype=K.dtype(p)) for p in params] 69 | self.weights = [self.iterations] + ms + vs 70 | 71 | for p, g, m, v in zip(params, grads, ms, vs): 72 | m_t = (self.beta_1 * m) + (1. - self.beta_1) * g 73 | v_t = (self.beta_2 * v) + (1. - self.beta_2) * K.square(g) 74 | mhat_t = m_t / (1 - beta_1_t) 75 | vhat_t = K.sqrt(v_t / (1 - beta_2_t)) 76 | p_t = p - lr * mhat_t * (flag * r_t / (vhat_t + self.epsilon) + (1 - flag)) 77 | 78 | self.updates.append(K.update(m, m_t)) 79 | self.updates.append(K.update(v, v_t)) 80 | new_p = p_t 81 | 82 | # Apply constraints. 83 | if getattr(p, 'constraint', None) is not None: 84 | new_p = p.constraint(new_p) 85 | 86 | self.updates.append(K.update(p, new_p)) 87 | return self.updates 88 | 89 | def get_config(self): 90 | config = {'lr': float(K.get_value(self.lr)), 91 | 'beta_1': float(K.get_value(self.beta_1)), 92 | 'beta_2': float(K.get_value(self.beta_2)), 93 | 'decay': float(K.get_value(self.decay)), 94 | 'epsilon': self.epsilon} 95 | base_config = super(RAdam, self).get_config() 96 | return dict(list(base_config.items()) + list(config.items())) -------------------------------------------------------------------------------- /keras_textclassification/keras_layers/non_mask_layer.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/7/10 10:35 4 | # @author :Mo 5 | # @function : 6 | 7 | from __future__ import print_function, division 8 | from keras.layers import Layer 9 | 10 | 11 | class NonMaskingLayer(Layer): 12 | """ 13 | fix convolutional 1D can't receive masked input, detail: https://github.com/keras-team/keras/issues/4978 14 | thanks for https://github.com/jacoxu 15 | """ 16 | 17 | def __init__(self, **kwargs): 18 | self.supports_masking = True 19 | super(NonMaskingLayer, self).__init__(**kwargs) 20 | 21 | def build(self, input_shape): 22 | pass 23 | 24 | def compute_mask(self, input, input_mask=None): 25 | # do not pass the mask to the next layers 26 | return None 27 | 28 | def call(self, x, mask=None): 29 | return x 30 | 31 | def compute_output_shape(self, input_shape): 32 | return input_shape 33 | -------------------------------------------------------------------------------- /keras_textclassification/keras_layers/transformer_utils/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/7/22 9:15 4 | # @author :Mo 5 | # @function : -------------------------------------------------------------------------------- /keras_textclassification/keras_layers/transformer_utils/embedding.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/7/22 10:00 4 | # @author :Mo 5 | # @function : 6 | 7 | from keras.layers import Embedding, Layer 8 | import keras.backend as K 9 | import keras 10 | 11 | 12 | class EmbeddingRet(Embedding): 13 | """Embedding layer with weights returned.""" 14 | 15 | def compute_output_shape(self, input_shape): 16 | return [super(EmbeddingRet, self).compute_output_shape(input_shape), 17 | (self.input_dim, self.output_dim), 18 | ] 19 | 20 | def compute_mask(self, inputs, mask=None): 21 | return [super(EmbeddingRet, self).compute_mask(inputs, mask), 22 | None, 23 | ] 24 | 25 | def call(self, inputs): 26 | return [super(EmbeddingRet, self).call(inputs), 27 | self.embeddings, 28 | ] 29 | 30 | 31 | class EmbeddingSim(Layer): 32 | """Calculate similarity between features and token embeddings with bias term.""" 33 | 34 | def __init__(self, 35 | use_bias=True, 36 | initializer='zeros', 37 | regularizer=None, 38 | constraint=None, 39 | **kwargs): 40 | """Initialize the layer. 41 | 42 | :param output_dim: Same as embedding output dimension. 43 | :param use_bias: Whether to use bias term. 44 | :param initializer: Initializer for bias. 45 | :param regularizer: Regularizer for bias. 46 | :param constraint: Constraint for bias. 47 | :param kwargs: Arguments for parent class. 48 | """ 49 | super(EmbeddingSim, self).__init__(**kwargs) 50 | self.supports_masking = True 51 | self.use_bias = use_bias 52 | self.initializer = keras.initializers.get(initializer) 53 | self.regularizer = keras.regularizers.get(regularizer) 54 | self.constraint = keras.constraints.get(constraint) 55 | self.bias = None 56 | 57 | def get_config(self): 58 | config = {'use_bias': self.use_bias, 59 | 'initializer': keras.initializers.serialize(self.initializer), 60 | 'regularizer': keras.regularizers.serialize(self.regularizer), 61 | 'constraint': keras.constraints.serialize(self.constraint), 62 | } 63 | base_config = super(EmbeddingSim, self).get_config() 64 | return dict(list(base_config.items()) + list(config.items())) 65 | 66 | def build(self, input_shape): 67 | if self.use_bias: 68 | embed_shape = input_shape[1] 69 | token_num = embed_shape[0] 70 | self.bias = self.add_weight(shape=(token_num,), 71 | initializer=self.initializer, 72 | regularizer=self.regularizer, 73 | constraint=self.constraint, 74 | name='bias', 75 | ) 76 | super(EmbeddingSim, self).build(input_shape) 77 | 78 | def compute_output_shape(self, input_shape): 79 | feature_shape, embed_shape = input_shape 80 | token_num = embed_shape[0] 81 | return feature_shape[:-1] + (token_num,) 82 | 83 | def compute_mask(self, inputs, mask=None): 84 | return mask[0] 85 | 86 | def call(self, inputs, mask=None, **kwargs): 87 | inputs, embeddings = inputs 88 | outputs = K.dot(inputs, K.transpose(embeddings)) 89 | if self.use_bias: 90 | outputs = K.bias_add(outputs, self.bias) 91 | return keras.activations.softmax(outputs) 92 | -------------------------------------------------------------------------------- /keras_textclassification/keras_layers/transformer_utils/layer_normalization.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/7/22 9:25 4 | # @author :Mo 5 | # @function : 6 | 7 | 8 | from keras.layers import Layer 9 | import keras.backend as K 10 | import keras 11 | 12 | 13 | class LayerNormalization(Layer): 14 | 15 | def __init__(self, 16 | center=True, 17 | scale=True, 18 | epsilon=None, 19 | gamma_initializer='ones', 20 | beta_initializer='zeros', 21 | gamma_regularizer=None, 22 | beta_regularizer=None, 23 | gamma_constraint=None, 24 | beta_constraint=None, 25 | **kwargs): 26 | """Layer normalization layer 27 | 28 | See: [Layer Normalization](https://arxiv.org/pdf/1607.06450.pdf) 29 | 30 | :param center: Add an offset parameter if it is True. 31 | :param scale: Add a scale parameter if it is True. 32 | :param epsilon: Epsilon for calculating variance. 33 | :param gamma_initializer: Initializer for the gamma weight. 34 | :param beta_initializer: Initializer for the beta weight. 35 | :param gamma_regularizer: Optional regularizer for the gamma weight. 36 | :param beta_regularizer: Optional regularizer for the beta weight. 37 | :param gamma_constraint: Optional constraint for the gamma weight. 38 | :param beta_constraint: Optional constraint for the beta weight. 39 | :param kwargs: 40 | """ 41 | super(LayerNormalization, self).__init__(**kwargs) 42 | self.supports_masking = True 43 | self.center = center 44 | self.scale = scale 45 | if epsilon is None: 46 | epsilon = K.epsilon() * K.epsilon() 47 | self.epsilon = epsilon 48 | self.gamma_initializer = keras.initializers.get(gamma_initializer) 49 | self.beta_initializer = keras.initializers.get(beta_initializer) 50 | self.gamma_regularizer = keras.regularizers.get(gamma_regularizer) 51 | self.beta_regularizer = keras.regularizers.get(beta_regularizer) 52 | self.gamma_constraint = keras.constraints.get(gamma_constraint) 53 | self.beta_constraint = keras.constraints.get(beta_constraint) 54 | self.gamma, self.beta = None, None 55 | 56 | def get_config(self): 57 | config = { 58 | 'center': self.center, 59 | 'scale': self.scale, 60 | 'epsilon': self.epsilon, 61 | 'gamma_initializer': keras.initializers.serialize(self.gamma_initializer), 62 | 'beta_initializer': keras.initializers.serialize(self.beta_initializer), 63 | 'gamma_regularizer': keras.regularizers.serialize(self.gamma_regularizer), 64 | 'beta_regularizer': keras.regularizers.serialize(self.beta_regularizer), 65 | 'gamma_constraint': keras.constraints.serialize(self.gamma_constraint), 66 | 'beta_constraint': keras.constraints.serialize(self.beta_constraint), 67 | } 68 | base_config = super(LayerNormalization, self).get_config() 69 | return dict(list(base_config.items()) + list(config.items())) 70 | 71 | def compute_output_shape(self, input_shape): 72 | return input_shape 73 | 74 | def compute_mask(self, inputs, input_mask=None): 75 | return input_mask 76 | 77 | def build(self, input_shape): 78 | self.input_spec = keras.layers.InputSpec(shape=input_shape) 79 | shape = input_shape[-1:] 80 | if self.scale: 81 | self.gamma = self.add_weight( 82 | shape=shape, 83 | initializer=self.gamma_initializer, 84 | regularizer=self.gamma_regularizer, 85 | constraint=self.gamma_constraint, 86 | name='gamma', 87 | ) 88 | if self.center: 89 | self.beta = self.add_weight( 90 | shape=shape, 91 | initializer=self.beta_initializer, 92 | regularizer=self.beta_regularizer, 93 | constraint=self.beta_constraint, 94 | name='beta', 95 | ) 96 | super(LayerNormalization, self).build(input_shape) 97 | 98 | def call(self, inputs, training=None): 99 | mean = K.mean(inputs, axis=-1, keepdims=True) 100 | variance = K.mean(K.square(inputs - mean), axis=-1, keepdims=True) 101 | std = K.sqrt(variance + self.epsilon) 102 | outputs = (inputs - mean) / std 103 | if self.scale: 104 | outputs *= self.gamma 105 | if self.center: 106 | outputs += self.beta 107 | return outputs 108 | -------------------------------------------------------------------------------- /keras_textclassification/keras_layers/transformer_utils/readme.md: -------------------------------------------------------------------------------- 1 | reference: 2 | 1.code from github: 3 | author:CyberZHG; 4 | url: https://github.com/CyberZHG/keras-transformer. 5 | 2.change: 6 | some code of function and so on. 7 | 8 | -------------------------------------------------------------------------------- /keras_textclassification/keras_layers/transformer_utils/scale_dot_product_attention.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/7/22 9:26 4 | # @author :Mo 5 | # @function : 6 | 7 | 8 | from keras.layers import Layer 9 | import keras.backend as K 10 | 11 | 12 | class ScaledDotProductAttention(Layer): 13 | """The attention layer that takes three inputs representing queries, keys and values. 14 | 15 | \text{Attention}(Q, K, V) = \text{softmax}(\frac{Q K^T}{\sqrt{d_k}}) V 16 | 17 | See: https://arxiv.org/pdf/1706.03762.pdf 18 | """ 19 | 20 | def __init__(self, 21 | return_attention=False, 22 | history_only=False, 23 | **kwargs): 24 | """Initialize the layer. 25 | 26 | :param return_attention: Whether to return attention weights. 27 | :param history_only: Whether to only use history data. 28 | :param kwargs: Arguments for parent class. 29 | """ 30 | self.supports_masking = True 31 | self.return_attention = return_attention 32 | self.history_only = history_only 33 | super(ScaledDotProductAttention, self).__init__(**kwargs) 34 | 35 | def get_config(self): 36 | config = { 37 | 'return_attention': self.return_attention, 38 | 'history_only': self.history_only, 39 | } 40 | base_config = super(ScaledDotProductAttention, self).get_config() 41 | return dict(list(base_config.items()) + list(config.items())) 42 | 43 | def compute_output_shape(self, input_shape): 44 | if isinstance(input_shape, list): 45 | query_shape, key_shape, value_shape = input_shape 46 | else: 47 | query_shape = key_shape = value_shape = input_shape 48 | output_shape = query_shape[:-1] + value_shape[-1:] 49 | if self.return_attention: 50 | attention_shape = query_shape[:2] + (key_shape[1],) 51 | return [output_shape, attention_shape] 52 | return output_shape 53 | 54 | def compute_mask(self, inputs, mask=None): 55 | if isinstance(mask, list): 56 | mask = mask[0] 57 | if self.return_attention: 58 | return [mask, None] 59 | return mask 60 | 61 | def call(self, inputs, mask=None, **kwargs): 62 | if isinstance(inputs, list): 63 | query, key, value = inputs 64 | else: 65 | query = key = value = inputs 66 | if isinstance(mask, list): 67 | mask = mask[1] 68 | feature_dim = K.shape(query)[-1] 69 | e = K.batch_dot(query, key, axes=2) / K.sqrt(K.cast(feature_dim, dtype=K.floatx())) 70 | e = K.exp(e - K.max(e, axis=-1, keepdims=True)) 71 | if self.history_only: 72 | query_len, key_len = K.shape(query)[1], K.shape(key)[1] 73 | indices = K.tile(K.expand_dims(K.arange(key_len), axis=0), [query_len, 1]) 74 | upper = K.expand_dims(K.arange(key_len), axis=-1) 75 | e *= K.expand_dims(K.cast(indices <= upper, K.floatx()), axis=0) 76 | if mask is not None: 77 | e *= K.cast(K.expand_dims(mask, axis=-2), K.floatx()) 78 | a = e / (K.sum(e, axis=-1, keepdims=True) + K.epsilon()) 79 | v = K.batch_dot(a, value) 80 | if self.return_attention: 81 | return [v, a] 82 | return v 83 | -------------------------------------------------------------------------------- /keras_textclassification/keras_layers/transformer_utils/triangle_position_embedding.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/7/22 9:36 4 | # @author :Mo 5 | # @function : 6 | 7 | 8 | from keras.layers import Layer 9 | import keras.backend as K 10 | 11 | 12 | class TriglePositiomEmbedding(Layer): 13 | """Position embedding use sine and cosine functions. 14 | 15 | See: https://arxiv.org/pdf/1706.03762 16 | 17 | Expand mode: 18 | # Input shape 19 | 2D tensor with shape: `(batch_size, sequence_length)`. 20 | 21 | # Output shape 22 | 3D tensor with shape: `(batch_size, sequence_length, output_dim)`. 23 | 24 | Add mode: 25 | # Input shape 26 | 3D tensor with shape: `(batch_size, sequence_length, feature_dim)`. 27 | 28 | # Output shape 29 | 3D tensor with shape: `(batch_size, sequence_length, feature_dim)`. 30 | 31 | Concat mode: 32 | # Input shape 33 | 3D tensor with shape: `(batch_size, sequence_length, feature_dim)`. 34 | 35 | # Output shape 36 | 3D tensor with shape: `(batch_size, sequence_length, feature_dim + output_dim)`. 37 | """ 38 | MODE_EXPAND = 'expand' 39 | MODE_ADD = 'add' 40 | MODE_CONCAT = 'concat' 41 | 42 | def __init__(self, 43 | mode=MODE_ADD, 44 | output_dim=None, 45 | **kwargs): 46 | """ 47 | :param output_dim: The embedding dimension. 48 | :param kwargs: 49 | """ 50 | if mode in [self.MODE_EXPAND, self.MODE_CONCAT]: 51 | if output_dim is None: 52 | raise NotImplementedError('`output_dim` is required in `%s` mode' % mode) 53 | if output_dim % 2 != 0: 54 | raise NotImplementedError('It does not make sense to use an odd output dimension: %d' % output_dim) 55 | self.mode = mode 56 | self.output_dim = output_dim 57 | self.supports_masking = True 58 | super(TriglePositiomEmbedding, self).__init__(**kwargs) 59 | 60 | def get_config(self): 61 | config = { 62 | 'mode': self.mode, 63 | 'output_dim': self.output_dim, 64 | } 65 | base_config = super(TriglePositiomEmbedding, self).get_config() 66 | return dict(list(base_config.items()) + list(config.items())) 67 | 68 | def compute_mask(self, inputs, mask=None): 69 | return mask 70 | 71 | def compute_output_shape(self, input_shape): 72 | if self.mode == self.MODE_EXPAND: 73 | return input_shape + (self.output_dim,) 74 | if self.mode == self.MODE_CONCAT: 75 | return input_shape[:-1] + (input_shape[-1] + self.output_dim,) 76 | return input_shape 77 | 78 | def call(self, inputs, mask=None): 79 | input_shape = K.shape(inputs) 80 | if self.mode == self.MODE_ADD: 81 | batch_size, seq_len, output_dim = input_shape[0], input_shape[1], input_shape[2] 82 | pos_input = K.tile(K.expand_dims(K.arange(seq_len), axis=0), [batch_size, 1]) 83 | elif self.mode == self.MODE_CONCAT: 84 | batch_size, seq_len, output_dim = input_shape[0], input_shape[1], self.output_dim 85 | pos_input = K.tile(K.expand_dims(K.arange(seq_len), axis=0), [batch_size, 1]) 86 | else: 87 | output_dim = self.output_dim 88 | pos_input = inputs 89 | if K.dtype(pos_input) != K.floatx(): 90 | pos_input = K.cast(pos_input, K.floatx()) 91 | evens = K.arange(output_dim // 2) * 2 92 | odds = K.arange(output_dim // 2) * 2 + 1 93 | even_embd = K.sin( 94 | K.dot( 95 | K.expand_dims(pos_input, -1), 96 | K.expand_dims(1.0 / K.pow( 97 | 10000.0, 98 | K.cast(evens, K.floatx()) / K.cast(output_dim, K.floatx()) 99 | ), 0) 100 | ) 101 | ) 102 | odd_embd = K.cos( 103 | K.dot( 104 | K.expand_dims(pos_input, -1), 105 | K.expand_dims(1.0 / K.pow( 106 | 10000.0, K.cast((odds - 1), K.floatx()) / K.cast(output_dim, K.floatx()) 107 | ), 0) 108 | ) 109 | ) 110 | embd = K.stack([even_embd, odd_embd], axis=-1) 111 | output = K.reshape(embd, [-1, K.shape(inputs)[1], output_dim]) 112 | if self.mode == self.MODE_CONCAT: 113 | output = K.concatenate([inputs, output], axis=-1) 114 | if self.mode == self.MODE_ADD: 115 | output += inputs 116 | return output 117 | -------------------------------------------------------------------------------- /keras_textclassification/m00_Albert/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/10/14 10:15 4 | # @author :Mo 5 | # @function : -------------------------------------------------------------------------------- /keras_textclassification/m00_Albert/graph.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/10/14 20:27 4 | # @author :Mo 5 | # @function :graph of albert fineture, 后面不接什么网络结构, 只有一个激活层 6 | 7 | from __future__ import print_function, division 8 | 9 | from keras.layers import SpatialDropout1D, Conv1D, GlobalMaxPooling1D, Dense 10 | from keras.layers import Dropout, Reshape, Concatenate, Lambda 11 | from keras.layers import LSTM, GRU 12 | from keras.layers import Flatten 13 | from keras.models import Model 14 | from keras import backend as K 15 | from keras import regularizers 16 | 17 | from keras_textclassification.base.graph import graph 18 | import numpy as np 19 | 20 | 21 | class AlbertGraph(graph): 22 | def __init__(self, hyper_parameters): 23 | """ 24 | 初始化 25 | :param hyper_parameters: json,超参 26 | """ 27 | super().__init__(hyper_parameters) 28 | 29 | def create_model(self, hyper_parameters): 30 | """ 31 | 构建神经网络 32 | :param hyper_parameters:json, hyper parameters of network 33 | :return: tensor, moedl 34 | """ 35 | super().create_model(hyper_parameters) 36 | embedding_output = self.word_embedding.output 37 | x = Lambda(lambda x : x[:, 0:1, :])(embedding_output) # 获取CLS 38 | # # text cnn 39 | # bert_output_emmbed = SpatialDropout1D(rate=self.dropout)(embedding_output) 40 | # concat_out = [] 41 | # for index, filter_size in enumerate(self.filters): 42 | # x = Conv1D(name='TextCNN_Conv1D_{}'.format(index), 43 | # filters= self.filters_num, # int(K.int_shape(embedding_output)[-1]/self.len_max), 44 | # strides=1, 45 | # kernel_size=self.filters[index], 46 | # padding='valid', 47 | # kernel_initializer='normal', 48 | # activation='relu')(bert_output_emmbed) 49 | # x = GlobalMaxPooling1D(name='TextCNN_MaxPool1D_{}'.format(index))(x) 50 | # concat_out.append(x) 51 | # x = Concatenate(axis=1)(concat_out) 52 | # x = Dropout(self.dropout)(x) 53 | x = Flatten()(x) 54 | x = Dropout(self.dropout)(x) 55 | x = Dense(128, activation="tanh")(x) 56 | x = Dropout(self.dropout)(x) 57 | # 最后就是softmax 58 | dense_layer = Dense(self.label, activation=self.activate_classify)(x) 59 | output_layers = [dense_layer] 60 | self.model = Model(self.word_embedding.input, output_layers) 61 | self.model.summary(132) 62 | -------------------------------------------------------------------------------- /keras_textclassification/m00_Bert/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/13 22:55 4 | # @author :Mo 5 | # @function : -------------------------------------------------------------------------------- /keras_textclassification/m00_Bert/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yongzhuo/Keras-TextClassification/af802f1dc6962cab2c47f93c123f18f169bacf1a/keras_textclassification/m00_Bert/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /keras_textclassification/m00_Bert/__pycache__/graph.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yongzhuo/Keras-TextClassification/af802f1dc6962cab2c47f93c123f18f169bacf1a/keras_textclassification/m00_Bert/__pycache__/graph.cpython-36.pyc -------------------------------------------------------------------------------- /keras_textclassification/m00_Bert/graph.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/13 23:06 4 | # @author :Mo 5 | # @function :graph of bert fineture, 后面不接什么网络结构, 只有一个激活层 6 | 7 | from __future__ import print_function, division 8 | 9 | from keras.layers import SpatialDropout1D, Conv1D, GlobalMaxPooling1D, Dense 10 | from keras.layers import Dropout, Reshape, Concatenate, Lambda 11 | from keras.layers import LSTM, GRU 12 | from keras.layers import Flatten 13 | from keras.models import Model 14 | from keras import backend as K 15 | from keras import regularizers 16 | 17 | from keras_textclassification.base.graph import graph 18 | 19 | import numpy as np 20 | 21 | 22 | class BertGraph(graph): 23 | def __init__(self, hyper_parameters): 24 | """ 25 | 初始化 26 | :param hyper_parameters: json,超参 27 | """ 28 | super().__init__(hyper_parameters) 29 | 30 | def create_model(self, hyper_parameters): 31 | """ 32 | 构建神经网络 33 | :param hyper_parameters:json, hyper parameters of network 34 | :return: tensor, moedl 35 | """ 36 | super().create_model(hyper_parameters) 37 | embedding_output = self.word_embedding.output 38 | x = Lambda(lambda x : x[:, 0:1, :])(embedding_output) # 获取CLS 39 | # # text cnn 40 | # bert_output_emmbed = SpatialDropout1D(rate=self.dropout)(embedding_output) 41 | # concat_out = [] 42 | # for index, filter_size in enumerate(self.filters): 43 | # x = Conv1D(name='TextCNN_Conv1D_{}'.format(index), 44 | # filters= self.filters_num, # int(K.int_shape(embedding_output)[-1]/self.len_max), 45 | # strides=1, 46 | # kernel_size=self.filters[index], 47 | # padding='valid', 48 | # kernel_initializer='normal', 49 | # activation='relu')(bert_output_emmbed) 50 | # x = GlobalMaxPooling1D(name='TextCNN_MaxPool1D_{}'.format(index))(x) 51 | # concat_out.append(x) 52 | # x = Concatenate(axis=1)(concat_out) 53 | # x = Dropout(self.dropout)(x) 54 | 55 | x = Flatten()(x) 56 | # 最后就是softmax 57 | dense_layer = Dense(self.label, activation=self.activate_classify)(x) 58 | output_layers = [dense_layer] 59 | self.model = Model(self.word_embedding.input, output_layers) 60 | self.model.summary(120) 61 | -------------------------------------------------------------------------------- /keras_textclassification/m00_Xlnet/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/13 22:55 4 | # @author :Mo 5 | # @function : -------------------------------------------------------------------------------- /keras_textclassification/m00_Xlnet/graph.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/8/28 23:06 4 | # @author :Mo 5 | # @function :graph of xlnet fineture, 后面不接什么网络结构, 只有一个激活层 6 | # @paper :XLNet: Generalized Autoregressive Pretraining for Language Understanding 7 | 8 | from __future__ import print_function, division 9 | 10 | from keras.layers import SpatialDropout1D, Conv1D, GlobalMaxPooling1D, Dense 11 | from keras.layers import Dropout, Reshape, Concatenate, Lambda 12 | from keras.layers import LSTM, GRU 13 | from keras.layers import Flatten 14 | from keras.models import Model 15 | from keras import backend as K 16 | from keras import regularizers 17 | 18 | from keras_textclassification.base.graph import graph 19 | 20 | import numpy as np 21 | 22 | 23 | class XlnetGraph(graph): 24 | def __init__(self, hyper_parameters): 25 | """ 26 | 初始化 27 | :param hyper_parameters: json,超参 28 | """ 29 | super().__init__(hyper_parameters) 30 | 31 | def create_model(self, hyper_parameters): 32 | """ 33 | 构建神经网络 34 | :param hyper_parameters:json, hyper parameters of network 35 | :return: tensor, moedl 36 | """ 37 | super().create_model(hyper_parameters) 38 | embedding_output = self.word_embedding.output 39 | # x = embedding_output 40 | # x = Lambda(lambda x: x[:, -1:, :])(embedding_output) # 获取CLS 41 | # x = Lambda(lambda x: x[:, -1:])(embedding_output) # 获取CLS 42 | x = embedding_output # 直接output 43 | # # text cnn 44 | # bert_output_emmbed = SpatialDropout1D(rate=self.dropout)(embedding_output) 45 | # concat_out = [] 46 | # for index, filter_size in enumerate(self.filters): 47 | # x = Conv1D(name='TextCNN_Conv1D_{}'.format(index), 48 | # filters= self.filters_num, # int(K.int_shape(embedding_output)[-1]/self.len_max), 49 | # strides=1, 50 | # kernel_size=self.filters[index], 51 | # padding='valid', 52 | # kernel_initializer='normal', 53 | # activation='relu')(bert_output_emmbed) 54 | # x = GlobalMaxPooling1D(name='TextCNN_MaxPool1D_{}'.format(index))(x) 55 | # concat_out.append(x) 56 | # x = Concatenate(axis=1)(concat_out) 57 | x = Dropout(self.dropout)(x) 58 | x = Flatten()(x) 59 | # 最后就是softmax 60 | dense_layer = Dense(self.label, activation=self.activate_classify)(x) 61 | output_layers = [dense_layer] 62 | self.model = Model(self.word_embedding.input, output_layers) 63 | self.model.summary(120) 64 | -------------------------------------------------------------------------------- /keras_textclassification/m01_FastText/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/3 10:51 4 | # @author :Mo 5 | # @function : -------------------------------------------------------------------------------- /keras_textclassification/m02_TextCNN/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/7 22:09 4 | # @author :Mo 5 | # @function : -------------------------------------------------------------------------------- /keras_textclassification/m02_TextCNN/train.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/3 10:51 4 | # @author :Mo 5 | # @function :train of TextCNN with baidu-qa-2019 in question title 6 | 7 | 8 | # 适配linux 9 | import pathlib 10 | import sys 11 | import os 12 | project_path = str(pathlib.Path(os.path.abspath(__file__)).parent.parent.parent) 13 | sys.path.append(project_path) 14 | # 地址 15 | from keras_textclassification.conf.path_config import path_model, path_fineture, path_model_dir, path_hyper_parameters 16 | # 训练验证数据地址 17 | from keras_textclassification.conf.path_config import path_baidu_qa_2019_train, path_baidu_qa_2019_valid 18 | # 数据预处理, 删除文件目录下文件 19 | from keras_textclassification.data_preprocess.text_preprocess import PreprocessText, delete_file 20 | # 模型图 21 | from keras_textclassification.m02_TextCNN.graph import TextCNNGraph as Graph 22 | # 计算时间 23 | import time 24 | 25 | 26 | def train(hyper_parameters=None, rate=1.0): 27 | if not hyper_parameters: 28 | hyper_parameters = { 29 | 'len_max': 50, # 句子最大长度, 固定推荐20-50, bert越长会越慢, 占用空间也会变大, 本地win10-4G设为20就好, 过大小心OOM 30 | 'embed_size': 300, # 字/词向量维度, bert取768, word取300, char可以更小些 31 | 'vocab_size': 20000, # 这里随便填的,会根据代码里修改 32 | 'trainable': True, # embedding是静态的还是动态的, 即控制可不可以微调 33 | 'level_type': 'char', # 级别, 最小单元, 字/词, 填 'char' or 'word', 注意:word2vec模式下训练语料要首先切好 34 | 'embedding_type': 'random', # 级别, 嵌入类型, 还可以填'xlnet'、'random'、 'bert'、 'albert' or 'word2vec" 35 | 'gpu_memory_fraction': 0.76, #gpu使用率 36 | 'model': {'label': 17, # 类别数 37 | 'batch_size': 256, # 批处理尺寸, 感觉原则上越大越好,尤其是样本不均衡的时候, batch_size设置影响比较大 38 | 'dropout': 0.5, # 随机失活, 概率 39 | 'decay_step': 100, # 学习率衰减step, 每N个step衰减一次 40 | 'decay_rate': 0.9, # 学习率衰减系数, 乘法 41 | 'epochs': 20, # 训练最大轮次 42 | 'patience': 3, # 早停,2-3就好 43 | 'lr': 5e-3, # 学习率,bert取5e-5,其他取1e-3, 对训练会有比较大的影响, 如果准确率一直上不去,可以考虑调这个参数 44 | 'l2': 1e-9, # l2正则化 45 | 'activate_classify': 'softmax', # 最后一个layer, 即分类激活函数 46 | 'loss': 'categorical_crossentropy', # 损失函数 47 | 'metrics': 'accuracy', # 保存更好模型的评价标准 48 | 'is_training': True, # 训练后者是测试模型 49 | 'path_model_dir': path_model_dir, # 模型目录 50 | 'model_path': path_model, 51 | # 模型地址, loss降低则保存的依据, save_best_only=True, save_weights_only=True 52 | 'path_hyper_parameters': path_hyper_parameters, # 模型(包括embedding),超参数地址, 53 | 'path_fineture': path_fineture, # 保存embedding trainable地址, 例如字向量、词向量、bert向量等 54 | }, 55 | 'embedding': {'layer_indexes': [1, 2, 3, 12, 13], # bert取的层数,1为embedding层,未处理 56 | # 'corpus_path': 'Y:/BaiduNetdiskDownload/DataSet/bert-model/chinese_bert_chinese_wwm_L-12_H-768_A-12', # embedding预训练数据地址,不配则会默认取conf里边默认的地址 57 | # 'corpus_path':'Y:/BaiduNetdiskDownload/DataSet/bert-model/baidu_ernie', 58 | # keras - bert可以加载谷歌版bert, 百度版ernie(需转换,https: // github.com / ArthurRizar / tensorflow_ernie), 哈工大版bert - wwm(tf框架,https: // github.com / ymcui / Chinese - BERT - wwm) 59 | }, 60 | 'data':{'train_data': path_baidu_qa_2019_train, # 训练数据 61 | 'val_data': path_baidu_qa_2019_valid # 验证数据 62 | }, 63 | } 64 | 65 | # 删除先前存在的模型和embedding微调模型等 66 | delete_file(path_model_dir) 67 | time_start = time.time() 68 | # graph初始化 69 | graph = Graph(hyper_parameters) 70 | print("graph init ok!") 71 | ra_ed = graph.word_embedding 72 | # 数据预处理 73 | pt = PreprocessText(path_model_dir) 74 | x_train, y_train = pt.preprocess_label_ques_to_idx(hyper_parameters['embedding_type'], 75 | hyper_parameters['data']['train_data'], 76 | ra_ed, rate=rate, shuffle=True) 77 | x_val, y_val = pt.preprocess_label_ques_to_idx(hyper_parameters['embedding_type'], 78 | hyper_parameters['data']['val_data'], 79 | ra_ed, rate=rate, shuffle=True) 80 | print("data propress ok!") 81 | print(len(y_train)) 82 | # 训练 graph.fit(x_train, y_train, x_val, y_val) 83 | print("耗时:" + str(time.time()-time_start)) 84 | 85 | 86 | if __name__=="__main__": 87 | train(rate=1) 88 | 89 | 90 | -------------------------------------------------------------------------------- /keras_textclassification/m03_CharCNN/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/7 23:08 4 | # @author :Mo 5 | # @function : -------------------------------------------------------------------------------- /keras_textclassification/m03_CharCNN/graph_zhang.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/12 14:32 4 | # @author :Mo 5 | # @function :graph of charCNN-zhang 6 | # @paper : Character-level Convolutional Networks for Text Classification(https://arxiv.org/pdf/1509.01626.pdf) 7 | 8 | 9 | from __future__ import print_function, division 10 | 11 | # char cnn 12 | from keras.layers import Convolution1D, MaxPooling1D, ThresholdedReLU 13 | from keras.layers import Dense, Dropout, Flatten 14 | from keras.models import Model 15 | 16 | from keras_textclassification.base.graph import graph 17 | 18 | 19 | class CharCNNGraph(graph): 20 | def __init__(self, hyper_parameters): 21 | """ 22 | 初始化 23 | :param hyper_parameters: json,超参 24 | """ 25 | self.char_cnn_layers = hyper_parameters['model'].get('char_cnn_layers', 26 | [[256, 7, 3], [256, 7, 3], [256, 3, -1], [256, 3, -1], [256, 3, -1], [256, 3, 3]],) 27 | self.full_connect_layers = hyper_parameters['model'].get('full_connect_layers', [1024, 1024],) 28 | self.threshold = hyper_parameters['model'].get('threshold', 1e-6) 29 | super().__init__(hyper_parameters) 30 | 31 | def create_model(self, hyper_parameters): 32 | """ 33 | 构建神经网络 34 | :param hyper_parameters:json, hyper parameters of network 35 | :return: tensor, moedl 36 | """ 37 | super().create_model(hyper_parameters) 38 | x = self.word_embedding.output 39 | # x = Reshape((self.len_max, self.embed_size, 1))(embedding_output) # (None, 50, 30, 1) 40 | # cnn + pool 41 | for char_cnn_size in self.char_cnn_layers: 42 | x = Convolution1D(filters = char_cnn_size[0], 43 | kernel_size = char_cnn_size[1],)(x) 44 | x = ThresholdedReLU(self.threshold)(x) 45 | if char_cnn_size[2] != -1: 46 | x = MaxPooling1D(pool_size = char_cnn_size[2], 47 | strides = 1)(x) 48 | x = Flatten()(x) 49 | # full-connect 50 | for full in self.full_connect_layers: 51 | x = Dense(units=full,)(x) 52 | x = ThresholdedReLU(self.threshold)(x) 53 | x = Dropout(self.dropout)(x) 54 | output = Dense(units=self.label, activation=self.activate_classify)(x) 55 | self.model = Model(inputs=self.word_embedding.input, outputs=output) 56 | self.model.summary(120) -------------------------------------------------------------------------------- /keras_textclassification/m04_TextRNN/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/12 14:38 4 | # @author :Mo 5 | # @function : -------------------------------------------------------------------------------- /keras_textclassification/m04_TextRNN/graph.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/3 10:51 4 | # @author :Mo 5 | # @function :graph of base 6 | 7 | 8 | from keras.layers import LSTM, GRU, Bidirectional, CuDNNLSTM, CuDNNGRU 9 | from keras.layers import Dense, Dropout, Flatten 10 | from keras import regularizers 11 | from keras.models import Model 12 | 13 | from keras_textclassification.base.graph import graph 14 | 15 | 16 | class TextRNNGraph(graph): 17 | def __init__(self, hyper_parameters): 18 | """ 19 | 初始化 20 | :param hyper_parameters: json,超参 21 | """ 22 | self.num_rnn_layers = hyper_parameters['model'].get('num_rnn_layers', 2) 23 | self.rnn_type = hyper_parameters['model'].get('rnn_type', 'LSTM') 24 | self.rnn_units = hyper_parameters['model'].get('rnn_units', 256) 25 | super().__init__(hyper_parameters) 26 | 27 | def create_model(self, hyper_parameters): 28 | """ 29 | 构建神经网络 30 | :param hyper_parameters:json, hyper parameters of network 31 | :return: tensor, moedl 32 | """ 33 | super().create_model(hyper_parameters) 34 | x = self.word_embedding.output 35 | # x = Reshape((self.len_max, self.embed_size, 1))(embedding) 36 | if self.rnn_type=="LSTM": 37 | layer_cell = LSTM 38 | elif self.rnn_type=="GRU": 39 | layer_cell = GRU 40 | elif self.rnn_type=="CuDNNLSTM": 41 | layer_cell = CuDNNLSTM 42 | elif self.rnn_type=="CuDNNGRU": 43 | layer_cell = CuDNNGRU 44 | else: 45 | layer_cell = GRU 46 | 47 | # Bi-LSTM 48 | for nrl in range(self.num_rnn_layers): 49 | x = Bidirectional(layer_cell(units=self.rnn_units, 50 | return_sequences=True, 51 | activation='relu', 52 | kernel_regularizer=regularizers.l2(0.32 * 0.1), 53 | recurrent_regularizer=regularizers.l2(0.32) 54 | ))(x) 55 | x = Dropout(self.dropout)(x) 56 | x = Flatten()(x) 57 | # 最后就是softmax 58 | dense_layer = Dense(self.label, activation=self.activate_classify)(x) 59 | output = [dense_layer] 60 | self.model = Model(self.word_embedding.input, output) 61 | self.model.summary(120) 62 | -------------------------------------------------------------------------------- /keras_textclassification/m04_TextRNN/train.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/3 10:51 4 | # @author :Mo 5 | # @function :train of text-rnn with baidu-qa-2019 in question title 6 | 7 | # 适配linux 8 | import pathlib 9 | import sys 10 | import os 11 | project_path = str(pathlib.Path(os.path.abspath(__file__)).parent.parent.parent) 12 | sys.path.append(project_path) 13 | # 地址 14 | from keras_textclassification.conf.path_config import path_model, path_fineture, path_model_dir, path_hyper_parameters 15 | # 训练验证数据地址 16 | from keras_textclassification.conf.path_config import path_baidu_qa_2019_train, path_baidu_qa_2019_valid 17 | # 数据预处理, 删除文件目录下文件 18 | from keras_textclassification.data_preprocess.text_preprocess import PreprocessText, delete_file 19 | # 模型图 20 | from keras_textclassification.m04_TextRNN.graph import TextRNNGraph as Graph 21 | # 计算时间 22 | import time 23 | 24 | 25 | def train(hyper_parameters=None, rate=1.0): 26 | if not hyper_parameters: 27 | hyper_parameters = { 28 | 'len_max': 50, # 句子最大长度, 固定推荐20-50, bert越长会越慢, 占用空间也会变大, 本地win10-4G设为20就好, 过大小心OOM 29 | 'embed_size': 300, # 字/词向量维度, bert取768, word取300, char可以更小些 30 | 'vocab_size': 20000, # 这里随便填的,会根据代码里修改 31 | 'trainable': True, # embedding是静态的还是动态的, 即控制可不可以微调 32 | 'level_type': 'char', # 级别, 最小单元, 字/词, 填 'char' or 'word', 注意:word2vec模式下训练语料要首先切好 33 | 'embedding_type': 'random', # 级别, 嵌入类型, 还可以填'xlnet'、'random'、 'bert'、 'albert' or 'word2vec" 34 | 'gpu_memory_fraction': 0.66, #gpu使用率 35 | 'model': {'label': 17, # 类别数 36 | 'batch_size': 256, # 批处理尺寸, 感觉原则上越大越好,尤其是样本不均衡的时候, batch_size设置影响比较大 37 | 'dropout': 0.5, # 随机失活, 概率 38 | 'decay_step': 100, # 学习率衰减step, 每N个step衰减一次 39 | 'decay_rate': 0.9, # 学习率衰减系数, 乘法 40 | 'epochs': 20, # 训练最大轮次 41 | 'patience': 3, # 早停,2-3就好 42 | 'lr': 1e-2, # 学习率, bert取5e-5,其他取1e-3,如果acc较低或者一直不变,优先调这个, 对训练会有比较大的影响, 如果准确率一直上不去,可以考虑调这个参数 43 | 'l2': 1e-9, # l2正则化 44 | 'activate_classify': 'softmax', # 最后一个layer, 即分类激活函数 45 | 'loss': 'categorical_crossentropy', # 损失函数 46 | 'metrics': 'accuracy', # 保存更好模型的评价标准 47 | 'is_training': True, # 训练后者是测试模型 48 | 'model_path': path_model, 49 | # 模型地址, loss降低则保存的依据, save_best_only=True, save_weights_only=True 50 | 'path_hyper_parameters': path_hyper_parameters, # 模型(包括embedding),超参数地址, 51 | 'path_fineture': path_fineture, # 保存embedding trainable地址, 例如字向量、词向量、bert向量等 52 | 'num_rnn_layers': 1, # rnn层数 53 | 'rnn_type': 'GRU', # rnn类型,可以填"LSTM","GRU","CuDNNLSTM","CuDNNGRU" 54 | 'rnn_units': 256, # rnn隐藏元 55 | }, 56 | 'embedding': {'layer_indexes': [12], # bert取的层数 57 | # 'corpus_path': '', # embedding预训练数据地址,不配则会默认取conf里边默认的地址, keras-bert可以加载谷歌版bert,百度版ernie(需转换,https://github.com/ArthurRizar/tensorflow_ernie),哈工大版bert-wwm(tf框架,https://github.com/ymcui/Chinese-BERT-wwm) 58 | }, 59 | 'data':{'train_data': path_baidu_qa_2019_train, # 训练数据 60 | 'val_data': path_baidu_qa_2019_valid # 验证数据 61 | }, 62 | } 63 | 64 | # 删除先前存在的模型和embedding微调模型等 65 | delete_file(path_model_dir) 66 | time_start = time.time() 67 | # graph初始化 68 | graph = Graph(hyper_parameters) 69 | print("graph init ok!") 70 | ra_ed = graph.word_embedding 71 | # 数据预处理 72 | pt = PreprocessText(path_model_dir) 73 | x_train, y_train = pt.preprocess_label_ques_to_idx(hyper_parameters['embedding_type'], 74 | hyper_parameters['data']['train_data'], 75 | ra_ed, rate=rate, shuffle=True) 76 | x_val, y_val = pt.preprocess_label_ques_to_idx(hyper_parameters['embedding_type'], 77 | hyper_parameters['data']['val_data'], 78 | ra_ed, rate=rate, shuffle=True) 79 | print("data propress ok!") 80 | print(len(y_train)) 81 | # 训练 82 | graph.fit(x_train, y_train, x_val, y_val) 83 | print("耗时:" + str(time.time()-time_start)) 84 | 85 | 86 | if __name__=="__main__": 87 | train(rate=1) 88 | 89 | -------------------------------------------------------------------------------- /keras_textclassification/m05_TextRCNN/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/12 15:41 4 | # @author :Mo 5 | # @function : -------------------------------------------------------------------------------- /keras_textclassification/m05_TextRCNN/train.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/8 14:37 4 | # @author :Mo 5 | # @function :train of RCNNGraph_kim with baidu-qa-2019 in question title 6 | 7 | 8 | # 适配linux 9 | import pathlib 10 | import sys 11 | import os 12 | project_path = str(pathlib.Path(os.path.abspath(__file__)).parent.parent.parent) 13 | sys.path.append(project_path) 14 | # 地址 15 | from keras_textclassification.conf.path_config import path_model, path_fineture, path_model_dir, path_hyper_parameters 16 | # 训练验证数据地址 17 | from keras_textclassification.conf.path_config import path_baidu_qa_2019_train, path_baidu_qa_2019_valid 18 | # 数据预处理, 删除文件目录下文件 19 | from keras_textclassification.data_preprocess.text_preprocess import PreprocessText, delete_file 20 | # 模型图 21 | from keras_textclassification.m05_TextRCNN.graph import RCNNGraph as Graph 22 | # 计算时间 23 | import time 24 | 25 | 26 | def train(hyper_parameters=None, rate=1.0): 27 | """ 28 | 训练函数 29 | :param hyper_parameters: json, 超参数 30 | :param rate: 比率, 抽出rate比率语料取训练 31 | :return: None 32 | """ 33 | if not hyper_parameters: 34 | hyper_parameters = { 35 | 'len_max': 50, # 句子最大长度, 固定 推荐20-50 36 | 'embed_size': 300, # 字/词向量维度 37 | 'vocab_size': 20000, # 这里随便填的,会根据代码里修改 38 | 'trainable': True, # embedding是静态的还是动态的, 即控制可不可以微调 39 | 'level_type': 'char', # 级别, 最小单元, 字/词, 填 'char' or 'word' 40 | 'embedding_type': 'random', # 级别, 嵌入类型, 还可以填'xlnet'、'random'、 'bert'、 'albert' or 'word2vec" 41 | 'gpu_memory_fraction': 0.66, #gpu使用率 42 | 'model': {'label': 17, # 类别数 43 | 'batch_size': 256, # 批处理尺寸, 感觉原则上越大越好,尤其是样本不均衡的时候, batch_size设置影响比较大 44 | 'filters': [2, 3, 4, 5], # 卷积核尺寸 45 | 'filters_num': 300, # 卷积个数 text-cnn:300-600 46 | 'channel_size': 1, # CNN通道数 47 | 'dropout': 0.32, # 随机失活, 概率 48 | 'decay_step': 100, # 学习率衰减step, 每N个step衰减一次 49 | 'decay_rate': 0.9, # 学习率衰减系数, 乘法 50 | 'epochs': 50, # 训练最大轮次 51 | 'patience': 3, # 早停,2-3就好 52 | 'lr': 5e-4, # 学习率, 对训练会有比较大的影响, 如果准确率一直上不去,可以考虑调这个参数 53 | 'l2': 1e-9, # l2正则化 54 | 'activate_classify': 'softmax', # 最后一个layer, 即分类激活函数 55 | 'loss': 'categorical_crossentropy', # 损失函数 56 | 'metrics': 'accuracy', # 保存更好模型的评价标准 57 | 'is_training': True, # 训练后者是测试模型 58 | 'path_model_dir': path_model_dir, # 模型目录 59 | 'model_path': path_model, 60 | # 模型地址, loss降低则保存的依据, save_best_only=True, save_weights_only=True 61 | 'path_hyper_parameters': path_hyper_parameters, # 模型(包括embedding),超参数地址, 62 | 'path_fineture': path_fineture, # 保存embedding trainable地址, 例如字向量、词向量、bert向量等 63 | 'rnn_type': 'LSTM', # rnn_type类型, 还可以填"GRU" 64 | 'rnn_units': 256, # RNN隐藏层 65 | }, 66 | 'embedding': {'layer_indexes': [12], # bert取的层数, 67 | # 'corpus_path': '', # embedding预训练数据地址,不配则会默认取conf里边默认的地址, keras-bert可以加载谷歌版bert,百度版ernie(需转换,https://github.com/ArthurRizar/tensorflow_ernie),哈工大版bert-wwm(tf框架,https://github.com/ymcui/Chinese-BERT-wwm) 68 | }, 69 | 'data':{'train_data': path_baidu_qa_2019_train, # 训练数据 70 | 'val_data': path_baidu_qa_2019_valid # 验证数据 71 | }, 72 | } 73 | 74 | # 删除先前存在的模型\embedding微调模型等 75 | delete_file(path_model_dir) 76 | time_start = time.time() 77 | # graph初始化 78 | graph = Graph(hyper_parameters) 79 | print("graph init ok!") 80 | ra_ed = graph.word_embedding 81 | # 数据预处理 82 | pt = PreprocessText(path_model_dir) 83 | x_train, y_train = pt.preprocess_label_ques_to_idx(hyper_parameters['embedding_type'], 84 | hyper_parameters['data']['train_data'], 85 | ra_ed, rate=rate, shuffle=True) 86 | x_val, y_val = pt.preprocess_label_ques_to_idx(hyper_parameters['embedding_type'], 87 | hyper_parameters['data']['val_data'], 88 | ra_ed, rate=rate, shuffle=True) 89 | print("data propress ok!") 90 | print(len(y_train)) 91 | # 训练 92 | graph.fit(x_train, y_train, x_val, y_val) 93 | print("耗时:" + str(time.time()-time_start)) 94 | 95 | 96 | if __name__=="__main__": 97 | train(rate=1) -------------------------------------------------------------------------------- /keras_textclassification/m06_TextDCNN/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/12 18:15 4 | # @author :Mo 5 | # @function : -------------------------------------------------------------------------------- /keras_textclassification/m06_TextDCNN/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yongzhuo/Keras-TextClassification/af802f1dc6962cab2c47f93c123f18f169bacf1a/keras_textclassification/m06_TextDCNN/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /keras_textclassification/m06_TextDCNN/__pycache__/graph.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yongzhuo/Keras-TextClassification/af802f1dc6962cab2c47f93c123f18f169bacf1a/keras_textclassification/m06_TextDCNN/__pycache__/graph.cpython-36.pyc -------------------------------------------------------------------------------- /keras_textclassification/m06_TextDCNN/train.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/8 14:37 4 | # @author :Mo 5 | # @function :train of CharCNNGraph_kim with baidu-qa-2019 in question title 6 | 7 | 8 | # 适配linux 9 | import pathlib 10 | import sys 11 | import os 12 | os.environ["CUDA_VISIBLE_DEVICES"] = "-1" 13 | project_path = str(pathlib.Path(os.path.abspath(__file__)).parent.parent.parent) 14 | sys.path.append(project_path) 15 | # 地址 16 | from keras_textclassification.conf.path_config import path_model, path_fineture, path_model_dir, path_hyper_parameters 17 | # 训练验证数据地址 18 | from keras_textclassification.conf.path_config import path_baidu_qa_2019_train, path_baidu_qa_2019_valid 19 | # 数据预处理, 删除文件目录下文件 20 | from keras_textclassification.data_preprocess.text_preprocess import PreprocessText, delete_file 21 | # 模型图 22 | from keras_textclassification.m06_TextDCNN.graph import DCNNGraph as Graph 23 | # 计算时间 24 | import time 25 | 26 | 27 | def train(hyper_parameters=None, rate=1.0): 28 | if not hyper_parameters: 29 | hyper_parameters = { 30 | 'len_max': 50, # 句子最大长度, 固定推荐20-50, bert越长会越慢, 占用空间也会变大, 本地win10-4G设为20就好, 过大小心OOM 31 | 'embed_size': 300, # 字/词向量维度, bert取768, word取300, char可以更小些 32 | 'vocab_size': 20000, # 这里随便填的,会根据代码里修改 33 | 'trainable': True, # embedding是静态的还是动态的, 即控制可不可以微调 34 | 'level_type': 'char', # 级别, 最小单元, 字/词, 填 'char' or 'word', 注意:word2vec模式下训练语料要首先切好 35 | 'embedding_type': 'random', # 级别, 嵌入类型, 还可以填'xlnet'、'random'、 'bert'、 'albert' or 'word2vec" 36 | 'gpu_memory_fraction': 0.66, #gpu使用率 37 | 'model': {'label': 17, # 类别数 38 | 'batch_size': 16, # 批处理尺寸, 感觉原则上越大越好,尤其是样本不均衡的时候, batch_size设置影响比较大 39 | 'filters': [[10, 7, 5], [6, 4, 3]], # 3层的时候 40 | # 'filters': [[10, 7], [5, 3]], # 2层的时候 41 | # 'filters': [[5, 3], [4, 2]], #2层的时候 42 | 'filters_num': 300, # 卷积个数 text-cnn:300-600 43 | 'channel_size': 1, # CNN通道数 44 | 'dropout': 0.32, # 随机失活, 概率 45 | 'decay_step': 100, # 学习率衰减step, 每N个step衰减一次 46 | 'decay_rate': 0.9, # 学习率衰减系数, 乘法 47 | 'epochs': 20, # 训练最大轮次 48 | 'patience': 3, # 早停,2-3就好 49 | 'lr': 1e-3, # 学习率,bert取5e-5,其他取1e-3, 对训练会有比较大的影响, 如果准确率一直上不去,可以考虑调这个参数 50 | 'l2': 1e-9, # l2正则化 51 | 'activate_classify': 'softmax', # 最后一个layer, 即分类激活函数 52 | 'loss': 'categorical_crossentropy', # 损失函数 53 | 'metrics': 'accuracy', # 保存更好模型的评价标准 54 | 'is_training': True, # 训练后者是测试模型 55 | 'model_path': path_model, # 模型地址, loss降低则保存的依据, save_best_only=True, save_weights_only=True 56 | 'path_hyper_parameters': path_hyper_parameters, # 模型(包括embedding),超参数地址, 57 | 'path_fineture': path_fineture, # 保存embedding trainable地址, 例如字向量、词向量、bert向量等 58 | }, 59 | 'embedding': {'layer_indexes': [12], # bert取的层数 60 | # 'corpus_path': '', # embedding预训练数据地址,不配则会默认取conf里边默认的地址, keras-bert可以加载谷歌版bert,百度版ernie(需转换,https://github.com/ArthurRizar/tensorflow_ernie),哈工大版bert-wwm(tf框架,https://github.com/ymcui/Chinese-BERT-wwm) 61 | }, 62 | 'data':{'train_data': path_baidu_qa_2019_train, # 训练数据 63 | 'val_data': path_baidu_qa_2019_valid # 验证数据 64 | }, 65 | } 66 | 67 | # 删除先前存在的模型和embedding微调模型等 68 | delete_file(path_model_dir) 69 | time_start = time.time() 70 | # graph初始化 71 | graph = Graph(hyper_parameters) 72 | print("graph init ok!") 73 | ra_ed = graph.word_embedding 74 | # 数据预处理 75 | pt = PreprocessText(path_model_dir) 76 | x_train, y_train = pt.preprocess_label_ques_to_idx(hyper_parameters['embedding_type'], 77 | hyper_parameters['data']['train_data'], 78 | ra_ed, rate=rate, shuffle=True) 79 | x_val, y_val = pt.preprocess_label_ques_to_idx(hyper_parameters['embedding_type'], 80 | hyper_parameters['data']['val_data'], 81 | ra_ed, rate=rate, shuffle=True) 82 | print("data propress ok!") 83 | print(len(y_train)) 84 | # 训练 85 | graph.fit(x_train, y_train, x_val, y_val) 86 | print("耗时:" + str(time.time()-time_start)) 87 | 88 | 89 | if __name__=="__main__": 90 | train(rate=1) 91 | 92 | -------------------------------------------------------------------------------- /keras_textclassification/m07_TextDPCNN/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/18 20:58 4 | # @author :Mo 5 | # @function : -------------------------------------------------------------------------------- /keras_textclassification/m07_TextDPCNN/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yongzhuo/Keras-TextClassification/af802f1dc6962cab2c47f93c123f18f169bacf1a/keras_textclassification/m07_TextDPCNN/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /keras_textclassification/m07_TextDPCNN/__pycache__/graph.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yongzhuo/Keras-TextClassification/af802f1dc6962cab2c47f93c123f18f169bacf1a/keras_textclassification/m07_TextDPCNN/__pycache__/graph.cpython-36.pyc -------------------------------------------------------------------------------- /keras_textclassification/m07_TextDPCNN/train.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/8 14:37 4 | # @author :Mo 5 | # @function :train of DPCNN with baidu-qa-2019 in question title 6 | 7 | 8 | # 适配linux 9 | import pathlib 10 | import sys 11 | import os 12 | project_path = str(pathlib.Path(os.path.abspath(__file__)).parent.parent.parent) 13 | sys.path.append(project_path) 14 | # 地址 15 | from keras_textclassification.conf.path_config import path_model, path_fineture, path_model_dir, path_hyper_parameters 16 | # 训练验证数据地址 17 | from keras_textclassification.conf.path_config import path_baidu_qa_2019_train, path_baidu_qa_2019_valid 18 | # 数据预处理, 删除文件目录下文件 19 | from keras_textclassification.data_preprocess.text_preprocess import PreprocessText, delete_file 20 | # 模型图 21 | from keras_textclassification.m07_TextDPCNN.graph import DPCNNGraph as Graph 22 | # 计算时间 23 | import time 24 | 25 | 26 | def train(hyper_parameters=None, rate=1.0): 27 | if not hyper_parameters: 28 | hyper_parameters = { 29 | 'len_max': 50, # 句子最大长度, 固定推荐20-50, bert越长会越慢, 占用空间也会变大, 本地win10-4G设为20就好, 过大小心OOM 30 | 'embed_size': 300, # 字/词向量维度, bert取768, word取300, char可以更小些 31 | 'vocab_size': 20000, # 这里随便填的,会根据代码里修改 32 | 'trainable': True, # embedding是静态的还是动态的, 即控制可不可以微调 33 | 'level_type': 'char', # 级别, 最小单元, 字/词, 填 'char' or 'word', 注意:word2vec模式下训练语料要首先切好 34 | 'embedding_type': 'random', # 级别, 嵌入类型, 还可以填'xlnet'、'random'、 'bert'、 'albert' or 'word2vec" 35 | 'gpu_memory_fraction': 0.66, #gpu使用率 36 | 'model': {'label': 17, # 类别数 37 | 'batch_size': 32, # 批处理尺寸, 感觉原则上越大越好,尤其是样本不均衡的时候, batch_size设置影响比较大 38 | 'filters': 3, # 固定feature maps(filters)的数量 39 | 'filters_num': 256, 40 | 'channel_size': 1, 41 | 'dropout': 0.5, # 随机失活, 概率 42 | 'decay_step': 100, # 学习率衰减step, 每N个step衰减一次 43 | 'decay_rate': 0.9, # 学习率衰减系数, 乘法 44 | 'epochs': 20, # 训练最大轮次 45 | 'patience': 3, # 早停,2-3就好 46 | 'lr': 1e-3, # 学习率,bert取5e-5,其他取1e-3, 对训练会有比较大的影响, 如果准确率一直上不去,可以考虑调这个参数 47 | 'l2': 1e-9, # l2正则化 48 | 'activate_classify': 'softmax', # 最后一个layer, 即分类激活函数 49 | 'loss': 'categorical_crossentropy', # 损失函数 50 | 'metrics': 'accuracy', # 保存更好模型的评价标准 51 | 'is_training': True, # 训练后者是测试模型 52 | 'model_path': path_model, # 模型地址, loss降低则保存的依据, save_best_only=True, save_weights_only=True 53 | 'path_hyper_parameters': path_hyper_parameters, # 模型(包括embedding),超参数地址, 54 | 'path_fineture': path_fineture, # 保存embedding trainable地址, 例如字向量、词向量、bert向量等 55 | # only DPCNN 56 | 'pooling_size_strides': [3, 2], # 固定1/2池化 57 | 'droupout_spatial': 0.2, # 作用是字/词/句向量某些维度覆盖,与dropout作用相同 58 | 'activation_conv': 'linear', # Shortcut connections with pre-activation 59 | 'layer_repeats': 7, # 小单元block,重复次数 60 | 'full_connect_unit': 256, # 全连接层隐藏元 61 | }, 62 | 'embedding': {'layer_indexes': [12], # bert取的层数 63 | # 'corpus_path': '', # embedding预训练数据地址,不配则会默认取conf里边默认的地址, keras-bert可以加载谷歌版bert,百度版ernie(需转换,https://github.com/ArthurRizar/tensorflow_ernie),哈工大版bert-wwm(tf框架,https://github.com/ymcui/Chinese-BERT-wwm) 64 | }, 65 | 'data':{'train_data': path_baidu_qa_2019_train, # 训练数据 66 | 'val_data': path_baidu_qa_2019_valid # 验证数据 67 | }, 68 | } 69 | 70 | # 删除先前存在的模型和embedding微调模型等 71 | delete_file(path_model_dir) 72 | time_start = time.time() 73 | # graph初始化 74 | graph = Graph(hyper_parameters) 75 | print("graph init ok!") 76 | ra_ed = graph.word_embedding 77 | # 数据预处理 78 | pt = PreprocessText(path_model_dir) 79 | x_train, y_train = pt.preprocess_label_ques_to_idx(hyper_parameters['embedding_type'], 80 | hyper_parameters['data']['train_data'], 81 | ra_ed, rate=rate, shuffle=True) 82 | x_val, y_val = pt.preprocess_label_ques_to_idx(hyper_parameters['embedding_type'], 83 | hyper_parameters['data']['val_data'], 84 | ra_ed, rate=rate, shuffle=True) 85 | print("data propress ok!") 86 | print(len(y_train)) 87 | # 训练 88 | graph.fit(x_train, y_train, x_val, y_val) 89 | print("耗时:" + str(time.time()-time_start)) 90 | 91 | 92 | if __name__=="__main__": 93 | train(rate=1) 94 | 95 | -------------------------------------------------------------------------------- /keras_textclassification/m08_TextVDCNN/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/20 20:03 4 | # @author :Mo 5 | # @function : -------------------------------------------------------------------------------- /keras_textclassification/m08_TextVDCNN/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yongzhuo/Keras-TextClassification/af802f1dc6962cab2c47f93c123f18f169bacf1a/keras_textclassification/m08_TextVDCNN/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /keras_textclassification/m08_TextVDCNN/__pycache__/graph.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yongzhuo/Keras-TextClassification/af802f1dc6962cab2c47f93c123f18f169bacf1a/keras_textclassification/m08_TextVDCNN/__pycache__/graph.cpython-36.pyc -------------------------------------------------------------------------------- /keras_textclassification/m09_TextCRNN/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/22 8:46 4 | # @author :Mo 5 | # @function : -------------------------------------------------------------------------------- /keras_textclassification/m09_TextCRNN/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yongzhuo/Keras-TextClassification/af802f1dc6962cab2c47f93c123f18f169bacf1a/keras_textclassification/m09_TextCRNN/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /keras_textclassification/m09_TextCRNN/__pycache__/graph.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yongzhuo/Keras-TextClassification/af802f1dc6962cab2c47f93c123f18f169bacf1a/keras_textclassification/m09_TextCRNN/__pycache__/graph.cpython-36.pyc -------------------------------------------------------------------------------- /keras_textclassification/m09_TextCRNN/graph.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/3 10:51 4 | # @author :Mo 5 | # @function :graph of CRNN 6 | # @paper :A C-LSTM Neural Network for Text Classification(https://arxiv.org/abs/1511.08630) 7 | 8 | 9 | from keras import regularizers 10 | from keras.models import Model 11 | from keras.layers import SpatialDropout1D, Conv1D 12 | from keras.layers import Dropout, Flatten, Dense, Concatenate 13 | from keras.layers import LSTM, GRU, Bidirectional, CuDNNLSTM, CuDNNGRU 14 | 15 | from keras_textclassification.base.graph import graph 16 | 17 | 18 | class CRNNGraph(graph): 19 | def __init__(self, hyper_parameters): 20 | """ 21 | 初始化 22 | :param hyper_parameters: json,超参 23 | """ 24 | self.rnn_type = hyper_parameters['model'].get('rnn_type', 'LSTM') 25 | self.rnn_units = hyper_parameters['model'].get('rnn_units', 650) # large, small is 300 26 | self.dropout_spatial = hyper_parameters['model'].get('dropout_spatial', 0.2) 27 | self.l2 = hyper_parameters['model'].get('l2', 0.001) 28 | super().__init__(hyper_parameters) 29 | 30 | def create_model(self, hyper_parameters): 31 | """ 32 | 构建神经网络 33 | :param hyper_parameters:json, hyper parameters of network 34 | :return: tensor, moedl 35 | """ 36 | super().create_model(hyper_parameters) 37 | x = self.word_embedding.output 38 | embedding_output_spatial = SpatialDropout1D(self.dropout_spatial)(x) 39 | 40 | if self.rnn_units=="LSTM": 41 | layer_cell = LSTM 42 | elif self.rnn_units=="GRU": 43 | layer_cell = GRU 44 | elif self.rnn_units=="CuDNNLSTM": 45 | layer_cell = CuDNNLSTM 46 | elif self.rnn_units=="CuDNNGRU": 47 | layer_cell = CuDNNGRU 48 | else: 49 | layer_cell = GRU 50 | # CNN 51 | convs = [] 52 | for kernel_size in self.filters: 53 | conv = Conv1D(self.filters_num, 54 | kernel_size=kernel_size, 55 | strides=1, 56 | padding='SAME', 57 | kernel_regularizer=regularizers.l2(self.l2), 58 | bias_regularizer=regularizers.l2(self.l2), 59 | )(embedding_output_spatial) 60 | convs.append(conv) 61 | x = Concatenate(axis=1)(convs) 62 | # Bi-LSTM, 论文中使用的是LSTM 63 | x = Bidirectional(layer_cell(units=self.rnn_units, 64 | return_sequences=True, 65 | activation='relu', 66 | kernel_regularizer=regularizers.l2(self.l2), 67 | recurrent_regularizer=regularizers.l2(self.l2) 68 | ))(x) 69 | x = Dropout(self.dropout)(x) 70 | x = Flatten()(x) 71 | # 最后就是softmax 72 | dense_layer = Dense(self.label, activation=self.activate_classify)(x) 73 | output = [dense_layer] 74 | self.model = Model(self.word_embedding.input, output) 75 | self.model.summary(120) 76 | -------------------------------------------------------------------------------- /keras_textclassification/m10_DeepMoji/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/21 23:24 4 | # @author :Mo 5 | # @function : -------------------------------------------------------------------------------- /keras_textclassification/m10_DeepMoji/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yongzhuo/Keras-TextClassification/af802f1dc6962cab2c47f93c123f18f169bacf1a/keras_textclassification/m10_DeepMoji/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /keras_textclassification/m10_DeepMoji/__pycache__/graph.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yongzhuo/Keras-TextClassification/af802f1dc6962cab2c47f93c123f18f169bacf1a/keras_textclassification/m10_DeepMoji/__pycache__/graph.cpython-36.pyc -------------------------------------------------------------------------------- /keras_textclassification/m11_SelfAttention/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/22 8:01 4 | # @author :Mo 5 | # @function : -------------------------------------------------------------------------------- /keras_textclassification/m11_SelfAttention/__pycache__/__init__.cpython-35.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yongzhuo/Keras-TextClassification/af802f1dc6962cab2c47f93c123f18f169bacf1a/keras_textclassification/m11_SelfAttention/__pycache__/__init__.cpython-35.pyc -------------------------------------------------------------------------------- /keras_textclassification/m11_SelfAttention/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yongzhuo/Keras-TextClassification/af802f1dc6962cab2c47f93c123f18f169bacf1a/keras_textclassification/m11_SelfAttention/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /keras_textclassification/m11_SelfAttention/__pycache__/graph.cpython-35.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yongzhuo/Keras-TextClassification/af802f1dc6962cab2c47f93c123f18f169bacf1a/keras_textclassification/m11_SelfAttention/__pycache__/graph.cpython-35.pyc -------------------------------------------------------------------------------- /keras_textclassification/m11_SelfAttention/__pycache__/graph.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yongzhuo/Keras-TextClassification/af802f1dc6962cab2c47f93c123f18f169bacf1a/keras_textclassification/m11_SelfAttention/__pycache__/graph.cpython-36.pyc -------------------------------------------------------------------------------- /keras_textclassification/m11_SelfAttention/graph.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/3 10:51 4 | # @author :Mo 5 | # @function :() 6 | 7 | 8 | from keras import regularizers 9 | from keras.layers import Dense 10 | from keras.layers import Dropout, Flatten 11 | from keras.layers import SpatialDropout1D, GlobalMaxPooling1D, GlobalAveragePooling1D, Concatenate 12 | from keras.models import Model 13 | 14 | from keras_textclassification.keras_layers.attention_self import AttentionSelf 15 | from keras_textclassification.base.graph import graph 16 | 17 | 18 | class SelfAttentionGraph(graph): 19 | def __init__(self, hyper_parameters): 20 | """ 21 | 初始化 22 | :param hyper_parameters: json,超参 23 | """ 24 | self.dropout_spatial = hyper_parameters['model'].get('droupout_spatial', 0.2) 25 | super().__init__(hyper_parameters) 26 | 27 | def create_model(self, hyper_parameters): 28 | """ 29 | 构建神经网络 30 | :param hyper_parameters:json, hyper parameters of network 31 | :return: tensor, moedl 32 | """ 33 | super().create_model(hyper_parameters) 34 | x = self.word_embedding.output 35 | x = SpatialDropout1D(self.dropout_spatial)(x) 36 | x = AttentionSelf(self.word_embedding.embed_size)(x) 37 | x_max = GlobalMaxPooling1D()(x) 38 | x_avg = GlobalAveragePooling1D()(x) 39 | x = Concatenate()([x_max, x_avg]) 40 | x = Dropout(self.dropout)(x) 41 | # x = Flatten()(x) 42 | x = Dense(72, activation="tanh")(x) 43 | x = Dropout(self.dropout)(x) 44 | # 最后就是softmax 45 | dense_layer = Dense(self.label, activation=self.activate_classify)(x) 46 | output = [dense_layer] 47 | self.model = Model(self.word_embedding.input, output) 48 | self.model.summary(120) 49 | -------------------------------------------------------------------------------- /keras_textclassification/m11_SelfAttention/train.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/3 10:51 4 | # @author :Mo 5 | # @function :train of SelfAttention with baidu-qa-2019 in question title 6 | 7 | # linux适配 8 | import pathlib 9 | import sys 10 | import os 11 | project_path = str(pathlib.Path(os.path.abspath(__file__)).parent.parent.parent) 12 | sys.path.append(project_path) 13 | # 地址 14 | from keras_textclassification.conf.path_config import path_model, path_fineture, path_model_dir, path_hyper_parameters 15 | # 训练验证数据地址 16 | from keras_textclassification.conf.path_config import path_baidu_qa_2019_train, path_baidu_qa_2019_valid, path_root 17 | 18 | # 数据预处理, 删除文件目录下文件 19 | from keras_textclassification.data_preprocess.text_preprocess import PreprocessText, PreprocessSim, delete_file 20 | 21 | # 模型图 22 | from keras_textclassification.m11_SelfAttention.graph import SelfAttentionGraph as Graph 23 | # 计算时间 24 | import time 25 | 26 | 27 | def train(hyper_parameters=None, rate=1.0): 28 | """ 29 | 训练函数 30 | :param hyper_parameters: json, 超参数 31 | :param rate: 比率, 抽出rate比率语料取训练 32 | :return: None 33 | """ 34 | if not hyper_parameters: 35 | hyper_parameters = { 36 | 'len_max': 1376, # 句子最大长度, 固定 推荐20-50 37 | 'embed_size': 300, # 字/词向量维度 38 | 'vocab_size': 20000, # 这里随便填的,会根据代码里修改 39 | 'trainable': True, # embedding是静态的还是动态的, 即控制可不可以微调 40 | 'level_type': 'char', # 级别, 最小单元, 字/词, 填 'char' or 'word' 41 | 'embedding_type': 'random', # 级别, 嵌入类型, 还可以填'xlnet'、'random'、 'bert'、 'albert' or 'word2vec" 42 | 'gpu_memory_fraction': 0.76, # gpu使用率 43 | 'model': {'label': 23, # 类别数 44 | 'batch_size': 8, # 批处理尺寸, 感觉原则上越大越好,尤其是样本不均衡的时候, batch_size设置影响比较大 45 | 'dropout': 0.5, # 随机失活, 概率 46 | 'decay_step': 1000, # 学习率衰减step, 每N个step衰减一次 47 | 'decay_rate': 0.999, # 学习率衰减系数, 乘法 48 | 'epochs': 20, # 训练最大轮次 49 | 'patience': 3, # 早停,2-3就好 50 | 'lr': 1e-3, # 学习率, 对训练会有比较大的影响, 如果准确率一直上不去,可以考虑调这个参数 51 | 'l2': 1e-6, # l2正则化 52 | 'activate_classify': 'softmax', # 最后一个layer, 即分类激活函数 53 | 'loss': 'categorical_crossentropy', # 损失函数 54 | 'metrics': 'accuracy', # 保存更好模型的评价标准 55 | 'is_training': True, # 训练后者是测试模型 56 | 'model_path': path_model, # 模型地址, loss降低则保存的依据, save_best_only=True, save_weights_only=True 57 | 'path_fineture': path_fineture, # 保存embedding trainable地址, 例如字向量、词向量、bert向量等 58 | 'path_hyper_parameters': path_hyper_parameters, # 模型(包括embedding),超参数地址, 59 | }, 60 | 'embedding': {'layer_indexes': [12], # bert取的层数, 61 | # 'corpus_path': '', # embedding预训练数据地址,不配则会默认取conf里边默认的地址, keras-bert可以加载谷歌版bert,百度版ernie(需转换,https://github.com/ArthurRizar/tensorflow_ernie),哈工大版bert-wwm(tf框架,https://github.com/ymcui/Chinese-BERT-wwm) 62 | }, 63 | 'data': {'train_data': path_baidu_qa_2019_train, # 训练数据 64 | 'val_data': path_baidu_qa_2019_valid # 验证数据 65 | }, 66 | } 67 | 68 | # 删除先前存在的模型\embedding微调模型等 69 | delete_file(path_model_dir) 70 | time_start = time.time() 71 | # graph初始化 72 | graph = Graph(hyper_parameters) 73 | print("graph init ok!") 74 | ra_ed = graph.word_embedding 75 | # 数据预处理 76 | pt = PreprocessSim(path_model_dir) 77 | x_train, y_train = pt.preprocess_label_ques_to_idx(hyper_parameters['embedding_type'], 78 | hyper_parameters['data']['train_data'], 79 | ra_ed, rate=rate, shuffle=True) 80 | x_val, y_val = pt.preprocess_label_ques_to_idx(hyper_parameters['embedding_type'], 81 | hyper_parameters['data']['val_data'], 82 | ra_ed, rate=rate, shuffle=True) 83 | print("data propress ok!") 84 | print(len(y_train)) 85 | # 训练 86 | graph.fit(x_train, y_train, x_val, y_val) 87 | print("耗时:" + str(time.time() - time_start)) 88 | 89 | 90 | if __name__ == "__main__": 91 | train(rate=1) 92 | -------------------------------------------------------------------------------- /keras_textclassification/m12_HAN/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/23 12:02 4 | # @author :Mo 5 | # @function : -------------------------------------------------------------------------------- /keras_textclassification/m12_HAN/__pycache__/__init__.cpython-35.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yongzhuo/Keras-TextClassification/af802f1dc6962cab2c47f93c123f18f169bacf1a/keras_textclassification/m12_HAN/__pycache__/__init__.cpython-35.pyc -------------------------------------------------------------------------------- /keras_textclassification/m12_HAN/__pycache__/graph.cpython-35.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yongzhuo/Keras-TextClassification/af802f1dc6962cab2c47f93c123f18f169bacf1a/keras_textclassification/m12_HAN/__pycache__/graph.cpython-35.pyc -------------------------------------------------------------------------------- /keras_textclassification/m12_HAN/graph.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/3 10:51 4 | # @author :Mo 5 | # @function :Hierarchical Attention Networks for Document Classification(https://www.cs.cmu.edu/~diyiy/docs/naacl16.pdf) 6 | 7 | 8 | from keras.layers import Dense, Dropout, Flatten, Input 9 | from keras.layers import Bidirectional, GRU 10 | from keras import regularizers 11 | from keras.models import Model 12 | import keras.backend as K 13 | 14 | from keras_textclassification.keras_layers.attention_self import AttentionSelf 15 | from keras_textclassification.base.graph import graph 16 | 17 | 18 | class HANGraph(graph): 19 | def __init__(self, hyper_parameters): 20 | """ 21 | 初始化 22 | :param hyper_parameters: json,超参 23 | """ 24 | self.rnn_type = hyper_parameters['model'].get('rnn_type', 'Bidirectional-LSTM') 25 | self.rnn_units = hyper_parameters['model'].get('rnn_units', 256) 26 | self.attention_units = hyper_parameters['model'].get('attention_units', self.rnn_units*2) 27 | self.dropout_spatial = hyper_parameters['model'].get('droupout_spatial', 0.2) 28 | self.len_max_sen = hyper_parameters['model'].get('len_max_sen', 50) 29 | super().__init__(hyper_parameters) 30 | 31 | def create_model(self, hyper_parameters): 32 | """ 33 | 构建神经网络 34 | :param hyper_parameters:json, hyper parameters of network 35 | :return: tensor, moedl 36 | """ 37 | super().create_model(hyper_parameters) 38 | # char or word 39 | x_input_word = self.word_embedding.output 40 | x_word = self.word_level()(x_input_word) 41 | x_word_to_sen = Dropout(self.dropout)(x_word) 42 | 43 | # sentence or doc 44 | x_sen = self.sentence_level()(x_word_to_sen) 45 | x_sen = Dropout(self.dropout)(x_sen) 46 | 47 | x_sen = Flatten()(x_sen) 48 | # 最后就是softmax 49 | dense_layer = Dense(self.label, activation=self.activate_classify)(x_sen) 50 | output = [dense_layer] 51 | self.model = Model(self.word_embedding.input, output) 52 | self.model.summary(132) 53 | 54 | def word_level(self): 55 | x_input_word = Input(shape=(self.len_max, self.embed_size)) 56 | # x = SpatialDropout1D(self.dropout_spatial)(x_input_word) 57 | x = Bidirectional(GRU(units=self.rnn_units, 58 | return_sequences=True, 59 | activation='relu', 60 | kernel_regularizer=regularizers.l2(self.l2), 61 | recurrent_regularizer=regularizers.l2(self.l2)))(x_input_word) 62 | out_sent = AttentionSelf(self.rnn_units*2)(x) 63 | model = Model(x_input_word, out_sent) 64 | return model 65 | 66 | def sentence_level(self): 67 | x_input_sen = Input(shape=(self.len_max, self.rnn_units*2)) 68 | # x = SpatialDropout1D(self.dropout_spatial)(x_input_sen) 69 | output_doc = Bidirectional(GRU(units=self.rnn_units*2, 70 | return_sequences=True, 71 | activation='relu', 72 | kernel_regularizer=regularizers.l2(self.l2), 73 | recurrent_regularizer=regularizers.l2(self.l2)))(x_input_sen) 74 | output_doc_att = AttentionSelf(self.word_embedding.embed_size)(output_doc) 75 | model = Model(x_input_sen, output_doc_att) 76 | return model 77 | 78 | -------------------------------------------------------------------------------- /keras_textclassification/m13_CapsuleNet/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/7/6 18:37 4 | # @author :Mo 5 | # @function : -------------------------------------------------------------------------------- /keras_textclassification/m13_CapsuleNet/train.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/3 10:51 4 | # @author :Mo 5 | # @function :train of fast text with baidu-qa-2019 in question title 6 | 7 | # linux适配 8 | import pathlib 9 | import sys 10 | import os 11 | project_path = str(pathlib.Path(os.path.abspath(__file__)).parent.parent.parent) 12 | sys.path.append(project_path) 13 | # 地址 14 | from keras_textclassification.conf.path_config import path_model, path_fineture, path_model_dir, path_hyper_parameters 15 | # 训练验证数据地址 16 | from keras_textclassification.conf.path_config import path_baidu_qa_2019_train, path_baidu_qa_2019_valid 17 | # 数据预处理, 删除文件目录下文件 18 | from keras_textclassification.data_preprocess.text_preprocess import PreprocessText, delete_file 19 | # 模型图 20 | from keras_textclassification.m13_CapsuleNet.graph import CapsuleNetGraph as Graph 21 | # 计算时间 22 | import time 23 | 24 | 25 | def train(hyper_parameters=None, rate=1.0): 26 | """ 27 | 训练函数 28 | :param hyper_parameters: json, 超参数 29 | :param rate: 比率, 抽出rate比率语料取训练 30 | :return: None 31 | """ 32 | if not hyper_parameters: 33 | hyper_parameters = { 34 | 'len_max': 55, # 句子最大长度, 固定 推荐20-50 35 | 'embed_size': 300, # 字/词向量维度 36 | 'vocab_size': 20000, # 这里随便填的,会根据代码里修改 37 | 'trainable': False, # embedding是静态的还是动态的 38 | 'level_type': 'word', # 级别, 最小单元, 字/词, 填 'char' or 'word' 39 | 'embedding_type': 'word2vec', # 级别, 嵌入类型, 还可以填'xlnet'、'random'、 'bert'、 'albert' or 'word2vec" 40 | 'gpu_memory_fraction': 0.76, # gpu使用率 41 | 'model': {'label': 90, # 类别数 42 | 'batch_size': 256, # 批处理尺寸, 感觉原则上越大越好,尤其是样本不均衡的时候, batch_size设置影响比较大 43 | 'dropout': 0.5, # 随机失活, 概率 44 | 'decay_step': 100, # 学习率衰减step, 每N个step衰减一次 45 | 'decay_rate': 0.9, # 学习率衰减系数, 乘法 46 | 'epochs': 20, # 训练最大轮次 47 | 'patience': 5, # 早停,2-3就好 48 | 'lr': 5e-4, # 学习率, 对训练会有比较大的影响, 如果准确率一直上不去,可以考虑调这个参数 49 | 'l2': 1e-9, # l2正则化 50 | 'activate_classify': 'softmax', # 最后一个layer, 即分类激活函数 51 | 'loss': 'categorical_crossentropy', # 损失函数 52 | 'metrics': 'accuracy', # 保存更好模型的评价标准 53 | 'is_training': True, # 训练后者是测试模型 54 | 'model_path': path_model, # 模型地址, loss降低则保存的依据, save_best_only=True, save_weights_only=True 55 | 'path_fineture': path_fineture, # 保存embedding trainable地址, 例如字向量、词向量、bert向量等 56 | 'path_hyper_parameters': path_hyper_parameters, # 模型(包括embedding),超参数地址, 57 | 'routings': 5, 58 | 'dim_capsule': 16, 59 | 'num_capsule': 16, 60 | 'droupout_spatial': 0.25, 61 | }, 62 | 'embedding': {'layer_indexes': [12], # bert取的层数, 63 | # 'corpus_path': '', # embedding预训练数据地址,不配则会默认取conf里边默认的地址, keras-bert可以加载谷歌版bert,百度版ernie(需转换,https://github.com/ArthurRizar/tensorflow_ernie),哈工大版bert-wwm(tf框架,https://github.com/ymcui/Chinese-BERT-wwm) 64 | }, 65 | 'data': {'train_data': path_baidu_qa_2019_train, # 训练数据 66 | 'val_data': path_baidu_qa_2019_valid # 验证数据 67 | }, 68 | } 69 | 70 | # 删除先前存在的模型\embedding微调模型等 71 | delete_file(path_model_dir) 72 | time_start = time.time() 73 | # graph初始化 74 | graph = Graph(hyper_parameters) 75 | print("graph init ok!") 76 | ra_ed = graph.word_embedding 77 | # 数据预处理 78 | pt = PreprocessText(path_model_dir) 79 | x_train, y_train = pt.preprocess_label_ques_to_idx(hyper_parameters['embedding_type'], 80 | hyper_parameters['data']['train_data'], 81 | ra_ed, rate=rate, shuffle=True) 82 | x_val, y_val = pt.preprocess_label_ques_to_idx(hyper_parameters['embedding_type'], 83 | hyper_parameters['data']['val_data'], 84 | ra_ed, rate=rate, shuffle=True) 85 | print("data propress ok!") 86 | print(len(y_train)) 87 | # 训练 88 | graph.fit(x_train, y_train, x_val, y_val) 89 | print("耗时:" + str(time.time() - time_start)) 90 | 91 | 92 | if __name__ == "__main__": 93 | train(rate=1) 94 | -------------------------------------------------------------------------------- /keras_textclassification/m14_Transformer/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/7/22 9:03 4 | # @author :Mo 5 | # @function : -------------------------------------------------------------------------------- /keras_textclassification/m14_Transformer/graph.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/3 10:51 4 | # @author :Mo 5 | # @function :graph of CapsuleNet 6 | 7 | 8 | from keras.layers import Dropout, Dense, Flatten 9 | from keras.models import Model 10 | import keras 11 | 12 | from keras_textclassification.keras_layers.transformer_utils.triangle_position_embedding import TriglePositiomEmbedding 13 | from keras_textclassification.keras_layers.transformer_utils.embedding import EmbeddingRet 14 | from keras_textclassification.keras_layers.transformer import build_encoders 15 | 16 | from keras_textclassification.keras_layers.non_mask_layer import NonMaskingLayer 17 | 18 | from keras_textclassification.base.graph import graph 19 | 20 | 21 | class TransformerEncodeGraph(graph): 22 | def __init__(self, hyper_parameters): 23 | """ 24 | 初始化 25 | :param hyper_parameters: json,超参 26 | """ 27 | self.encoder_num = hyper_parameters["model"].get('encoder_num', 2) 28 | self.head_num = hyper_parameters["model"].get('head_num', 6) 29 | self.hidden_dim = hyper_parameters["model"].get('hidden_dim', 3072) 30 | self.attention_activation = hyper_parameters["model"].get('attention_activation', 'relu') 31 | self.feed_forward_activation = hyper_parameters["model"].get('feed_forward_activation', 'relu') 32 | self.use_adapter = hyper_parameters["model"].get('use_adapter', False) 33 | self.adapter_units = hyper_parameters["model"].get('adapter_units', 768) 34 | self.adapter_activation = hyper_parameters["model"].get('adapter_activation', 'relu') 35 | super().__init__(hyper_parameters) 36 | 37 | def create_model(self, hyper_parameters): 38 | """ 39 | 构建神经网络 40 | :param hyper_parameters:json, hyper parameters of network 41 | :return: tensor, moedl 42 | """ 43 | super().create_model(hyper_parameters) # 这里的embedding不用,只提取token(即onehot-index) 44 | # embedding = self.word_embedding.output 45 | # embed_layer = SpatialDropout1D(self.dropout)(embedding) 46 | encoder_input = keras.layers.Input(shape=(self.len_max,), name='Encoder-Input') 47 | encoder_embed_layer = EmbeddingRet(input_dim=self.word_embedding.vocab_size, 48 | output_dim=self.word_embedding.embed_size, 49 | mask_zero=False, 50 | weights=None, 51 | trainable=self.trainable, 52 | name='Token-Embedding',) 53 | encoder_embedding = encoder_embed_layer(encoder_input) 54 | encoder_embed = TriglePositiomEmbedding(mode=TriglePositiomEmbedding.MODE_ADD, 55 | name='Encoder-Embedding',)(encoder_embedding[0]) 56 | encoded_layer = build_encoders(encoder_num=self.encoder_num, 57 | input_layer=encoder_embed, 58 | head_num=self.head_num, 59 | hidden_dim=self.hidden_dim, 60 | attention_activation=self.activate_classify, 61 | feed_forward_activation=self.activate_classify, 62 | dropout_rate=self.dropout, 63 | trainable=self.trainable, 64 | use_adapter=self.use_adapter, 65 | adapter_units=self.adapter_units, 66 | adapter_activation=self.adapter_activation, 67 | ) 68 | encoded_layer = NonMaskingLayer()(encoded_layer) 69 | encoded_layer_flat = Flatten()(encoded_layer) 70 | encoded_layer_drop = Dropout(self.dropout)(encoded_layer_flat) 71 | output = Dense(self.label, activation=self.activate_classify)(encoded_layer_drop) 72 | self.model = Model(inputs=encoder_input, outputs=output) 73 | self.model.summary(120) 74 | -------------------------------------------------------------------------------- /keras_textclassification/m14_Transformer/train.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/3 10:51 4 | # @author :Mo 5 | # @function :train of fast text with baidu-qa-2019 in question title 6 | 7 | # linux适配 8 | import pathlib 9 | import sys 10 | import os 11 | project_path = str(pathlib.Path(os.path.abspath(__file__)).parent.parent.parent) 12 | sys.path.append(project_path) 13 | # 地址 14 | from keras_textclassification.conf.path_config import path_model, path_fineture, path_model_dir, path_hyper_parameters 15 | # 训练验证数据地址 16 | from keras_textclassification.conf.path_config import path_baidu_qa_2019_train, path_baidu_qa_2019_valid 17 | # 数据预处理, 删除文件目录下文件 18 | from keras_textclassification.data_preprocess.text_preprocess import PreprocessText, delete_file 19 | # 模型图 20 | from keras_textclassification.m14_Transformer.graph import TransformerEncodeGraph as Graph 21 | # 计算时间 22 | import time 23 | 24 | 25 | def train(hyper_parameters=None, rate=1.0): 26 | """ 27 | 训练函数 28 | :param hyper_parameters: json, 超参数 29 | :param rate: 比率, 抽出rate比率语料取训练 30 | :return: None 31 | """ 32 | if not hyper_parameters: 33 | hyper_parameters = { 34 | 'len_max': 50, # 句子最大长度, 固定 推荐20-50 35 | 'embed_size': 768, # 字/词向量维度 36 | 'vocab_size': 20000, # 这里随便填的,会根据代码里修改 37 | 'trainable': True, # embedding是静态的还是动态的 38 | 'level_type': 'char', # 级别, 最小单元, 字/词, 填 'char' or 'word' 39 | 'embedding_type': 'word2vec', # 级别, 嵌入类型, 还可以填'xlnet'、'random'、 'bert'、 'albert' or 'word2vec" 40 | 'gpu_memory_fraction': 0.66, # gpu使用率 41 | 'model': {'label': 17, # 类别数 42 | 'batch_size': 64, # 批处理尺寸, 感觉原则上越大越好,尤其是样本不均衡的时候, batch_size设置影响比较大 43 | 'dropout': 0.1, # 随机失活, 概率 44 | 'decay_step': 100, # 学习率衰减step, 每N个step衰减一次 45 | 'decay_rate': 0.9, # 学习率衰减系数, 乘法 46 | 'epochs': 50, # 训练最大轮次 47 | 'patience': 5, # 早停,2-3就好 48 | 'lr': 1e-3, # 学习率, 对训练会有比较大的影响, 如果准确率一直上不去,可以考虑调这个参数 49 | 'l2': 1e-9, # l2正则化 50 | 'activate_classify': 'softmax', # 最后一个layer, 即分类激活函数 51 | 'loss': 'categorical_crossentropy', # 损失函数 52 | 'metrics': 'accuracy', # 保存更好模型的评价标准 53 | 'is_training': True, # 训练后者是测试模型 54 | 'model_path': path_model, # 模型地址, loss降低则保存的依据, save_best_only=True, save_weights_only=True 55 | 'path_fineture': path_fineture, # 保存embedding trainable地址, 例如字向量、词向量、bert向量等 56 | 'path_hyper_parameters': path_hyper_parameters, # 模型(包括embedding),超参数地址, 57 | 'droupout_spatial': 0.25, 58 | 'encoder_num': 1, 59 | 'head_num': 12, 60 | 'hidden_dim': 3072, 61 | 'attention_activation': 'relu', 62 | 'feed_forward_activation': 'relu', 63 | 'use_adapter': False, 64 | 'adapter_units': 768, 65 | 'adapter_activation': 'relu', 66 | }, 67 | 'embedding': {'layer_indexes': [12], # bert取的层数, 68 | # 'corpus_path': '', # embedding预训练数据地址,不配则会默认取conf里边默认的地址, keras-bert可以加载谷歌版bert,百度版ernie(需转换,https://github.com/ArthurRizar/tensorflow_ernie),哈工大版bert-wwm(tf框架,https://github.com/ymcui/Chinese-BERT-wwm) 69 | }, 70 | 'data': {'train_data': path_baidu_qa_2019_train, # 训练数据 71 | 'val_data': path_baidu_qa_2019_valid # 验证数据 72 | }, 73 | } 74 | 75 | # 删除先前存在的模型\embedding微调模型等 76 | delete_file(path_model_dir) 77 | time_start = time.time() 78 | # graph初始化 79 | graph = Graph(hyper_parameters) 80 | print("graph init ok!") 81 | ra_ed = graph.word_embedding 82 | # 数据预处理 83 | pt = PreprocessText(path_model_dir) 84 | x_train, y_train = pt.preprocess_label_ques_to_idx(hyper_parameters['embedding_type'], 85 | hyper_parameters['data']['train_data'], 86 | ra_ed, rate=rate, shuffle=True) 87 | x_val, y_val = pt.preprocess_label_ques_to_idx(hyper_parameters['embedding_type'], 88 | hyper_parameters['data']['val_data'], 89 | ra_ed, rate=rate, shuffle=True) 90 | print("data propress ok!") 91 | print(len(y_train)) 92 | # 训练 93 | graph.fit(x_train, y_train, x_val, y_val) 94 | print("耗时:" + str(time.time() - time_start)) 95 | 96 | 97 | if __name__ == "__main__": 98 | train(rate=1) 99 | -------------------------------------------------------------------------------- /keras_textclassification/m15_SWEM/__init__.py: -------------------------------------------------------------------------------- 1 | # !/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # @time : 2019/12/13 11:43 4 | # @author : Mo 5 | # @function: -------------------------------------------------------------------------------- /keras_textclassification/m15_SWEM/graph.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/12/13 10:51 4 | # @author :Mo 5 | # @function :graph of SWEM 6 | # @paper : Baseline Needs More Love: On Simple Word-Embedding-Based Models and Associated Pooling Mechanisms() 7 | 8 | 9 | from keras.layers import GlobalMaxPooling1D, GlobalAveragePooling1D, Concatenate 10 | from keras_textclassification.base.graph import graph 11 | from keras.layers import Dense, Lambda 12 | from keras.models import Model 13 | import tensorflow as tf 14 | 15 | 16 | class SWEMGraph(graph): 17 | def __init__(self, hyper_parameters): 18 | """ 19 | 初始化 20 | :param hyper_parameters: json,超参 21 | """ 22 | self.encode_type = hyper_parameters["model"].get("encode_type", "MAX") # AVG, CONCAT, HIERARCHICAL 23 | self.n_win = hyper_parameters["model"].get("n_win", 3) # n_win=3 24 | super().__init__(hyper_parameters) 25 | 26 | 27 | def create_model(self, hyper_parameters): 28 | """ 29 | 构建神经网络 30 | :param hyper_parameters:json, hyper parameters of network 31 | :return: tensor, moedl 32 | """ 33 | super().create_model(hyper_parameters) 34 | embedding = self.word_embedding.output 35 | 36 | def win_mean(x): 37 | res_list = [] 38 | for i in range(self.len_max-self.n_win+1): 39 | x_mean = tf.reduce_mean(x[:, i:i + self.n_win, :], axis=1) 40 | x_mean_dims = tf.expand_dims(x_mean, axis=-1) 41 | res_list.append(x_mean_dims) 42 | res_list = tf.concat(res_list, axis=-1) 43 | gg = tf.reduce_max(res_list, axis=-1) 44 | return gg 45 | 46 | if self.encode_type=="HIERARCHICAL": 47 | x = Lambda(win_mean, output_shape=(self.embed_size, ))(embedding) 48 | elif self.encode_type=="MAX": 49 | x = GlobalMaxPooling1D()(embedding) 50 | elif self.encode_type=="AVG": 51 | x = GlobalAveragePooling1D()(embedding) 52 | elif self.encode_type == "CONCAT": 53 | x_max = GlobalMaxPooling1D()(embedding) 54 | x_avg = GlobalAveragePooling1D()(embedding) 55 | x = Concatenate()([x_max, x_avg]) 56 | else: 57 | raise RuntimeError("encode_type must be 'MAX', 'AVG', 'CONCAT', 'HIERARCHICAL'") 58 | 59 | output = Dense(self.label, activation=self.activate_classify)(x) 60 | self.model = Model(inputs=self.word_embedding.input, outputs=output) 61 | self.model.summary(132) 62 | 63 | -------------------------------------------------------------------------------- /keras_textclassification/m15_SWEM/predict.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/12/13 10:51 4 | # @author :Mo 5 | # @function :train of fast text with baidu-qa-2019 in question title 6 | 7 | 8 | # 适配linux 9 | import pathlib 10 | import sys 11 | import os 12 | project_path = str(pathlib.Path(os.path.abspath(__file__)).parent.parent.parent) 13 | sys.path.append(project_path) 14 | # 地址 15 | from keras_textclassification.conf.path_config import path_model, path_fineture, path_model_dir, path_hyper_parameters 16 | # 训练验证数据地址 17 | from keras_textclassification.conf.path_config import path_baidu_qa_2019_train, path_baidu_qa_2019_valid 18 | # 数据预处理, 删除文件目录下文件 19 | from keras_textclassification.data_preprocess.text_preprocess import PreprocessText, read_and_process, load_json 20 | # 模型图 21 | from keras_textclassification.m15_SWEM.graph import SWEMGraph as Graph 22 | # 模型评估 23 | from sklearn.metrics import classification_report 24 | # 计算时间 25 | import time 26 | 27 | import numpy as np 28 | 29 | 30 | 31 | 32 | def pred_tet(path_hyper_parameter=path_hyper_parameters, path_test=None, rate=1.0): 33 | """ 34 | 测试集测试与模型评估 35 | :param hyper_parameters: json, 超参数 36 | :param path_test:str, path of test data, 测试集 37 | :param rate: 比率, 抽出rate比率语料取训练 38 | :return: None 39 | """ 40 | hyper_parameters = load_json(path_hyper_parameter) 41 | if path_test: # 从外部引入测试数据地址 42 | hyper_parameters['data']['val_data'] = path_test 43 | time_start = time.time() 44 | # graph初始化 45 | graph = Graph(hyper_parameters) 46 | print("graph init ok!") 47 | graph.load_model() 48 | print("graph load ok!") 49 | ra_ed = graph.word_embedding 50 | # 数据预处理 51 | pt = PreprocessText(path_model_dir) 52 | y, x = read_and_process(hyper_parameters['data']['val_data']) 53 | # 取该数据集的百分之几的语料测试 54 | len_rate = int(len(y) * rate) 55 | x = x[1:len_rate] 56 | y = y[1:len_rate] 57 | y_pred = [] 58 | count = 0 59 | for x_one in x: 60 | count += 1 61 | ques_embed = ra_ed.sentence2idx(x_one) 62 | if hyper_parameters['embedding_type'] in ['bert', 'albert']: # bert数据处理, token 63 | x_val_1 = np.array([ques_embed[0]]) 64 | x_val_2 = np.array([ques_embed[1]]) 65 | x_val = [x_val_1, x_val_2] 66 | else: 67 | x_val = ques_embed 68 | # 预测 69 | pred = graph.predict(x_val) 70 | pre = pt.prereocess_idx(pred[0]) 71 | label_pred = pre[0][0][0] 72 | if count % 1000==0: 73 | print(label_pred) 74 | y_pred.append(label_pred) 75 | 76 | print("data pred ok!") 77 | # 预测结果转为int类型 78 | index_y = [pt.l2i_i2l['l2i'][i] for i in y] 79 | index_pred = [pt.l2i_i2l['l2i'][i] for i in y_pred] 80 | target_names = [pt.l2i_i2l['i2l'][str(i)] for i in list(set((index_pred + index_y)))] 81 | # 评估 82 | report_predict = classification_report(index_y, index_pred, 83 | target_names=target_names, digits=9) 84 | print(report_predict) 85 | print("耗时:" + str(time.time() - time_start)) 86 | 87 | 88 | def pred_input(path_hyper_parameter=path_hyper_parameters): 89 | """ 90 | 输入预测 91 | :param path_hyper_parameter: str, 超参存放地址 92 | :return: None 93 | """ 94 | # 加载超参数 95 | hyper_parameters = load_json(path_hyper_parameter) 96 | pt = PreprocessText(path_model_dir) 97 | # 模式初始化和加载 98 | graph = Graph(hyper_parameters) 99 | graph.load_model() 100 | ra_ed = graph.word_embedding 101 | ques = '我要打王者荣耀' 102 | # str to token 103 | ques_embed = ra_ed.sentence2idx(ques) 104 | if hyper_parameters['embedding_type'] in ['bert', 'albert']: 105 | x_val_1 = np.array([ques_embed[0]]) 106 | x_val_2 = np.array([ques_embed[1]]) 107 | x_val = [x_val_1, x_val_2] 108 | else: 109 | x_val = ques_embed 110 | # 预测 111 | pred = graph.predict(x_val) 112 | # 取id to label and pred 113 | pre = pt.prereocess_idx(pred[0]) 114 | print(pre) 115 | while True: 116 | print("请输入: ") 117 | ques = input() 118 | ques_embed = ra_ed.sentence2idx(ques) 119 | print(ques_embed) 120 | if hyper_parameters['embedding_type'] in ['bert', 'albert']: 121 | x_val_1 = np.array([ques_embed[0]]) 122 | x_val_2 = np.array([ques_embed[1]]) 123 | x_val = [x_val_1, x_val_2] 124 | else: 125 | x_val = ques_embed 126 | pred = graph.predict(x_val) 127 | pre = pt.prereocess_idx(pred[0]) 128 | print(pre) 129 | 130 | 131 | if __name__=="__main__": 132 | # 测试集预测 133 | pred_tet(path_test=path_baidu_qa_2019_valid, rate=1) # sample条件下设为1,否则训练语料可能会很少 134 | 135 | # 可输入 input 预测 136 | pred_input() 137 | 138 | -------------------------------------------------------------------------------- /keras_textclassification/m15_SWEM/train.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/12/13 10:51 4 | # @author :Mo 5 | # @function :train of SWEM with baidu-qa-2019 in question title 6 | 7 | 8 | # 适配linux 9 | import pathlib 10 | import sys 11 | import os 12 | project_path = str(pathlib.Path(os.path.abspath(__file__)).parent.parent.parent) 13 | sys.path.append(project_path) 14 | # os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID' 15 | # os.environ['CUDA_VISIBLE_DEVICES'] = '-1' 16 | # 地址 17 | from keras_textclassification.conf.path_config import path_model, path_fineture, path_model_dir, path_hyper_parameters 18 | # 训练验证数据地址 19 | from keras_textclassification.conf.path_config import path_baidu_qa_2019_train, path_baidu_qa_2019_valid 20 | # 数据预处理, 删除文件目录下文件 21 | from keras_textclassification.data_preprocess.text_preprocess import PreprocessText, delete_file 22 | # 模型图 23 | from keras_textclassification.m15_SWEM.graph import SWEMGraph as Graph 24 | # 计算时间 25 | import time 26 | 27 | 28 | def train(hyper_parameters=None, rate=1.0): 29 | if not hyper_parameters: 30 | hyper_parameters = { 31 | 'len_max': 50, # 句子最大长度, 固定推荐20-50, bert越长会越慢, 占用空间也会变大, 小心OOM 32 | 'embed_size': 150, # 字/词向量维度, bert取768, word取300, char可以更小些 33 | 'vocab_size': 20000, # 这里随便填的,会根据代码里修改 34 | 'trainable': True, # embedding是静态的还是动态的, 即控制可不可以微调 35 | 'level_type': 'char', # 级别, 最小单元, 字/词, 填 'char' or 'word', 注意:word2vec模式下训练语料要首先切好 36 | 'embedding_type': 'random', # 级别, 嵌入类型, 还可以填'xlnet'、'random'、 'bert'、 'albert' or 'word2vec' 37 | # 'gpu_memory_fraction': 0.76, #gpu使用率 38 | 'model': {'label': 17, # 类别数 39 | 'batch_size': 64, # 批处理尺寸, 感觉原则上越大越好,尤其是样本不均衡的时候, batch_size设置影响比较大 40 | 'dropout': 0.5, # 随机失活, 概率 41 | 'decay_step': 1000, # 学习率衰减step, 每N个step衰减一次 42 | 'decay_rate': 0.9, # 学习率衰减系数, 乘法 43 | 'epochs': 20, # 训练最大轮次 44 | 'patience': 3, # 早停,2-3就好 45 | 'lr': 1e-3, # 学习率,bert取5e-5,其他取1e-3, 对训练会有比较大的影响, 如果准确率一直上不去,可以考虑调这个参数 46 | 'l2': 1e-9, # l2正则化 47 | 'activate_classify': 'softmax', # 最后一个layer, 即分类激活函数 48 | 'loss': 'categorical_crossentropy', # 损失函数 49 | 'metrics': 'accuracy', # 保存更好模型的评价标准 50 | 'optimizer_name': 'Adam', # 优化器, 可选['Adam', 'Radam', 'RAdam,Lookahead'], win10下必须使用GPU, 原因未知 51 | 'is_training': True, # 训练后者是测试模型 52 | 'model_path': path_model, 53 | # 模型地址, loss降低则保存的依据, save_best_only=True, save_weights_only=True 54 | 'path_hyper_parameters': path_hyper_parameters, # 模型(包括embedding),超参数地址, 55 | 'path_fineture': path_fineture, # 保存embedding trainable地址, 例如字向量、词向量、bert向量等 56 | # SWEM参数 57 | 'encode_type': 'HIERARCHICAL', # MAX, AVG, CONCAT, HIERARCHICAL 58 | 'n_win': 3 59 | }, 60 | 'embedding': {'layer_indexes': [24], # bert取的层数 61 | }, 62 | 'data':{'train_data': path_baidu_qa_2019_train, # 训练数据 63 | 'val_data': path_baidu_qa_2019_valid # 验证数据 64 | }, 65 | } 66 | 67 | # 删除先前存在的模型\embedding微调模型等 68 | delete_file(path_model_dir) 69 | time_start = time.time() 70 | # graph初始化 71 | graph = Graph(hyper_parameters) 72 | print('graph init ok!') 73 | ra_ed = graph.word_embedding 74 | # 数据预处理 75 | pt = PreprocessText(path_model_dir) 76 | x_train, y_train = pt.preprocess_label_ques_to_idx(hyper_parameters['embedding_type'], 77 | hyper_parameters['data']['train_data'], 78 | ra_ed, rate=rate, shuffle=True) 79 | x_val, y_val = pt.preprocess_label_ques_to_idx(hyper_parameters['embedding_type'], 80 | hyper_parameters['data']['val_data'], 81 | ra_ed, rate=rate, shuffle=True) 82 | print('data propress ok!') 83 | print(len(y_train)) 84 | # 训练 85 | graph.fit(x_train, y_train, x_val, y_val) 86 | print('耗时:' + str(time.time()-time_start)) 87 | 88 | 89 | if __name__=='__main__': 90 | train(rate=1) 91 | 92 | 93 | -------------------------------------------------------------------------------- /keras_textclassification/m16_LEAM/__init__.py: -------------------------------------------------------------------------------- 1 | # !/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # @time : 2019/12/13 19:36 4 | # @author : Mo 5 | # @function: -------------------------------------------------------------------------------- /keras_textclassification/m16_LEAM/graph.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2020/4/1 19:51 4 | # @author :Mo 5 | # @function :graph of LEAM 6 | # @paper :Joint Embedding of Words and Labels for Text Classification(https://arxiv.org/abs/1805.04174) 7 | 8 | 9 | from keras_textclassification.base.graph import graph 10 | from keras.layers import Dense, Dropout, Concatenate 11 | from keras.models import Model 12 | 13 | from keras_textclassification.keras_layers.attention_dot import AttentionDot, CVG_Layer 14 | from keras_textclassification.keras_layers.attention_self import AttentionSelf 15 | 16 | 17 | class LEAMGraph(graph): 18 | def __init__(self, hyper_parameters): 19 | """ 20 | 初始化 21 | :param hyper_parameters: json,超参 22 | """ 23 | super().__init__(hyper_parameters) 24 | 25 | 26 | def create_model(self, hyper_parameters): 27 | """ 28 | 构建神经网络 29 | :param hyper_parameters:json, hyper parameters of network 30 | :return: tensor, moedl 31 | """ 32 | super().create_model(hyper_parameters) 33 | # 构建网络层 sentence 34 | # self.word_embedding_attention = AttentionSelf(self.embed_size)(self.word_embedding.output) 35 | self.word_embedding_attention = AttentionDot()(self.word_embedding.output) 36 | 37 | # 1.C*V/G; 2.relu(text-cnn); 3.softmax; 4.β * V 38 | pools = [] 39 | for filter in self.filters: 40 | x_cvg = CVG_Layer(self.embed_size, filter, self.label)(self.word_embedding_attention) 41 | pools.append(x_cvg) 42 | pools_concat = Concatenate()(pools) 43 | # MLP 44 | x_cvg_dense = Dense(int(self.embed_size/2), activation="relu")(pools_concat) 45 | x = Dropout(self.dropout)(x_cvg_dense) 46 | output = Dense(self.label, activation=self.activate_classify)(x) 47 | 48 | self.model = Model(inputs=self.word_embedding.input, outputs=output) 49 | self.model.summary(132) 50 | -------------------------------------------------------------------------------- /keras_textclassification/m16_LEAM/predict.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2020/4/1 19:51 4 | # @author :Mo 5 | # @function :predict of LEAM with baidu-qa-2019 in question title 6 | 7 | 8 | # 适配linux 9 | import pathlib 10 | import sys 11 | import os 12 | project_path = str(pathlib.Path(os.path.abspath(__file__)).parent.parent.parent) 13 | sys.path.append(project_path) 14 | # 地址 15 | from keras_textclassification.conf.path_config import path_model, path_fineture, path_model_dir, path_hyper_parameters 16 | # 训练验证数据地址 17 | from keras_textclassification.conf.path_config import path_baidu_qa_2019_train, path_baidu_qa_2019_valid 18 | # 数据预处理, 删除文件目录下文件 19 | from keras_textclassification.data_preprocess.text_preprocess import PreprocessText, read_and_process, load_json 20 | # 模型图 21 | from keras_textclassification.m16_LEAM.graph import LEAMGraph as Graph 22 | # 模型评估 23 | from sklearn.metrics import classification_report 24 | # 计算时间 25 | import time 26 | 27 | import numpy as np 28 | 29 | 30 | def pred_tet(path_hyper_parameter=path_hyper_parameters, path_test=None, rate=1.0): 31 | """ 32 | 测试集测试与模型评估 33 | :param hyper_parameters: json, 超参数 34 | :param path_test:str, path of test data, 测试集 35 | :param rate: 比率, 抽出rate比率语料取训练 36 | :return: None 37 | """ 38 | hyper_parameters = load_json(path_hyper_parameter) 39 | if path_test: # 从外部引入测试数据地址 40 | hyper_parameters['data']['val_data'] = path_test 41 | time_start = time.time() 42 | # graph初始化 43 | graph = Graph(hyper_parameters) 44 | print("graph init ok!") 45 | graph.load_model() 46 | print("graph load ok!") 47 | ra_ed = graph.word_embedding 48 | # 数据预处理 49 | pt = PreprocessText(path_model_dir) 50 | y, x = read_and_process(hyper_parameters['data']['val_data']) 51 | # 取该数据集的百分之几的语料测试 52 | len_rate = int(len(y) * rate) 53 | x = x[1:len_rate] 54 | y = y[1:len_rate] 55 | y_pred = [] 56 | count = 0 57 | for x_one in x: 58 | count += 1 59 | ques_embed = ra_ed.sentence2idx(x_one) 60 | if hyper_parameters['embedding_type'] in ['bert', 'albert']: # bert数据处理, token 61 | x_val_1 = np.array([ques_embed[0]]) 62 | x_val_2 = np.array([ques_embed[1]]) 63 | x_val = [x_val_1, x_val_2] 64 | else: 65 | x_val = ques_embed 66 | # 预测 67 | pred = graph.predict(x_val) 68 | pre = pt.prereocess_idx(pred[0]) 69 | label_pred = pre[0][0][0] 70 | if count % 1000==0: 71 | print(label_pred) 72 | y_pred.append(label_pred) 73 | 74 | print("data pred ok!") 75 | # 预测结果转为int类型 76 | index_y = [pt.l2i_i2l['l2i'][i] for i in y] 77 | index_pred = [pt.l2i_i2l['l2i'][i] for i in y_pred] 78 | target_names = [pt.l2i_i2l['i2l'][str(i)] for i in list(set((index_pred + index_y)))] 79 | # 评估 80 | report_predict = classification_report(index_y, index_pred, 81 | target_names=target_names, digits=9) 82 | print(report_predict) 83 | print("耗时:" + str(time.time() - time_start)) 84 | 85 | 86 | def pred_input(path_hyper_parameter=path_hyper_parameters): 87 | """ 88 | 输入预测 89 | :param path_hyper_parameter: str, 超参存放地址 90 | :return: None 91 | """ 92 | # 加载超参数 93 | hyper_parameters = load_json(path_hyper_parameter) 94 | pt = PreprocessText(path_model_dir) 95 | # 模式初始化和加载 96 | graph = Graph(hyper_parameters) 97 | graph.load_model() 98 | ra_ed = graph.word_embedding 99 | ques = '我要打王者荣耀' 100 | # str to token 101 | ques_embed = ra_ed.sentence2idx(ques) 102 | if hyper_parameters['embedding_type'] in ['bert', 'albert']: 103 | x_val_1 = np.array([ques_embed[0]]) 104 | x_val_2 = np.array([ques_embed[1]]) 105 | x_val = [x_val_1, x_val_2] 106 | else: 107 | x_val = ques_embed 108 | # 预测 109 | pred = graph.predict(x_val) 110 | # 取id to label and pred 111 | pre = pt.prereocess_idx(pred[0]) 112 | print(pre) 113 | while True: 114 | print("请输入: ") 115 | ques = input() 116 | ques_embed = ra_ed.sentence2idx(ques) 117 | print(ques_embed) 118 | if hyper_parameters['embedding_type'] in ['bert', 'albert']: 119 | x_val_1 = np.array([ques_embed[0]]) 120 | x_val_2 = np.array([ques_embed[1]]) 121 | x_val = [x_val_1, x_val_2] 122 | else: 123 | x_val = ques_embed 124 | pred = graph.predict(x_val) 125 | pre = pt.prereocess_idx(pred[0]) 126 | print(pre) 127 | 128 | 129 | if __name__=="__main__": 130 | # 测试集预测 131 | pred_tet(path_test=path_baidu_qa_2019_valid, rate=1) # sample条件下设为1,否则训练语料可能会很少 132 | 133 | # 可输入 input 预测 134 | pred_input() 135 | 136 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | gensim==3.7.1 2 | jieba==0.39 3 | numpy==1.16.2 4 | pandas==0.23.4 5 | scikit-learn==0.19.1 6 | tflearn==0.3.2 7 | tqdm==4.31.1 8 | passlib==1.7.1 9 | keras==2.2.4 10 | keras-bert==0.41.0 11 | keras-xlnet==0.16.0 12 | keras-adaptive-softmax==0.6.0 13 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/13 10:17 4 | # @author :Mo 5 | # @function :setup of Keras-TextClassification 6 | # @codes :copy reference from https://github.com/TianWenQAQ/Kashgari/blob/master/setup.py 7 | 8 | 9 | from setuptools import find_packages, setup 10 | import pathlib 11 | import codecs 12 | 13 | 14 | # Package meta-data. 15 | NAME = 'Keras-TextClassification' 16 | DESCRIPTION = 'chinese text classification of keras' 17 | URL = 'https://github.com/yongzhuo/Keras-TextClassification' 18 | EMAIL = '1903865025@qq.com' 19 | AUTHOR = 'yongzhuo' 20 | LICENSE = 'MIT' 21 | 22 | with codecs.open('README.md', 'r', 'utf8') as reader: 23 | long_description = reader.read() 24 | with codecs.open('requirements.txt', 'r', 'utf8') as reader: 25 | install_requires = list(map(lambda x: x.strip(), reader.readlines())) 26 | 27 | setup(name=NAME, 28 | version='0.1.7', 29 | description=DESCRIPTION, 30 | long_description=long_description, 31 | long_description_content_type="text/markdown", 32 | author=AUTHOR, 33 | author_email=EMAIL, 34 | url=URL, 35 | packages=find_packages(exclude=('test')), 36 | install_requires=install_requires, 37 | include_package_data=True, 38 | license=LICENSE, 39 | classifiers=['License :: OSI Approved :: MIT License', 40 | 'Programming Language :: Python :: 3.4', 41 | 'Programming Language :: Python :: 3.5', 42 | 'Programming Language :: Python :: 3.6', 43 | 'Programming Language :: Python :: 3.7', 44 | 'Programming Language :: Python :: 3.8', 45 | 'Programming Language :: Python :: Implementation :: CPython', 46 | 'Programming Language :: Python :: Implementation :: PyPy'],) 47 | 48 | 49 | if __name__ == "__main__": 50 | print("setup ok!") 51 | 52 | # 说明,tensorflow>=1.12.0 or tensorflow-gpu>=1.12.0 53 | # 项目工程目录这里Keras-TextClassification,实际上,下边还要有一层keras_textclassification,也就是说,keras_textclassification和setup同一层 54 | # data包里必须要有__init__.py,否则文件不会生成, .py文件才能copy 55 | 56 | # step: 57 | # 打开cmd 58 | # 到达安装目录 59 | # python setup.py build 60 | # python setup.py install 61 | 62 | # or 63 | 64 | # python setup.py bdist_wheel --universal 65 | # twine upload dist/* 66 | -------------------------------------------------------------------------------- /test/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/11 22:54 4 | # @author :Mo 5 | # @function : -------------------------------------------------------------------------------- /test/fit_generator/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/11/02 15:35 4 | # @author :Mo 5 | # @function : -------------------------------------------------------------------------------- /test/fit_generator/tet_fit_data_generator.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/10/28 15:36 4 | # @author :Mo 5 | # @function :test bert fit_data_generator, deal with bigdata 6 | 7 | 8 | # 适配linux 9 | import pathlib 10 | import sys 11 | import os 12 | 13 | project_path = str(pathlib.Path(os.path.abspath(__file__)).parent.parent.parent) 14 | sys.path.append(project_path) 15 | # 地址 16 | from keras_textclassification.conf.path_config import path_model, path_fineture, path_model_dir, path_hyper_parameters 17 | # 训练验证数据地址 18 | from keras_textclassification.conf.path_config import path_baidu_qa_2019_train, path_baidu_qa_2019_valid 19 | # 数据预处理, 删除文件目录下文件 20 | from keras_textclassification.data_preprocess.text_preprocess import delete_file 21 | # 模型图 22 | from keras_textclassification.m00_Bert.graph import BertGraph as Graph 23 | # 计算时间 24 | import time 25 | 26 | 27 | def train(hyper_parameters=None, rate=1.0): 28 | """ 29 | 训练函数 30 | :param hyper_parameters: json, 超参数 31 | :param rate: 比率, 抽出rate比率语料取训练 32 | :return: None 33 | """ 34 | if not hyper_parameters: 35 | hyper_parameters = { 36 | 'len_max': 20, # 句子最大长度, 固定 推荐20-50 37 | 'embed_size': 768, # 字/词向量维度 38 | 'vocab_size': 20000, # 这里随便填的,会根据代码里修改 39 | 'trainable': True, # embedding是静态的还是动态的, 即控制可不可以微调 40 | 'level_type': 'char', # 级别, 最小单元, 字/词, 填 'char' or 'word' 41 | 'embedding_type': 'albert', # 级别, 嵌入类型, 还可以填'xlnet'、'random'、 'bert'、 'albert' or 'word2vec" 42 | 'gpu_memory_fraction': 0.76, # gpu使用率 43 | 'model': {'label': 17, # 类别数 44 | 'batch_size': 2, # 批处理尺寸, 感觉原则上越大越好,尤其是样本不均衡的时候, batch_size设置影响比较大 45 | 'filters': [2, 3, 4, 5], # 卷积核尺寸 46 | 'filters_num': 300, # 卷积个数 text-cnn:300-600 47 | 'channel_size': 1, # CNN通道数 48 | 'dropout': 0.5, # 随机失活, 概率 49 | 'decay_step': 100, # 学习率衰减step, 每N个step衰减一次 50 | 'decay_rate': 0.9, # 学习率衰减系数, 乘法 51 | 'epochs': 20, # 训练最大轮次 52 | 'patience': 3, # 早停,2-3就好 53 | 'lr': 5e-5, # 学习率, 对训练会有比较大的影响, 如果准确率一直上不去,可以考虑调这个参数 54 | 'l2': 1e-9, # l2正则化 55 | 'activate_classify': 'softmax', # 最后一个layer, 即分类激活函数 56 | 'loss': 'categorical_crossentropy', # 损失函数 57 | 'metrics': 'accuracy', # 保存更好模型的评价标准 58 | 'is_training': True, # 训练后者是测试模型 59 | 'model_path': path_model, 60 | # 模型地址, loss降低则保存的依据, save_best_only=True, save_weights_only=True 61 | 'path_hyper_parameters': path_hyper_parameters, # 模型(包括embedding),超参数地址, 62 | 'path_fineture': path_fineture, # 保存embedding trainable地址, 例如字向量、词向量、bert向量等 63 | }, 64 | 'embedding': {'layer_indexes': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], # bert取的层数,包括embedding层 65 | # 'corpus_path': '', # embedding预训练数据地址,不配则会默认取conf里边默认的地址, keras-bert可以加载谷歌版bert,百度版ernie(需转换,https://github.com/ArthurRizar/tensorflow_ernie),哈工大版bert-wwm(tf框架,https://github.com/ymcui/Chinese-BERT-wwm) 66 | }, 67 | 'data': {'train_data': path_baidu_qa_2019_train, # 训练数据 68 | 'val_data': path_baidu_qa_2019_valid # 验证数据 69 | }, 70 | } 71 | 72 | # 删除先前存在的模型和embedding微调模型等 73 | delete_file(path_model_dir) 74 | time_start = time.time() 75 | # graph初始化 76 | graph = Graph(hyper_parameters) 77 | print("graph init ok!") 78 | ra_ed = graph.word_embedding 79 | 80 | # 训练 81 | graph.fit_generator(embed=ra_ed, rate=rate) 82 | print("耗时:" + str(time.time() - time_start)) 83 | 84 | 85 | if __name__ == "__main__": 86 | train(rate=1) 87 | -------------------------------------------------------------------------------- /test/fit_generator/tet_fit_data_generator_textcnn.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/11/03 10:51 4 | # @author :Mo 5 | # @function :test textcnn fit_data_generator, deal with bigdata 6 | 7 | 8 | # 适配linux 9 | import pathlib 10 | import sys 11 | import os 12 | project_path = str(pathlib.Path(os.path.abspath(__file__)).parent.parent.parent) 13 | sys.path.append(project_path) 14 | # 地址 15 | from keras_textclassification.conf.path_config import path_model, path_fineture, path_model_dir, path_hyper_parameters 16 | # 训练验证数据地址 17 | from keras_textclassification.conf.path_config import path_baidu_qa_2019_train, path_baidu_qa_2019_valid 18 | # 数据预处理, 删除文件目录下文件 19 | from keras_textclassification.data_preprocess.text_preprocess import delete_file 20 | # 模型图 21 | from keras_textclassification.m02_TextCNN.graph import TextCNNGraph as Graph 22 | # 计算时间 23 | import time 24 | 25 | 26 | def train(hyper_parameters=None, rate=1.0): 27 | if not hyper_parameters: 28 | hyper_parameters = { 29 | 'len_max': 50, # 句子最大长度, 固定推荐20-50, bert越长会越慢, 占用空间也会变大, 本地win10-4G设为20就好, 过大小心OOM 30 | 'embed_size': 300, # 字/词向量维度, bert取768, word取300, char可以更小些 31 | 'vocab_size': 20000, # 这里随便填的,会根据代码里修改 32 | 'trainable': True, # embedding是静态的还是动态的, 即控制可不可以微调 33 | 'level_type': 'char', # 级别, 最小单元, 字/词, 填 'char' or 'word', 注意:word2vec模式下训练语料要首先切好 34 | 'embedding_type': 'random', # 级别, 嵌入类型, 还可以填'xlnet'、'random'、 'bert'、 'albert' or 'word2vec" 35 | 'gpu_memory_fraction': 0.76, #gpu使用率 36 | 'model': {'label': 17, # 类别数 37 | 'batch_size': 2, # 批处理尺寸, 感觉原则上越大越好,尤其是样本不均衡的时候, batch_size设置影响比较大 38 | 'dropout': 0.5, # 随机失活, 概率 39 | 'decay_step': 100, # 学习率衰减step, 每N个step衰减一次 40 | 'decay_rate': 0.9, # 学习率衰减系数, 乘法 41 | 'epochs': 20, # 训练最大轮次 42 | 'patience': 3, # 早停,2-3就好 43 | 'lr': 1e-3, # 学习率,bert取5e-5,其他取1e-3, 对训练会有比较大的影响, 如果准确率一直上不去,可以考虑调这个参数 44 | 'l2': 1e-9, # l2正则化 45 | 'activate_classify': 'softmax', # 最后一个layer, 即分类激活函数 46 | 'loss': 'categorical_crossentropy', # 损失函数 47 | 'metrics': 'accuracy', # 保存更好模型的评价标准 48 | 'is_training': True, # 训练后者是测试模型 49 | 'model_path': path_model, 50 | # 模型地址, loss降低则保存的依据, save_best_only=True, save_weights_only=True 51 | 'path_hyper_parameters': path_hyper_parameters, # 模型(包括embedding),超参数地址, 52 | 'path_fineture': path_fineture, # 保存embedding trainable地址, 例如字向量、词向量、bert向量等 53 | }, 54 | 'embedding': {'layer_indexes': [1, 2, 3, 12, 13], # bert取的层数,1为embedding层,未处理 55 | # 'corpus_path': 'Y:/BaiduNetdiskDownload/DataSet/bert-model/chinese_bert_chinese_wwm_L-12_H-768_A-12', # embedding预训练数据地址,不配则会默认取conf里边默认的地址 56 | # 'corpus_path':'Y:/BaiduNetdiskDownload/DataSet/bert-model/baidu_ernie', 57 | # keras - bert可以加载谷歌版bert, 百度版ernie(需转换,https: // github.com / ArthurRizar / tensorflow_ernie), 哈工大版bert - wwm(tf框架,https: // github.com / ymcui / Chinese - BERT - wwm) 58 | }, 59 | 'data':{'train_data': path_baidu_qa_2019_train, # 训练数据 60 | 'val_data': path_baidu_qa_2019_valid # 验证数据 61 | }, 62 | } 63 | 64 | # 删除先前存在的模型和embedding微调模型等 65 | delete_file(path_model_dir) 66 | time_start = time.time() 67 | # graph初始化 68 | graph = Graph(hyper_parameters) 69 | print("graph init ok!") 70 | ra_ed = graph.word_embedding 71 | 72 | # 训练 73 | graph.fit_generator(embed=ra_ed, rate=rate) 74 | print("耗时:" + str(time.time() - time_start)) 75 | 76 | 77 | if __name__=="__main__": 78 | train(rate=1) 79 | -------------------------------------------------------------------------------- /test/flask/__init__.py: -------------------------------------------------------------------------------- 1 | # !/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # @time : 2020/11/13 16:58 4 | # @author : Mo 5 | # @function: -------------------------------------------------------------------------------- /test/flask/model_flask.py: -------------------------------------------------------------------------------- 1 | # !/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # @time : 2020/11/13 20:58 4 | # @author : Mo 5 | # @function: flask of model 6 | 7 | 8 | # 适配linux 9 | import pathlib 10 | import sys 11 | import os 12 | project_path = str(pathlib.Path(os.path.abspath(__file__)).parent.parent.parent) 13 | sys.path.append(project_path) 14 | # 地址 15 | from keras_textclassification.conf.path_config import path_model, path_fineture, path_model_dir, path_hyper_parameters 16 | # 训练验证数据地址 17 | from keras_textclassification.conf.path_config import path_baidu_qa_2019_train, path_baidu_qa_2019_valid 18 | # 数据预处理, 删除文件目录下文件 19 | from keras_textclassification.data_preprocess.text_preprocess import PreprocessText, read_and_process, load_json 20 | # 模型图 21 | from keras_textclassification.m02_TextCNN.graph import TextCNNGraph as Graph 22 | import numpy as np 23 | # flask 24 | from flask import Flask, request, jsonify 25 | app = Flask(__name__) 26 | 27 | 28 | hyper_parameters = load_json(path_hyper_parameters) 29 | pt = PreprocessText(path_model_dir) 30 | # 模式初始化和加载 31 | graph = Graph(hyper_parameters) 32 | graph.load_model() 33 | ra_ed = graph.word_embedding 34 | ques = '我要打王者荣耀' 35 | # str to token 36 | ques_embed = ra_ed.sentence2idx(ques) 37 | if hyper_parameters['embedding_type'] in ['bert', 'albert']: 38 | x_val_1 = np.array([ques_embed[0]]) 39 | x_val_2 = np.array([ques_embed[1]]) 40 | x_val = [x_val_1, x_val_2] 41 | else: 42 | x_val = ques_embed 43 | # 预测 44 | pred = graph.predict(x_val) 45 | # 取id to label and pred 46 | pre = pt.prereocess_idx(pred[0]) 47 | 48 | 49 | @app.route("/nlp/textcnn/predict", methods=["GET","POST"]) 50 | def predict(): 51 | ques = request.args.get("text", "") 52 | ques_embed = ra_ed.sentence2idx(ques) 53 | if hyper_parameters['embedding_type'] in ['bert', 'albert']: 54 | x_val_1 = np.array([ques_embed[0]]) 55 | x_val_2 = np.array([ques_embed[1]]) 56 | x_val = [x_val_1, x_val_2] 57 | else: 58 | x_val = ques_embed 59 | pred = graph.predict(x_val) 60 | pre = pt.prereocess_idx(pred[0]) 61 | pres_json = [dict(p) for p in pre] 62 | return jsonify(content_type="application/json;charset=utf-8", 63 | reason="success", 64 | charset="utf-8", 65 | status="200", 66 | content=pres_json) 67 | 68 | 69 | if __name__ == "__main__": 70 | app.run(host="0.0.0.0", 71 | threaded=True, 72 | debug=True, 73 | port=8081) 74 | 75 | 76 | # http://localhost:8081/nlp/textcnn/predict?text=你是谁 77 | 78 | 79 | 80 | -------------------------------------------------------------------------------- /test/multi_label_class/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/8/14 21:23 4 | # @author :Mo 5 | # @function : -------------------------------------------------------------------------------- /test/multi_label_class/predict_multi.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/8/14 17:40 4 | # @author :Mo 5 | # @function : 6 | 7 | 8 | # 适配linux 9 | import pathlib 10 | import sys 11 | import os 12 | project_path = str(pathlib.Path(os.path.abspath(__file__)).parent.parent.parent) 13 | sys.path.append(project_path) 14 | # 地址 15 | from keras_textclassification.conf.path_config import path_model, path_fineture, path_model_dir, path_hyper_parameters 16 | # 训练验证数据地址 17 | from keras_textclassification.conf.path_config import path_byte_multi_news_valid, path_byte_multi_news_train 18 | # 数据预处理, 删除文件目录下文件 19 | from keras_textclassification.data_preprocess.text_preprocess import PreprocessTextMulti, read_and_process, load_json 20 | # 模型图 21 | from keras_textclassification.m02_TextCNN.graph import TextCNNGraph as Graph 22 | # 模型评估 23 | from sklearn.metrics import classification_report 24 | # 计算时间 25 | import time 26 | 27 | import numpy as np 28 | 29 | 30 | def pred_input(path_hyper_parameter=path_hyper_parameters): 31 | # 输入预测 32 | # 加载超参数 33 | hyper_parameters = load_json(path_hyper_parameter) 34 | pt = PreprocessTextMulti(path_model_dir) 35 | # 模式初始化和加载 36 | graph = Graph(hyper_parameters) 37 | graph.load_model() 38 | ra_ed = graph.word_embedding 39 | ques = '我要打王者荣耀' 40 | # str to token 41 | ques_embed = ra_ed.sentence2idx(ques) 42 | if hyper_parameters['embedding_type'] in ['bert', 'albert']: 43 | x_val_1 = np.array([ques_embed[0]]) 44 | x_val_2 = np.array([ques_embed[1]]) 45 | x_val = [x_val_1, x_val_2] 46 | else: 47 | x_val = ques_embed 48 | # 预测 49 | pred = graph.predict(x_val) 50 | print(pred) 51 | # 取id to label and pred 52 | pre = pt.prereocess_idx(pred[0]) 53 | ls_nulti = [] 54 | for ls in pre[0]: 55 | if ls[1] >= 0.5: 56 | ls_nulti.append(ls) 57 | print(pre[0]) 58 | print(ls_nulti) 59 | while True: 60 | print("请输入: ") 61 | ques = input() 62 | ques_embed = ra_ed.sentence2idx(ques) 63 | print(ques_embed) 64 | if hyper_parameters['embedding_type'] in ['bert', 'albert']: 65 | x_val_1 = np.array([ques_embed[0]]) 66 | x_val_2 = np.array([ques_embed[1]]) 67 | x_val = [x_val_1, x_val_2] 68 | else: 69 | x_val = ques_embed 70 | pred = graph.predict(x_val) 71 | pre = pt.prereocess_idx(pred[0]) 72 | ls_nulti = [] 73 | for ls in pre[0]: 74 | if ls[1] >= 0.5: 75 | ls_nulti.append(ls) 76 | print(pre[0]) 77 | print(ls_nulti) 78 | 79 | if __name__=="__main__": 80 | # 测试集预测 81 | # pred_tet(path_test=path_byte_multi_news_valid, rate=1) # sample条件下设为1,否则训练语料可能会很少 82 | 83 | # 可输入 input 预测 84 | pred_input() 85 | -------------------------------------------------------------------------------- /test/multi_label_class/train_multi.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/8/14 16:14 4 | # @author :Mo 5 | # @function : 6 | 7 | 8 | # 适配linux 9 | import pathlib 10 | import sys 11 | import os 12 | project_path = str(pathlib.Path(os.path.abspath(__file__)).parent.parent.parent) 13 | sys.path.append(project_path) 14 | # 地址 15 | from keras_textclassification.conf.path_config import path_model, path_fineture, path_model_dir, path_hyper_parameters 16 | # 训练验证数据地址 17 | from keras_textclassification.conf.path_config import path_byte_multi_news_train, path_byte_multi_news_valid 18 | # 数据预处理, 删除文件目录下文件 19 | from keras_textclassification.data_preprocess.text_preprocess import PreprocessTextMulti, delete_file 20 | # 模型图 21 | from keras_textclassification.m02_TextCNN.graph import TextCNNGraph as Graph 22 | # 计算时间 23 | import time 24 | # from keras.metrics import top_k_categorical_accuracy 25 | 26 | def train(hyper_parameters=None, rate=1.0): 27 | if not hyper_parameters: 28 | hyper_parameters = { 29 | 'len_max': 50, # 句子最大长度, 固定推荐20-50, bert越长会越慢, 占用空间也会变大, 本地win10-4G设为20就好, 过大小心OOM 30 | 'embed_size': 300, # 字/词向量维度, bert取768, word取300, char可以更小些 31 | 'vocab_size': 20000, # 这里随便填的,会根据代码里修改 32 | 'trainable': True, # embedding是静态的还是动态的, 即控制可不可以微调 33 | 'level_type': 'char', # 级别, 最小单元, 字/词, 填 'char' or 'word', 注意:word2vec模式下训练语料要首先切好 34 | 'embedding_type': 'random', # 级别, 嵌入类型, 还可以填'xlnet'、'random'、 'bert'、 'albert' or 'word2vec" 35 | 'gpu_memory_fraction': 0.66, #gpu使用率 36 | 'model': {'label': 1070, # 类别数 37 | 'batch_size': 32, # 批处理尺寸, 感觉原则上越大越好,尤其是样本不均衡的时候, batch_size设置影响比较大 38 | 'dropout': 0.5, # 随机失活, 概率 39 | 'decay_step': 100, # 学习率衰减step, 每N个step衰减一次 40 | 'decay_rate': 0.9, # 学习率衰减系数, 乘法 41 | 'epochs': 20, # 训练最大轮次 42 | 'patience': 3, # 早停,2-3就好 43 | 'lr': 1e-3, # 学习率, bert取5e-5, 其他取1e-3, 对训练会有比较大的影响, 如果准确率一直上不去,可以考虑调这个参数 44 | 'l2': 1e-9, # l2正则化 45 | 'activate_classify': 'sigmoid', # 'sigmoid', # 最后一个layer, 即分类激活函数 46 | 'loss': 'binary_crossentropy', # 损失函数, 可能有问题, 可以自己定义 47 | 'metrics': 'top_k_categorical_accuracy', # 1070个类, 太多了先用topk, 这里数据k设置为最大:33 48 | # 'metrics': 'categorical_accuracy', # 保存更好模型的评价标准 49 | 'is_training': True, # 训练后者是测试模型 50 | 'model_path': path_model, 51 | # 模型地址, loss降低则保存的依据, save_best_only=True, save_weights_only=True 52 | 'path_hyper_parameters': path_hyper_parameters, # 模型(包括embedding),超参数地址, 53 | 'path_fineture': path_fineture, # 保存embedding trainable地址, 例如字向量、词向量、bert向量等 54 | }, 55 | 'embedding': {'layer_indexes': [13], # bert取的层数 56 | # 'corpus_path': '', # embedding预训练数据地址,不配则会默认取conf里边默认的地址, keras-bert可以加载谷歌版bert,百度版ernie(需转换,https://github.com/ArthurRizar/tensorflow_ernie),哈工大版bert-wwm(tf框架,https://github.com/ymcui/Chinese-BERT-wwm) 57 | }, 58 | 'data':{'train_data': path_byte_multi_news_train, # 训练数据 59 | 'val_data': path_byte_multi_news_valid, # 验证数据 60 | }, 61 | } 62 | 63 | 64 | # 删除先前存在的模型和embedding微调模型等 65 | delete_file(path_model_dir) 66 | time_start = time.time() 67 | # graph初始化 68 | graph = Graph(hyper_parameters) 69 | print("graph init ok!") 70 | ra_ed = graph.word_embedding 71 | # 数据预处理 72 | pt = PreprocessTextMulti(path_model_dir) 73 | x_train, y_train = pt.preprocess_label_ques_to_idx(hyper_parameters['embedding_type'], 74 | hyper_parameters['data']['train_data'], 75 | ra_ed, rate=rate, shuffle=True) 76 | print('train data propress ok!') 77 | x_val, y_val = pt.preprocess_label_ques_to_idx(hyper_parameters['embedding_type'], 78 | hyper_parameters['data']['val_data'], 79 | ra_ed, rate=rate, shuffle=True) 80 | print("data propress ok!") 81 | print(len(y_train)) 82 | # 训练 83 | graph.fit(x_train, y_train, x_val, y_val) 84 | print("耗时:" + str(time.time()-time_start)) 85 | 86 | 87 | if __name__=="__main__": 88 | train(rate=1) 89 | -------------------------------------------------------------------------------- /test/predict_bert_text_cnn.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/3 10:51 4 | # @author :Mo 5 | # @function :pred of text-cnn with baidu-qa-2019 in question title 6 | 7 | 8 | # 适配linux 9 | import pathlib 10 | import sys 11 | import os 12 | project_path = str(pathlib.Path(os.path.abspath(__file__)).parent.parent.parent) 13 | sys.path.append(project_path) 14 | # 地址 15 | from keras_textclassification.conf.path_config import path_model, path_fineture, path_model_dir, path_hyper_parameters 16 | # 训练验证数据地址 17 | from keras_textclassification.conf.path_config import path_baidu_qa_2019_train, path_baidu_qa_2019_valid 18 | # 数据预处理, 删除文件目录下文件 19 | from keras_textclassification.data_preprocess.text_preprocess import PreprocessText, read_and_process, load_json 20 | # 模型图 21 | from keras_textclassification.m02_TextCNN.graph import TextCNNGraph as Graph 22 | # 模型评估 23 | from sklearn.metrics import classification_report 24 | # 计算时间 25 | import time 26 | 27 | import numpy as np 28 | 29 | 30 | def pred_tet(path_hyper_parameter=path_hyper_parameters, path_test=None, rate=1.0): 31 | # 测试集的准确率 32 | hyper_parameters = load_json(path_hyper_parameter) 33 | if path_test: # 从外部引入测试数据地址 34 | hyper_parameters['data']['val_data'] = path_test 35 | time_start = time.time() 36 | # graph初始化 37 | graph = Graph(hyper_parameters) 38 | print("graph init ok!") 39 | graph.load_model() 40 | print("graph load ok!") 41 | ra_ed = graph.word_embedding 42 | # 数据预处理 43 | pt = PreprocessText(path_model_dir) 44 | y, x = read_and_process(hyper_parameters['data']['val_data']) 45 | # 取该数据集的百分之几的语料测试 46 | len_rate = int(len(y) * rate) 47 | x = x[:len_rate] 48 | y = y[:len_rate] 49 | y_pred = [] 50 | count = 0 51 | for x_one in x: 52 | count += 1 53 | ques_embed = ra_ed.sentence2idx(x_one) 54 | if hyper_parameters['embedding_type'] in ['bert', 'albert']: # bert数据处理, token 55 | x_val_1 = np.array([ques_embed[0]]) 56 | x_val_2 = np.array([ques_embed[1]]) 57 | x_val = [x_val_1, x_val_2] 58 | else: 59 | x_val = ques_embed 60 | # 预测 61 | pred = graph.predict(x_val) 62 | pre = pt.prereocess_idx(pred[0]) 63 | label_pred = pre[0][0][0] 64 | if count % 1000==0: 65 | print(label_pred) 66 | y_pred.append(label_pred) 67 | 68 | print("data pred ok!") 69 | # 预测结果转为int类型 70 | index_y = [pt.l2i_i2l['l2i'][i] for i in y] 71 | index_pred = [pt.l2i_i2l['l2i'][i] for i in y_pred] 72 | target_names = [pt.l2i_i2l['i2l'][str(i)] for i in list(set((index_pred + index_y)))] 73 | # 评估 74 | report_predict = classification_report(index_y, index_pred, 75 | target_names=target_names, digits=9) 76 | print(report_predict) 77 | print("耗时:" + str(time.time() - time_start)) 78 | 79 | 80 | def pred_input(path_hyper_parameter=path_hyper_parameters): 81 | # 输入预测 82 | # 加载超参数 83 | hyper_parameters = load_json(path_hyper_parameter) 84 | pt = PreprocessText(path_model_dir) 85 | # 模式初始化和加载 86 | graph = Graph(hyper_parameters) 87 | graph.load_model() 88 | ra_ed = graph.word_embedding 89 | ques = '我要打王者荣耀' 90 | # str to token 91 | ques_embed = ra_ed.sentence2idx(ques) 92 | if hyper_parameters['embedding_type'] in ['bert', 'albert']: 93 | x_val_1 = np.array([ques_embed[0]]) 94 | x_val_2 = np.array([ques_embed[1]]) 95 | x_val = [x_val_1, x_val_2] 96 | else: 97 | x_val = ques_embed 98 | # 预测 99 | pred = graph.predict(x_val) 100 | # 取id to label and pred 101 | pre = pt.prereocess_idx(pred[0]) 102 | print(pre) 103 | while True: 104 | print("请输入: ") 105 | ques = input() 106 | ques_embed = ra_ed.sentence2idx(ques) 107 | print(ques_embed) 108 | if hyper_parameters['embedding_type'] in ['bert', 'albert']: 109 | x_val_1 = np.array([ques_embed[0]]) 110 | x_val_2 = np.array([ques_embed[1]]) 111 | x_val = [x_val_1, x_val_2] 112 | else: 113 | x_val = ques_embed 114 | pred = graph.predict(x_val) 115 | pre = pt.prereocess_idx(pred[0]) 116 | print(pre) 117 | 118 | 119 | if __name__=="__main__": 120 | # 测试集预测 121 | pred_tet(path_test=path_baidu_qa_2019_valid, rate=1) # sample条件下设为1,否则训练语料可能会很少 122 | 123 | # 可输入 input 预测 124 | pred_input() 125 | 126 | 127 | -------------------------------------------------------------------------------- /test/save2load/estimator_/estimator_tst.py: -------------------------------------------------------------------------------- 1 | # !/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # @time : 2020/1/13 15:41 4 | # @author : Mo 5 | # @function: 6 | 7 | 8 | import tensorflow as tf 9 | 10 | 11 | def serving_input_receiver_fn(): 12 | serialized_tf_example = tf.placeholder(dtype=tf.string, shape=[None], name='input_tensors') 13 | receiver_tensors = {"predictor_inputs": serialized_tf_example} 14 | feature_spec = {"words": tf.FixedLenFeature([25],tf.int64)} 15 | features = tf.parse_example(serialized_tf_example, feature_spec) 16 | return tf.estimator.export.ServingInputReceiver(features, receiver_tensors) 17 | 18 | 19 | def estimator_spec_for_softmax_classification(logits, labels, mode): 20 | predicted_classes = tf.argmax(logits, 1) 21 | if (mode == tf.estimator.ModeKeys.PREDICT): 22 | export_outputs = {'predict_output': tf.estimator.export.PredictOutput({"pred_output_classes": predicted_classes, 'probabilities': tf.nn.softmax(logits)})} 23 | return tf.estimator.EstimatorSpec(mode=mode, predictions={'class': predicted_classes, 'prob': tf.nn.softmax(logits)}, export_outputs=export_outputs) # IMPORTANT!!! 24 | 25 | onehot_labels = tf.one_hot(labels, 31, 1, 0) 26 | loss = tf.losses.softmax_cross_entropy(onehot_labels=onehot_labels, logits=logits) 27 | if (mode == tf.estimator.ModeKeys.TRAIN): 28 | optimizer = tf.train.AdamOptimizer(learning_rate=0.01) 29 | train_op = optimizer.minimize(loss, global_step=tf.train.get_global_step()) 30 | return tf.estimator.EstimatorSpec(mode, loss=loss, train_op=train_op) 31 | 32 | eval_metric_ops = {'accuracy': tf.metrics.accuracy(labels=labels, predictions=predicted_classes)} 33 | return tf.estimator.EstimatorSpec(mode=mode, loss=loss, eval_metric_ops=eval_metric_ops) 34 | 35 | 36 | def model_custom(features, labels, mode): 37 | bow_column = tf.feature_column.categorical_column_with_identity("words", num_buckets=1000) 38 | bow_embedding_column = tf.feature_column.embedding_column(bow_column, dimension=50) 39 | bow = tf.feature_column.input_layer(features, feature_columns=[bow_embedding_column]) 40 | logits = tf.layers.dense(bow, 31, activation=None) 41 | 42 | return estimator_spec_for_softmax_classification(logits=logits, labels=labels, mode=mode) 43 | 44 | 45 | def main_(): 46 | # ... 47 | # preprocess-> features_train_set and labels_train_set 48 | # ... 49 | classifier = tf.estimator.Estimator(model_fn = model_custom) 50 | train_input_fn = tf.estimator.inputs.numpy_input_fn(x={"words": features_train_set}, y=labels_train_set, batch_size=batch_size_param, num_epochs=None, shuffle=True) 51 | classifier.train(input_fn=train_input_fn, steps=100) 52 | 53 | full_model_dir = classifier.export_savedmodel(export_dir_base="C:/models/directory_base", serving_input_receiver_fn=serving_input_receiver_fn) 54 | 55 | 56 | def main_tst(): 57 | # ... 58 | # preprocess-> features_test_set 59 | # ... 60 | with tf.Session() as sess: 61 | tf.saved_model.loader.load(sess, [tf.saved_model.tag_constants.SERVING], full_model_dir) 62 | predictor = tf.contrib.predictor.from_saved_model(full_model_dir) 63 | model_input = tf.train.Example(features=tf.train.Features( feature={"words": tf.train.Feature(int64_list=tf.train.Int64List(value=features_test_set)) })) 64 | model_input = model_input.SerializeToString() 65 | output_dict = predictor({"predictor_inputs":[model_input]}) 66 | y_predicted = output_dict["pred_output_classes"][0] 67 | 68 | 69 | -------------------------------------------------------------------------------- /test/sentence_similarity/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/10/28 14:21 4 | # @author :Mo 5 | # @function : -------------------------------------------------------------------------------- /test/sentence_similarity/train.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/8 14:37 4 | # @author :Mo 5 | # @function :train of bert-fune with baidu-qa-2019 in question title 6 | 7 | # 适配linux 8 | import pathlib 9 | import sys 10 | import os 11 | 12 | project_path = str(pathlib.Path(os.path.abspath(__file__)).parent.parent.parent) 13 | sys.path.append(project_path) 14 | # 地址 15 | from keras_textclassification.conf.path_config import path_model, path_fineture, path_model_dir, path_hyper_parameters 16 | # 训练验证数据地址 17 | from keras_textclassification.conf.path_config import path_sim_webank_train, path_sim_webank_valid 18 | # 数据预处理, 删除文件目录下文件 19 | from keras_textclassification.data_preprocess.text_preprocess import PreprocessSim, delete_file 20 | # 模型图 21 | from keras_textclassification.m00_Bert.graph import BertGraph as Graph 22 | # 计算时间 23 | import time 24 | 25 | 26 | def train(hyper_parameters=None, rate=1.0): 27 | """ 28 | 训练函数 29 | :param hyper_parameters: json, 超参数 30 | :param rate: 比率, 抽出rate比率语料取训练 31 | :return: None 32 | """ 33 | if not hyper_parameters: 34 | hyper_parameters = { 35 | 'len_max': 18, # 句子最大长度, 固定 推荐20-50 36 | 'embed_size': 768, # 字/词向量维度 37 | 'vocab_size': 20000, # 这里随便填的,会根据代码里修改 38 | 'trainable': True, # embedding是静态的还是动态的, 即控制可不可以微调 39 | 'level_type': 'char', # 级别, 最小单元, 字/词, 填 'char' or 'word' 40 | 'embedding_type': 'bert', # 级别, 嵌入类型, 还可以填'xlnet'、'random'、 'bert'、 'albert' or 'word2vec" 41 | 'gpu_memory_fraction': 0.76, # gpu使用率 42 | 'model': {'label': 2, # 类别数 43 | 'batch_size': 2, # 批处理尺寸, 感觉原则上越大越好,尤其是样本不均衡的时候, batch_size设置影响比较大 44 | 'filters': [2, 3, 4, 5], # 卷积核尺寸 45 | 'filters_num': 300, # 卷积个数 text-cnn:300-600 46 | 'channel_size': 1, # CNN通道数 47 | 'dropout': 0.5, # 随机失活, 概率 48 | 'decay_step': 100, # 学习率衰减step, 每N个step衰减一次 49 | 'decay_rate': 0.9, # 学习率衰减系数, 乘法 50 | 'epochs': 20, # 训练最大轮次 51 | 'patience': 3, # 早停,2-3就好 52 | 'lr': 5e-5, # 学习率, 对训练会有比较大的影响, 如果准确率一直上不去,可以考虑调这个参数 53 | 'l2': 1e-9, # l2正则化 54 | 'activate_classify': 'sigmoid', # 最后一个layer, 即分类激活函数 55 | 'loss': 'binary_crossentropy', # 损失函数 56 | 'metrics': 'accuracy', # 保存更好模型的评价标准 57 | 'is_training': True, # 训练后者是测试模型 58 | 'model_path': path_model, 59 | # 模型地址, loss降低则保存的依据, save_best_only=True, save_weights_only=True 60 | 'path_hyper_parameters': path_hyper_parameters, # 模型(包括embedding),超参数地址, 61 | 'path_fineture': path_fineture, # 保存embedding trainable地址, 例如字向量、词向量、bert向量等 62 | }, 63 | 'embedding': {'layer_indexes': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], # bert取的层数,包括embedding层 64 | # 'corpus_path': '', # embedding预训练数据地址,不配则会默认取conf里边默认的地址, keras-bert可以加载谷歌版bert,百度版ernie(需转换,https://github.com/ArthurRizar/tensorflow_ernie),哈工大版bert-wwm(tf框架,https://github.com/ymcui/Chinese-BERT-wwm) 65 | }, 66 | 'data': {'train_data': path_sim_webank_train, # 训练数据 67 | 'val_data': path_sim_webank_valid # 验证数据 68 | }, 69 | } 70 | 71 | # 删除先前存在的模型\embedding微调模型等 72 | delete_file(path_model_dir) 73 | time_start = time.time() 74 | # graph初始化 75 | graph = Graph(hyper_parameters) 76 | print("graph init ok!") 77 | ra_ed = graph.word_embedding 78 | # 数据预处理 79 | pt = PreprocessSim(path_model_dir) 80 | x_train, y_train = pt.preprocess_label_ques_to_idx(hyper_parameters['embedding_type'], 81 | hyper_parameters['data']['train_data'], 82 | ra_ed, rate=rate, shuffle=True) 83 | x_val, y_val = pt.preprocess_label_ques_to_idx(hyper_parameters['embedding_type'], 84 | hyper_parameters['data']['val_data'], 85 | ra_ed, rate=rate, shuffle=True) 86 | print("data propress ok!") 87 | print(len(y_train)) 88 | # 训练 89 | graph.fit(x_train, y_train, x_val, y_val) 90 | print("耗时:" + str(time.time() - time_start)) 91 | 92 | 93 | if __name__ == "__main__": 94 | train(rate=0.1) 95 | -------------------------------------------------------------------------------- /test/tet_char_albert_embedding.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/3 10:51 4 | # @author :Mo 5 | # @function :train of textcnn-char-bert with baidu-qa-2019 in question title 6 | 7 | 8 | # 适配linux 9 | import pathlib 10 | import sys 11 | import os 12 | project_path = str(pathlib.Path(os.path.abspath(__file__)).parent.parent.parent) 13 | sys.path.append(project_path) 14 | # 地址 15 | from keras_textclassification.conf.path_config import path_model, path_fineture, path_model_dir, path_hyper_parameters 16 | # 训练验证数据地址 17 | from keras_textclassification.conf.path_config import path_baidu_qa_2019_train, path_baidu_qa_2019_valid 18 | # 数据预处理, 删除文件目录下文件 19 | from keras_textclassification.data_preprocess.text_preprocess import PreprocessText, delete_file 20 | # 模型图 21 | from keras_textclassification.m02_TextCNN.graph import TextCNNGraph as Graph 22 | # 计算时间 23 | import time 24 | 25 | 26 | def train(hyper_parameters=None, rate=1.0): 27 | if not hyper_parameters: 28 | hyper_parameters = { 29 | 'len_max': 50, # 句子最大长度, 固定推荐20-50, bert越长会越慢, 占用空间也会变大, 本地win10-4G设为20就好, 过大小心OOM 30 | 'embed_size': 768, # 字/词向量维度, bert取768, word取300, char可以更小些 31 | 'vocab_size': 20000, # 这里随便填的,会根据代码里修改 32 | 'trainable': True, # embedding是静态的还是动态的, 即控制可不可以微调 33 | 'level_type': 'char', # 级别, 最小单元, 字/词, 填 'char' or 'word', 注意:word2vec模式下训练语料要首先切好 34 | 'embedding_type': 'albert', # 级别, 嵌入类型, 还可以填'xlnet'、'random'、 'bert'、 'albert' or 'word2vec" 35 | 'gpu_memory_fraction': 0.66, #gpu使用率 36 | 'model': {'label': 17, # 类别数 37 | 'batch_size': 32, # 批处理尺寸, 感觉原则上越大越好,尤其是样本不均衡的时候, batch_size设置影响比较大 38 | 'dropout': 0.5, # 随机失活, 概率 39 | 'decay_step': 100, # 学习率衰减step, 每N个step衰减一次 40 | 'decay_rate': 0.9, # 学习率衰减系数, 乘法 41 | 'epochs': 20, # 训练最大轮次 42 | 'patience': 3, # 早停,2-3就好 43 | 'lr': 5e-5, # 学习率,bert取5e-5,其他取1e-3, 对训练会有比较大的影响, 如果准确率一直上不去,可以考虑调这个参数 44 | 'l2': 1e-9, # l2正则化 45 | 'activate_classify': 'softmax', # 最后一个layer, 即分类激活函数 46 | 'loss': 'categorical_crossentropy', # 损失函数 47 | 'metrics': 'accuracy', # 保存更好模型的评价标准 48 | 'is_training': True, # 训练后者是测试模型 49 | 'model_path': path_model, 50 | # 模型地址, loss降低则保存的依据, save_best_only=True, save_weights_only=True 51 | 'path_hyper_parameters': path_hyper_parameters, # 模型(包括embedding),超参数地址, 52 | 'path_fineture': path_fineture, # 保存embedding trainable地址, 例如字向量、词向量、bert向量等 53 | }, 54 | 'embedding': {'layer_indexes': [12], # bert取的层数 55 | # 'corpus_path': '', # embedding预训练数据地址,不配则会默认取conf里边默认的地址, keras-bert可以加载谷歌版bert,百度版ernie(需转换,https://github.com/ArthurRizar/tensorflow_ernie),哈工大版bert-wwm(tf框架,https://github.com/ymcui/Chinese-BERT-wwm) 56 | }, 57 | 'data':{'train_data': path_baidu_qa_2019_train, # 训练数据 58 | 'val_data': path_baidu_qa_2019_valid # 验证数据 59 | }, 60 | } 61 | 62 | # 删除先前存在的模型和embedding微调模型等 63 | delete_file(path_model_dir) 64 | time_start = time.time() 65 | # graph初始化 66 | graph = Graph(hyper_parameters) 67 | print("graph init ok!") 68 | ra_ed = graph.word_embedding 69 | # 数据预处理 70 | pt = PreprocessText(path_model_dir) 71 | x_train, y_train = pt.preprocess_label_ques_to_idx(hyper_parameters['embedding_type'], 72 | hyper_parameters['data']['train_data'], 73 | ra_ed, rate=rate, shuffle=True) 74 | x_val, y_val = pt.preprocess_label_ques_to_idx(hyper_parameters['embedding_type'], 75 | hyper_parameters['data']['val_data'], 76 | ra_ed, rate=rate, shuffle=True) 77 | print("data propress ok!") 78 | print(len(y_train)) 79 | # 训练 80 | graph.fit(x_train, y_train, x_val, y_val) 81 | print("耗时:" + str(time.time()-time_start)) 82 | 83 | 84 | if __name__=="__main__": 85 | train(rate=1) 86 | -------------------------------------------------------------------------------- /test/tet_char_bert_embedding.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/3 10:51 4 | # @author :Mo 5 | # @function :train of textcnn-char-bert with baidu-qa-2019 in question title 6 | 7 | 8 | # 适配linux 9 | import pathlib 10 | import sys 11 | import os 12 | project_path = str(pathlib.Path(os.path.abspath(__file__)).parent.parent.parent) 13 | sys.path.append(project_path) 14 | # 地址 15 | from keras_textclassification.conf.path_config import path_model, path_fineture, path_model_dir, path_hyper_parameters 16 | # 训练验证数据地址 17 | from keras_textclassification.conf.path_config import path_baidu_qa_2019_train, path_baidu_qa_2019_valid 18 | # 数据预处理, 删除文件目录下文件 19 | from keras_textclassification.data_preprocess.text_preprocess import PreprocessText, delete_file 20 | # 模型图 21 | from keras_textclassification.m02_TextCNN.graph import TextCNNGraph as Graph 22 | # 计算时间 23 | import time 24 | 25 | 26 | def train(hyper_parameters=None, rate=1.0): 27 | if not hyper_parameters: 28 | hyper_parameters = { 29 | 'len_max': 5, # 句子最大长度, 固定推荐20-50, bert越长会越慢, 占用空间也会变大, 本地win10-4G设为20就好, 过大小心OOM 30 | 'embed_size': 768, # 字/词向量维度, bert取768, word取300, char可以更小些 31 | 'vocab_size': 20000, # 这里随便填的,会根据代码里修改 32 | 'trainable': True, # embedding是静态的还是动态的, 即控制可不可以微调 33 | 'level_type': 'char', # 级别, 最小单元, 字/词, 填 'char' or 'word', 注意:word2vec模式下训练语料要首先切好 34 | 'embedding_type': 'bert', # 级别, 嵌入类型, 还可以填'xlnet'、'random'、 'bert'、 'albert' or 'word2vec" 35 | 'gpu_memory_fraction': 0.66, #gpu使用率 36 | 'model': {'label': 17, # 类别数 37 | 'batch_size': 32, # 批处理尺寸, 感觉原则上越大越好,尤其是样本不均衡的时候, batch_size设置影响比较大 38 | 'dropout': 0.5, # 随机失活, 概率 39 | 'decay_step': 100, # 学习率衰减step, 每N个step衰减一次 40 | 'decay_rate': 0.9, # 学习率衰减系数, 乘法 41 | 'epochs': 20, # 训练最大轮次 42 | 'patience': 3, # 早停,2-3就好 43 | 'lr': 5e-5, # 学习率,bert取5e-5,其他取1e-3, 对训练会有比较大的影响, 如果准确率一直上不去,可以考虑调这个参数 44 | 'l2': 1e-9, # l2正则化 45 | 'activate_classify': 'softmax', # 最后一个layer, 即分类激活函数 46 | 'loss': 'categorical_crossentropy', # 损失函数 47 | 'metrics': 'accuracy', # 保存更好模型的评价标准 48 | 'is_training': True, # 训练后者是测试模型 49 | 'model_path': path_model, 50 | # 模型地址, loss降低则保存的依据, save_best_only=True, save_weights_only=True 51 | 'path_hyper_parameters': path_hyper_parameters, # 模型(包括embedding),超参数地址, 52 | 'path_fineture': path_fineture, # 保存embedding trainable地址, 例如字向量、词向量、bert向量等 53 | }, 54 | 'embedding': {'layer_indexes': [12], # bert取的层数 55 | # 'corpus_path': '', # embedding预训练数据地址,不配则会默认取conf里边默认的地址, keras-bert可以加载谷歌版bert,百度版ernie(需转换,https://github.com/ArthurRizar/tensorflow_ernie),哈工大版bert-wwm(tf框架,https://github.com/ymcui/Chinese-BERT-wwm) 56 | }, 57 | 'data':{'train_data': path_baidu_qa_2019_train, # 训练数据 58 | 'val_data': path_baidu_qa_2019_valid # 验证数据 59 | }, 60 | } 61 | 62 | # 删除先前存在的模型和embedding微调模型等 63 | delete_file(path_model_dir) 64 | time_start = time.time() 65 | # graph初始化 66 | graph = Graph(hyper_parameters) 67 | print("graph init ok!") 68 | ra_ed = graph.word_embedding 69 | # 数据预处理 70 | pt = PreprocessText(path_model_dir) 71 | x_train, y_train = pt.preprocess_label_ques_to_idx(hyper_parameters['embedding_type'], 72 | hyper_parameters['data']['train_data'], 73 | ra_ed, rate=rate, shuffle=True) 74 | x_val, y_val = pt.preprocess_label_ques_to_idx(hyper_parameters['embedding_type'], 75 | hyper_parameters['data']['val_data'], 76 | ra_ed, rate=rate, shuffle=True) 77 | print("data propress ok!") 78 | print(len(y_train)) 79 | # 训练 80 | graph.fit(x_train, y_train, x_val, y_val) 81 | print("耗时:" + str(time.time()-time_start)) 82 | 83 | 84 | if __name__=="__main__": 85 | train(rate=1) 86 | # 注意: 4G的1050Ti的GPU、win10下batch_size=32,len_max=20, gpu<=0.87, 应该就可以bert-fineture了。 87 | # 全量数据训练一轮(batch_size=32),就能达到80%准确率(验证集), 效果还是不错的 88 | # win10下出现过错误,gpu、len_max、batch_size配小一点就好:ailed to allocate 3.56G (3822520832 bytes) from device: CUDA_ERROR_OUT_OF_MEMORY: out of memory 89 | -------------------------------------------------------------------------------- /test/tet_char_random_embedding.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/3 10:51 4 | # @author :Mo 5 | # @function :train of textcnn-char-random with baidu-qa-2019 in question title 6 | 7 | # 适配linux 8 | import pathlib 9 | import sys 10 | import os 11 | project_path = str(pathlib.Path(os.path.abspath(__file__)).parent.parent.parent) 12 | sys.path.append(project_path) 13 | # 地址 14 | from keras_textclassification.conf.path_config import path_model, path_fineture, path_model_dir, path_hyper_parameters 15 | # 训练验证数据地址 16 | from keras_textclassification.conf.path_config import path_baidu_qa_2019_train, path_baidu_qa_2019_valid 17 | # 数据预处理, 删除文件目录下文件 18 | from keras_textclassification.data_preprocess.text_preprocess import PreprocessText, delete_file 19 | # 模型图 20 | from keras_textclassification.m02_TextCNN.graph import TextCNNGraph as Graph 21 | # 计算时间 22 | import time 23 | 24 | 25 | def train(hyper_parameters=None, rate=1.0): 26 | if not hyper_parameters: 27 | hyper_parameters = { 28 | 'len_max': 50, # 句子最大长度, 固定推荐20-50, bert越长会越慢, 占用空间也会变大, 本地win10-4G设为20就好, 过大小心OOM 29 | 'embed_size': 300, # 字/词向量维度, bert取768, word取300, char可以更小些 30 | 'vocab_size': 20000, # 这里随便填的,会根据代码里修改 31 | 'trainable': True, # embedding是静态的还是动态的, 即控制可不可以微调 32 | 'level_type': 'char', # 级别, 最小单元, 字/词, 填 'char' or 'word', 注意:word2vec模式下训练语料要首先切好 33 | 'embedding_type': 'random', # 级别, 嵌入类型, 还可以填'xlnet'、'random'、 'bert'、 'albert' or 'word2vec" 34 | 'gpu_memory_fraction': 0.66, #gpu使用率 35 | 'model': {'label': 17, # 类别数 36 | 'batch_size': 32, # 批处理尺寸, 感觉原则上越大越好,尤其是样本不均衡的时候, batch_size设置影响比较大 37 | 'dropout': 0.5, # 随机失活, 概率 38 | 'decay_step': 100, # 学习率衰减step, 每N个step衰减一次 39 | 'decay_rate': 0.9, # 学习率衰减系数, 乘法 40 | 'epochs': 20, # 训练最大轮次 41 | 'patience': 3, # 早停,2-3就好 42 | 'lr': 1e-3, # 学习率,bert取5e-5,其他取1e-3, 对训练会有比较大的影响, 如果准确率一直上不去,可以考虑调这个参数 43 | 'l2': 1e-9, # l2正则化 44 | 'activate_classify': 'softmax', # 最后一个layer, 即分类激活函数 45 | 'loss': 'categorical_crossentropy', # 损失函数 46 | 'metrics': 'accuracy', # 保存更好模型的评价标准 47 | 'is_training': True, # 训练后者是测试模型 48 | 'model_path': path_model, 49 | # 模型地址, loss降低则保存的依据, save_best_only=True, save_weights_only=True 50 | 'path_hyper_parameters': path_hyper_parameters, # 模型(包括embedding),超参数地址, 51 | 'path_fineture': path_fineture, # 保存embedding trainable地址, 例如字向量、词向量、bert向量等 52 | }, 53 | 'embedding': {'layer_indexes': [12], # bert取的层数 54 | # 'corpus_path': '', # embedding预训练数据地址,不配则会默认取conf里边默认的地址, keras-bert可以加载谷歌版bert,百度版ernie(需转换,https://github.com/ArthurRizar/tensorflow_ernie),哈工大版bert-wwm(tf框架,https://github.com/ymcui/Chinese-BERT-wwm) 55 | }, 56 | 'data':{'train_data': path_baidu_qa_2019_train, # 训练数据 57 | 'val_data': path_baidu_qa_2019_valid # 验证数据 58 | }, 59 | } 60 | 61 | # 删除先前存在的模型和embedding微调模型等 62 | delete_file(path_model_dir) 63 | time_start = time.time() 64 | # graph初始化 65 | graph = Graph(hyper_parameters) 66 | print("graph init ok!") 67 | ra_ed = graph.word_embedding 68 | # 数据预处理 69 | pt = PreprocessText(path_model_dir) 70 | x_train, y_train = pt.preprocess_label_ques_to_idx(hyper_parameters['embedding_type'], 71 | hyper_parameters['data']['train_data'], 72 | ra_ed, rate=rate, shuffle=True) 73 | x_val, y_val = pt.preprocess_label_ques_to_idx(hyper_parameters['embedding_type'], 74 | hyper_parameters['data']['val_data'], 75 | ra_ed, rate=rate, shuffle=True) 76 | print("data propress ok!") 77 | print(len(y_train)) 78 | # 训练 79 | graph.fit(x_train, y_train, x_val, y_val) 80 | print("耗时:" + str(time.time()-time_start)) 81 | 82 | 83 | if __name__=="__main__": 84 | train(rate=1) 85 | # 注意: 4G的1050Ti的GPU、win10下batch_size=32,len_max=20, gpu<=0.87, 应该就可以bert-fineture了。 86 | # 全量数据训练一轮(batch_size=32),就能达到80%准确率(验证集), 效果还是不错的 87 | # win10下出现过错误,gpu、len_max、batch_size配小一点就好:ailed to allocate 3.56G (3822520832 bytes) from device: CUDA_ERROR_OUT_OF_MEMORY: out of memory 88 | 89 | -------------------------------------------------------------------------------- /test/tet_char_word2vec_embedding.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/3 10:51 4 | # @author :Mo 5 | # @function :train of textcnn-char-word2vec with baidu-qa-2019 in question title 6 | 7 | 8 | # 适配linux 9 | import pathlib 10 | import sys 11 | import os 12 | project_path = str(pathlib.Path(os.path.abspath(__file__)).parent.parent.parent) 13 | sys.path.append(project_path) 14 | # 地址 15 | from keras_textclassification.conf.path_config import path_model, path_fineture, path_model_dir, path_hyper_parameters 16 | # 训练验证数据地址 17 | from keras_textclassification.conf.path_config import path_baidu_qa_2019_train, path_baidu_qa_2019_valid 18 | # 数据预处理, 删除文件目录下文件 19 | from keras_textclassification.data_preprocess.text_preprocess import PreprocessText, delete_file 20 | # 模型图 21 | from keras_textclassification.m02_TextCNN.graph import TextCNNGraph as Graph 22 | # 计算时间 23 | import time 24 | 25 | 26 | def train(hyper_parameters=None, rate=1.0): 27 | if not hyper_parameters: 28 | hyper_parameters = { 29 | 'len_max': 50, # 句子最大长度, 固定推荐20-50, bert越长会越慢, 占用空间也会变大, 本地win10-4G设为20就好, 过大小心OOM 30 | 'embed_size': 300, # 字/词向量维度, bert取768, word取300, char可以更小些 31 | 'vocab_size': 20000, # 这里随便填的,会根据代码里修改 32 | 'trainable': True, # embedding是静态的还是动态的, 即控制可不可以微调 33 | 'level_type': 'char', # 级别, 最小单元, 字/词, 填 'char' or 'word', 注意:word2vec模式下训练语料要首先切好 34 | 'embedding_type': 'word2vec', # 级别, 嵌入类型, 还可以填'xlnet'、'random'、 'bert'、 'albert' or 'word2vec" 35 | 'gpu_memory_fraction': 0.66, #gpu使用率 36 | 'model': {'label': 17, # 类别数 37 | 'batch_size': 32, # 批处理尺寸, 感觉原则上越大越好,尤其是样本不均衡的时候, batch_size设置影响比较大 38 | 'dropout': 0.5, # 随机失活, 概率 39 | 'decay_step': 100, # 学习率衰减step, 每N个step衰减一次 40 | 'decay_rate': 0.9, # 学习率衰减系数, 乘法 41 | 'epochs': 20, # 训练最大轮次 42 | 'patience': 3, # 早停,2-3就好 43 | 'lr': 1e-3, # 学习率,bert取5e-5,其他取1e-3, 对训练会有比较大的影响, 如果准确率一直上不去,可以考虑调这个参数 44 | 'l2': 1e-9, # l2正则化 45 | 'activate_classify': 'softmax', # 最后一个layer, 即分类激活函数 46 | 'loss': 'categorical_crossentropy', # 损失函数 47 | 'metrics': 'accuracy', # 保存更好模型的评价标准 48 | 'is_training': True, # 训练后者是测试模型 49 | 'model_path': path_model, 50 | # 模型地址, loss降低则保存的依据, save_best_only=True, save_weights_only=True 51 | 'path_hyper_parameters': path_hyper_parameters, # 模型(包括embedding),超参数地址, 52 | 'path_fineture': path_fineture, # 保存embedding trainable地址, 例如字向量、词向量、bert向量等 53 | }, 54 | 'embedding': {'layer_indexes': [12], # bert取的层数 55 | # 'corpus_path': '', # embedding预训练数据地址,不配则会默认取conf里边默认的地址, keras-bert可以加载谷歌版bert,百度版ernie(需转换,https://github.com/ArthurRizar/tensorflow_ernie),哈工大版bert-wwm(tf框架,https://github.com/ymcui/Chinese-BERT-wwm) 56 | }, 57 | 'data':{'train_data': path_baidu_qa_2019_train, # 训练数据 58 | 'val_data': path_baidu_qa_2019_valid # 验证数据 59 | }, 60 | } 61 | 62 | # 删除先前存在的模型和embedding微调模型等 63 | delete_file(path_model_dir) 64 | time_start = time.time() 65 | # graph初始化 66 | graph = Graph(hyper_parameters) 67 | print("graph init ok!") 68 | ra_ed = graph.word_embedding 69 | # 数据预处理 70 | pt = PreprocessText(path_model_dir) 71 | x_train, y_train = pt.preprocess_label_ques_to_idx(hyper_parameters['embedding_type'], 72 | hyper_parameters['data']['train_data'], 73 | ra_ed, rate=rate, shuffle=True) 74 | x_val, y_val = pt.preprocess_label_ques_to_idx(hyper_parameters['embedding_type'], 75 | hyper_parameters['data']['val_data'], 76 | ra_ed, rate=rate, shuffle=True) 77 | print("data propress ok!") 78 | print(len(y_train)) 79 | # 训练 80 | graph.fit(x_train, y_train, x_val, y_val) 81 | print("耗时:" + str(time.time()-time_start)) 82 | 83 | 84 | if __name__=="__main__": 85 | train(rate=1) 86 | # 注意: 4G的1050Ti的GPU、win10下batch_size=32,len_max=20, gpu<=0.87, 应该就可以bert-fineture了。 87 | # 全量数据训练一轮(batch_size=32),就能达到80%准确率(验证集), 效果还是不错的 88 | # win10下出现过错误,gpu、len_max、batch_size配小一点就好:ailed to allocate 3.56G (3822520832 bytes) from device: CUDA_ERROR_OUT_OF_MEMORY: out of memory 89 | 90 | 91 | 92 | -------------------------------------------------------------------------------- /test/tet_char_xlnet_embedding.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/8/28 15:08 4 | # @author :Mo 5 | # @function :train of textcnn-char-bert with baidu-qa-2019 in question title 6 | 7 | 8 | # # 使用cpu 9 | # import os 10 | # os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" 11 | # os.environ["CUDA_VISIBLE_DEVICES"] = "-1" 12 | 13 | # 适配linux 14 | import pathlib 15 | import sys 16 | import os 17 | os.environ["TF_KERAS"] = "1" 18 | project_path = str(pathlib.Path(os.path.abspath(__file__)).parent.parent.parent) 19 | sys.path.append(project_path) 20 | # 地址 21 | from keras_textclassification.conf.path_config import path_model, path_fineture, path_model_dir, path_hyper_parameters 22 | # 训练验证数据地址 23 | from keras_textclassification.conf.path_config import path_baidu_qa_2019_train, path_baidu_qa_2019_valid 24 | # 数据预处理, 删除文件目录下文件 25 | from keras_textclassification.data_preprocess.text_preprocess import PreprocessText, delete_file 26 | # 模型图 27 | from keras_textclassification.m02_TextCNN.graph import TextCNNGraph as Graph 28 | # 计算时间 29 | import time 30 | 31 | 32 | def train(hyper_parameters=None, rate=1.0): 33 | if not hyper_parameters: 34 | hyper_parameters = { 35 | 'len_max': 32, # 句子最大长度, 固定推荐20-50, bert越长会越慢, 占用空间也会变大, 本地win10-4G设为20就好, 过大小心OOM 36 | 'embed_size': 768, # 字/词向量维度, bert取768, word取300, char可以更小些 37 | 'vocab_size': 20000, # 这里随便填的,会根据代码里修改 38 | 'trainable': True, # embedding是静态的还是动态的, 即控制可不可以微调 39 | 'level_type': 'char', # 级别, 最小单元, 字/词, 填 'char' or 'word', 注意:word2vec模式下训练语料要首先切好 40 | 'embedding_type': 'xlnet', # 级别, 嵌入类型, 还可以填'xlnet'、'random'、 'bert'、 'albert' or 'word2vec" 41 | 'gpu_memory_fraction': 0.66, #gpu使用率 42 | 'model': {'label': 17, # 类别数 43 | 'batch_size': 2, # 批处理尺寸, 感觉原则上越大越好,尤其是样本不均衡的时候, batch_size设置影响比较大 44 | 'dropout': 0.5, # 随机失活, 概率 45 | 'decay_step': 100, # 学习率衰减step, 每N个step衰减一次 46 | 'decay_rate': 0.9, # 学习率衰减系数, 乘法 47 | 'epochs': 20, # 训练最大轮次 48 | 'patience': 3, # 早停,2-3就好 49 | 'lr': 5e-5, # 学习率,bert取5e-5,其他取1e-3, 对训练会有比较大的影响, 如果准确率一直上不去,可以考虑调这个参数 50 | 'l2': 1e-9, # l2正则化 51 | 'activate_classify': 'softmax', # 最后一个layer, 即分类激活函数 52 | 'loss': 'categorical_crossentropy', # 损失函数 53 | 'metrics': 'accuracy', # 保存更好模型的评价标准 54 | 'is_training': True, # 训练后者是测试模型 55 | 'model_path': path_model, 56 | # 模型地址, loss降低则保存的依据, save_best_only=True, save_weights_only=True 57 | 'path_hyper_parameters': path_hyper_parameters, # 模型(包括embedding),超参数地址, 58 | 'path_fineture': path_fineture, # 保存embedding trainable地址, 例如字向量、词向量、bert向量等 59 | }, 60 | 'embedding': {'layer_indexes': [i for i in range(24)], # bert取的层数 61 | # 'corpus_path': '', # embedding预训练数据地址,不配则会默认取conf里边默认的地址, keras-bert可以加载谷歌版bert,百度版ernie(需转换,https://github.com/ArthurRizar/tensorflow_ernie),哈工大版bert-wwm(tf框架,https://github.com/ymcui/Chinese-BERT-wwm) 62 | 'xlnet_embed':{'attention_type': 'bi', # or 'uni' 63 | 'memory_len': 0, 64 | 'target_len': 32, }, 65 | }, 66 | 'data':{'train_data': path_baidu_qa_2019_train, # 训练数据 67 | 'val_data': path_baidu_qa_2019_valid # 验证数据 68 | }, 69 | } 70 | 71 | # 删除先前存在的模型和embedding微调模型等 72 | delete_file(path_model_dir) 73 | time_start = time.time() 74 | # graph初始化 75 | graph = Graph(hyper_parameters) 76 | print("graph init ok!") 77 | ra_ed = graph.word_embedding 78 | # 数据预处理 79 | pt = PreprocessText(path_model_dir) 80 | x_train, y_train = pt.preprocess_label_ques_to_idx(hyper_parameters['embedding_type'], 81 | hyper_parameters['data']['train_data'], 82 | ra_ed, rate=rate, shuffle=True) 83 | x_val, y_val = pt.preprocess_label_ques_to_idx(hyper_parameters['embedding_type'], 84 | hyper_parameters['data']['val_data'], 85 | ra_ed, rate=rate, shuffle=True) 86 | print("data propress ok!") 87 | print(len(y_train)) 88 | # 训练 89 | graph.fit(x_train, y_train, x_val, y_val) 90 | print("耗时:" + str(time.time()-time_start)) 91 | 92 | 93 | if __name__=="__main__": 94 | train(rate=1) 95 | -------------------------------------------------------------------------------- /test/tet_train.py: -------------------------------------------------------------------------------- 1 | # !/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # @time : 2019/11/12 16:45 4 | # @author : Mo 5 | # @function: 6 | 7 | 8 | from keras_textclassification import train 9 | train(graph='TextCNN', # 必填, 算法名, 可选"ALBERT","BERT","XLNET","FASTTEXT","TEXTCNN","CHARCNN", 10 | # "TEXTRNN","RCNN","DCNN","DPCNN","VDCNN","CRNN","DEEPMOJI", 11 | # "SELFATTENTION", "HAN","CAPSULE","TRANSFORMER" 12 | label=17, # 必填, 类别数, 训练集和测试集合必须一样 13 | path_train_data=None, # 必填, 训练数据文件, csv格式, 必须含'label,ques'头文件, 详见keras_textclassification/data 14 | path_dev_data=None, # 必填, 测试数据文件, csv格式, 必须含'label,ques'头文件, 详见keras_textclassification/data 15 | rate=1, # 可填, 训练数据选取比例 16 | hyper_parameters=None) # 可填, json格式, 超参数, 默认embedding为'char','random' 17 | -------------------------------------------------------------------------------- /test/tet_word_random_embedding.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/3 10:51 4 | # @author :Mo 5 | # @function :train of textcnn-word-random with baidu-qa-2019 in question title 6 | 7 | # 适配linux 8 | import pathlib 9 | import sys 10 | import os 11 | project_path = str(pathlib.Path(os.path.abspath(__file__)).parent.parent.parent) 12 | sys.path.append(project_path) 13 | # 地址 14 | from keras_textclassification.conf.path_config import path_model, path_fineture, path_model_dir, path_hyper_parameters 15 | # 训练验证数据地址 16 | from keras_textclassification.conf.path_config import path_baidu_qa_2019_train, path_baidu_qa_2019_valid 17 | # 数据预处理, 删除文件目录下文件 18 | from keras_textclassification.data_preprocess.text_preprocess import PreprocessText, delete_file 19 | # 模型图 20 | from keras_textclassification.m02_TextCNN.graph import TextCNNGraph as Graph 21 | # 计算时间 22 | import time 23 | 24 | 25 | def train(hyper_parameters=None, rate=1.0): 26 | if not hyper_parameters: 27 | hyper_parameters = { 28 | 'len_max': 50, # 句子最大长度, 固定推荐20-50, bert越长会越慢, 占用空间也会变大, 本地win10-4G设为20就好, 过大小心OOM 29 | 'embed_size': 300, # 字/词向量维度, bert取768, word取300, char可以更小些 30 | 'vocab_size': 20000, # 这里随便填的,会根据代码里修改 31 | 'trainable': True, # embedding是静态的还是动态的, 即控制可不可以微调 32 | 'level_type': 'word', # 级别, 最小单元, 字/词, 填 'char' or 'word', 注意:word2vec模式下训练语料要首先切好 33 | 'embedding_type': 'random', # 级别, 嵌入类型, 还可以填'xlnet'、'random'、 'bert'、 'albert' or 'word2vec" 34 | 'gpu_memory_fraction': 0.66, #gpu使用率 35 | 'model': {'label': 17, # 类别数 36 | 'batch_size': 32, # 批处理尺寸, 感觉原则上越大越好,尤其是样本不均衡的时候, batch_size设置影响比较大 37 | 'dropout': 0.5, # 随机失活, 概率 38 | 'decay_step': 100, # 学习率衰减step, 每N个step衰减一次 39 | 'decay_rate': 0.9, # 学习率衰减系数, 乘法 40 | 'epochs': 20, # 训练最大轮次 41 | 'patience': 3, # 早停,2-3就好 42 | 'lr': 1e-3, # 学习率,bert取5e-5,其他取1e-3, 对训练会有比较大的影响, 如果准确率一直上不去,可以考虑调这个参数 43 | 'l2': 1e-9, # l2正则化 44 | 'activate_classify': 'softmax', # 最后一个layer, 即分类激活函数 45 | 'loss': 'categorical_crossentropy', # 损失函数 46 | 'metrics': 'accuracy', # 保存更好模型的评价标准 47 | 'is_training': True, # 训练后者是测试模型 48 | 'model_path': path_model, 49 | # 模型地址, loss降低则保存的依据, save_best_only=True, save_weights_only=True 50 | 'path_hyper_parameters': path_hyper_parameters, # 模型(包括embedding),超参数地址, 51 | 'path_fineture': path_fineture, # 保存embedding trainable地址, 例如字向量、词向量、bert向量等 52 | }, 53 | 'embedding': {'layer_indexes': [12], # bert取的层数 54 | # 'corpus_path': '', # embedding预训练数据地址,不配则会默认取conf里边默认的地址, keras-bert可以加载谷歌版bert,百度版ernie(需转换,https://github.com/ArthurRizar/tensorflow_ernie),哈工大版bert-wwm(tf框架,https://github.com/ymcui/Chinese-BERT-wwm) 55 | }, 56 | 'data':{'train_data': path_baidu_qa_2019_train, # 训练数据 57 | 'val_data': path_baidu_qa_2019_valid # 验证数据 58 | }, 59 | } 60 | 61 | # 删除先前存在的模型和embedding微调模型等 62 | delete_file(path_model_dir) 63 | time_start = time.time() 64 | # graph初始化 65 | graph = Graph(hyper_parameters) 66 | print("graph init ok!") 67 | ra_ed = graph.word_embedding 68 | # 数据预处理 69 | pt = PreprocessText(path_model_dir) 70 | x_train, y_train = pt.preprocess_label_ques_to_idx(hyper_parameters['embedding_type'], 71 | hyper_parameters['data']['train_data'], 72 | ra_ed, rate=rate, shuffle=True) 73 | x_val, y_val = pt.preprocess_label_ques_to_idx(hyper_parameters['embedding_type'], 74 | hyper_parameters['data']['val_data'], 75 | ra_ed, rate=rate, shuffle=True) 76 | print("data propress ok!") 77 | print(len(y_train)) 78 | # 训练 79 | graph.fit(x_train, y_train, x_val, y_val) 80 | print("耗时:" + str(time.time()-time_start)) 81 | 82 | 83 | if __name__=="__main__": 84 | train(rate=1) 85 | # 注意: 4G的1050Ti的GPU、win10下batch_size=32,len_max=20, gpu<=0.87, 应该就可以bert-fineture了。 86 | # 全量数据训练一轮(batch_size=32),就能达到80%准确率(验证集), 效果还是不错的 87 | # win10下出现过错误,gpu、len_max、batch_size配小一点就好:ailed to allocate 3.56G (3822520832 bytes) from device: CUDA_ERROR_OUT_OF_MEMORY: out of memory 88 | 89 | 90 | -------------------------------------------------------------------------------- /test/tet_word_word2vec_embedding.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # !/usr/bin/python 3 | # @time :2019/6/3 10:51 4 | # @author :Mo 5 | # @function :train of textcnn-word-word2vec with baidu-qa-2019 in question title 6 | 7 | # 适配linux 8 | import pathlib 9 | import sys 10 | import os 11 | project_path = str(pathlib.Path(os.path.abspath(__file__)).parent.parent.parent) 12 | sys.path.append(project_path) 13 | # 地址 14 | from keras_textclassification.conf.path_config import path_model, path_fineture, path_model_dir, path_hyper_parameters 15 | # 训练验证数据地址 16 | from keras_textclassification.conf.path_config import path_baidu_qa_2019_train, path_baidu_qa_2019_valid 17 | # 数据预处理, 删除文件目录下文件 18 | from keras_textclassification.data_preprocess.text_preprocess import PreprocessText, delete_file 19 | # 模型图 20 | from keras_textclassification.m02_TextCNN.graph import TextCNNGraph as Graph 21 | # 计算时间 22 | import time 23 | 24 | 25 | def train(hyper_parameters=None, rate=1.0): 26 | if not hyper_parameters: 27 | hyper_parameters = { 28 | 'len_max': 50, # 句子最大长度, 固定推荐20-50, bert越长会越慢, 占用空间也会变大, 本地win10-4G设为20就好, 过大小心OOM 29 | 'embed_size': 300, # 字/词向量维度, bert取768, word取300, char可以更小些 30 | 'vocab_size': 20000, # 这里随便填的,会根据代码里修改 31 | 'trainable': True, # embedding是静态的还是动态的, 即控制可不可以微调 32 | 'level_type': 'word', # 级别, 最小单元, 字/词, 填 'char' or 'word', 注意:word2vec模式下训练语料要首先切好 33 | 'embedding_type': 'word2vec', # 级别, 嵌入类型, 还可以填'xlnet'、'random'、 'bert'、 'albert' or 'word2vec" 34 | 'gpu_memory_fraction': 0.66, #gpu使用率 35 | 'model': {'label': 17, # 类别数 36 | 'batch_size': 32, # 批处理尺寸, 感觉原则上越大越好,尤其是样本不均衡的时候, batch_size设置影响比较大 37 | 'dropout': 0.5, # 随机失活, 概率 38 | 'decay_step': 100, # 学习率衰减step, 每N个step衰减一次 39 | 'decay_rate': 0.9, # 学习率衰减系数, 乘法 40 | 'epochs': 20, # 训练最大轮次 41 | 'patience': 3, # 早停,2-3就好 42 | 'lr': 1e-3, # 学习率,bert取5e-5,其他取1e-3, 对训练会有比较大的影响, 如果准确率一直上不去,可以考虑调这个参数 43 | 'l2': 1e-9, # l2正则化 44 | 'activate_classify': 'softmax', # 最后一个layer, 即分类激活函数 45 | 'loss': 'categorical_crossentropy', # 损失函数 46 | 'metrics': 'accuracy', # 保存更好模型的评价标准 47 | 'is_training': True, # 训练后者是测试模型 48 | 'model_path': path_model, 49 | # 模型地址, loss降低则保存的依据, save_best_only=True, save_weights_only=True 50 | 'path_hyper_parameters': path_hyper_parameters, # 模型(包括embedding),超参数地址, 51 | 'path_fineture': path_fineture, # 保存embedding trainable地址, 例如字向量、词向量、bert向量等 52 | }, 53 | 'embedding': {'layer_indexes': [12], # bert取的层数 54 | # 'corpus_path': '', # embedding预训练数据地址,不配则会默认取conf里边默认的地址, keras-bert可以加载谷歌版bert,百度版ernie(需转换,https://github.com/ArthurRizar/tensorflow_ernie),哈工大版bert-wwm(tf框架,https://github.com/ymcui/Chinese-BERT-wwm) 55 | }, 56 | 'data':{'train_data': path_baidu_qa_2019_train, # 训练数据 57 | 'val_data': path_baidu_qa_2019_valid # 验证数据 58 | }, 59 | } 60 | 61 | # 删除先前存在的模型和embedding微调模型等 62 | delete_file(path_model_dir) 63 | time_start = time.time() 64 | # graph初始化 65 | graph = Graph(hyper_parameters) 66 | print("graph init ok!") 67 | ra_ed = graph.word_embedding 68 | # 数据预处理 69 | pt = PreprocessText(path_model_dir) 70 | x_train, y_train = pt.preprocess_label_ques_to_idx(hyper_parameters['embedding_type'], 71 | hyper_parameters['data']['train_data'], 72 | ra_ed, rate=rate, shuffle=True) 73 | x_val, y_val = pt.preprocess_label_ques_to_idx(hyper_parameters['embedding_type'], 74 | hyper_parameters['data']['val_data'], 75 | ra_ed, rate=rate, shuffle=True) 76 | print("data propress ok!") 77 | print(len(y_train)) 78 | # 训练 79 | graph.fit(x_train, y_train, x_val, y_val) 80 | print("耗时:" + str(time.time()-time_start)) 81 | 82 | 83 | if __name__=="__main__": 84 | train(rate=1) 85 | # 注意: 4G的1050Ti的GPU、win10下batch_size=32,len_max=20, gpu<=0.87, 应该就可以bert-fineture了。 86 | # 全量数据训练一轮(batch_size=32),就能达到80%准确率(验证集), 效果还是不错的 87 | # win10下出现过错误,gpu、len_max、batch_size配小一点就好:ailed to allocate 3.56G (3822520832 bytes) from device: CUDA_ERROR_OUT_OF_MEMORY: out of memory 88 | 89 | 90 | 91 | -------------------------------------------------------------------------------- /test/tft_tensorflow_transformer/__init__.py: -------------------------------------------------------------------------------- 1 | # !/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # @time : 2020/2/20 15:51 4 | # @author : Mo 5 | # @function: --------------------------------------------------------------------------------