江西万通建设有限公司网站app引流推广软件
文章目录
- 一、关于 langid
- 二、基本使用
- Normalization
- 多个语言中选择一个
- 三、训练模型
- 1、需要
- 2、工具是
- 3、过程
- 4、代码调用自定义模型
一、关于 langid
https://github.com/saffsd/langid.py
用于检测语言
二、基本使用
import langidlangid.classify("This is a test")
('en', -54.41310358047485)
Normalization
可以使用 0–1 之间的数据来衡量
from langid.langid import LanguageIdentifier, model
identifier = LanguageIdentifier.from_modelstring(model, norm_probs=True)identifier.classify("This is a test")
# ('en', 0.9999999909903544)
多个语言中选择一个
上述方式,很多时候存在语言不准的情况,可以设置默认语言,让 langid 来选取
langid.set_languages(['de','fr','it'])langid.classify("I do not speak english")
('it', 0.99999835791478453)
def detect():identifier = LanguageIdentifier.from_modelstring(model, norm_probs=True)identifier.set_languages(['th', 'zh', 'en'])arr = ['I do not speak english','ผู้สื่อข่าวได้รับแจ้งว่ามีประชาชนเ','得亲密。','由泰国当红男星"film" Rattapoom Toekongsap和泰国超模']for str in arr:print(identifier.classify(str))
三、训练模型
1、需要
1、单语文档语料库
2 层深的文件夹层次结构:域 – 语言类型 – 文档文件
每个文档应该是一个单独的文件,每个文件应该在一个 2 层深的文件夹层次结构中,语言嵌套在域中。
./corpus/domain1/en/File1.txt
./corpus/domainX/en/001-file.xml
2、工具是
- index.py - 索引语料库。生成文件、语料库、语言对的列表。
- tokenize.py - 获取索引并
标记
相应的文件 - DFfeatureselect.py - 按文档频率选择
特征
- IGweight.py - 计算语言和领域的 IG 权重
- LDfeatureselect.py - 获取 IG 权重并使用它们来选择一个特征集
- scanner.py - 基于功能集构建扫描仪
- NBtrain.py - 使用索引语料库和扫描仪学习 NB 参数
3、过程
1、索引
$ python index.py ./corpus
2、标记
python tokenize.py corpus.model
3、识别最频繁的标记
通过文档频率识别最频繁的标记
python DFfeatureselect.py corpus.model
4、计算每个顶级特征的 IG 权重
以下两个都需要执行
python IGweight.py -d corpus.model
python IGweight.py -lb corpus.model
5、计算每个令牌的 LD 分数
python LDfeatureselect.py corpus.model
这将生成用于构建 NB 模型的 LD 特征的最终列表。
6、组装扫描仪
python scanner.py corpus.model
扫描仪是对特征集的编译 DFA,可用于计算文档中每个特征在单次遍历文档中出现的次数。此 DFA 是使用 Aho-Corasick 字符串匹配构建的。
7、朴素贝叶斯参数
最后,我们学习实际的朴素贝叶斯参数:
python NBtrain.py corpus.model
4、代码调用自定义模型
1)从指定位置加载模型,并进行 normalize
identifier = LanguageIdentifier.from_modelpath(model_path, norm_probs=True)
model 本质是一个长字符串
2)从字符串加载模型
from langid.langid import LanguageIdentifier, modelidentifier = LanguageIdentifier.from_modelstring(model, norm_probs=True)
3)命令行中使用
# normalize
$ python langid.py -n
>>> 你好呀
('zh', 0.9998446372669386)# normalize + custom model
$ python langid.py -n -m /Users/xxx/langid.py/langid/train/corpus.model/model
>>> 这是美好的开始
('zh', 0.999999927953073)
伊织 2021-09-07