胖哥網(wǎng)站的建設(shè)目標(biāo)網(wǎng)絡(luò)廣告投放渠道有哪些
文章目錄
- 一、關(guān)于 langid
- 二、基本使用
- Normalization
- 多個語言中選擇一個
- 三、訓(xùn)練模型
- 1、需要
- 2、工具是
- 3、過程
- 4、代碼調(diào)用自定義模型
一、關(guān)于 langid
https://github.com/saffsd/langid.py
用于檢測語言
二、基本使用
import langidlangid.classify("This is a test")
('en', -54.41310358047485)
Normalization
可以使用 0–1 之間的數(shù)據(jù)來衡量
from langid.langid import LanguageIdentifier, model
identifier = LanguageIdentifier.from_modelstring(model, norm_probs=True)identifier.classify("This is a test")
# ('en', 0.9999999909903544)
多個語言中選擇一個
上述方式,很多時候存在語言不準(zhǔn)的情況,可以設(shè)置默認(rèn)語言,讓 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','??????????????????????????????????','得親密。','由泰國當(dāng)紅男星"film" Rattapoom Toekongsap和泰國超模']for str in arr:print(identifier.classify(str))
三、訓(xùn)練模型
1、需要
1、單語文檔語料庫
2 層深的文件夾層次結(jié)構(gòu):域 – 語言類型 – 文檔文件
每個文檔應(yīng)該是一個單獨的文件,每個文件應(yīng)該在一個 2 層深的文件夾層次結(jié)構(gòu)中,語言嵌套在域中。
./corpus/domain1/en/File1.txt
./corpus/domainX/en/001-file.xml
2、工具是
- index.py - 索引語料庫。生成文件、語料庫、語言對的列表。
- tokenize.py - 獲取索引并
標(biāo)記
相應(yīng)的文件 - DFfeatureselect.py - 按文檔頻率選擇
特征
- IGweight.py - 計算語言和領(lǐng)域的 IG 權(quán)重
- LDfeatureselect.py - 獲取 IG 權(quán)重并使用它們來選擇一個特征集
- scanner.py - 基于功能集構(gòu)建掃描儀
- NBtrain.py - 使用索引語料庫和掃描儀學(xué)習(xí) NB 參數(shù)
3、過程
1、索引
$ python index.py ./corpus
2、標(biāo)記
python tokenize.py corpus.model
3、識別最頻繁的標(biāo)記
通過文檔頻率識別最頻繁的標(biāo)記
python DFfeatureselect.py corpus.model
4、計算每個頂級特征的 IG 權(quán)重
以下兩個都需要執(zhí)行
python IGweight.py -d corpus.model
python IGweight.py -lb corpus.model
5、計算每個令牌的 LD 分?jǐn)?shù)
python LDfeatureselect.py corpus.model
這將生成用于構(gòu)建 NB 模型的 LD 特征的最終列表。
6、組裝掃描儀
python scanner.py corpus.model
掃描儀是對特征集的編譯 DFA,可用于計算文檔中每個特征在單次遍歷文檔中出現(xiàn)的次數(shù)。此 DFA 是使用 Aho-Corasick 字符串匹配構(gòu)建的。
7、樸素貝葉斯參數(shù)
最后,我們學(xué)習(xí)實際的樸素貝葉斯參數(shù):
python NBtrain.py corpus.model
4、代碼調(diào)用自定義模型
1)從指定位置加載模型,并進(jìn)行 normalize
identifier = LanguageIdentifier.from_modelpath(model_path, norm_probs=True)
model 本質(zhì)是一個長字符串
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