未经允许不可转载

Kenlm相关知识

Kenlm下载地址

kenlm中文版本训练语言模型

如何使用kenlm训练出来的模型C++版本

关于Kenlm模块的使用及C++源码说明

加载Kenlm模块命令

qy@IAT-QYVPN:~/Documents/kenlm/lm$ ../bin/query -n test.arpa


Kenlm模块C++源码说明

query的主入口文件:query_main.cc

query的执行函数文件:ngram_query.hh

注意:

默认执行的是query_main.cc文件96行的

Query<ProbingModel>(file, config, sentence_context, show_words);

而不是lm/wrappers/nplm.hh,这个封装文件是需要NPLM模块的,参考以下代码,当时疏忽了在这个地方耽误了一些时间

#ifdef WITH_NPLM
} else if (lm::np::Model::Recognize(file)) {
lm::np::Model model(file);
if (show_words) {
Query<lm::np::Model, lm::ngram::FullPrint>(model, sentence_context);
} else {
Query<lm::np::Model, lm::ngram::BasicPrint>(model, sentence_context);
}
#endif

关于Model类的继承关系

  • 最基类virtual_interface.hh lm::base::Model
  • 次基类facade.hh lm::base::ModelFacade : public Model
  • 子类model.hh lm::ngram::GenericModel : public base::ModelFacade<GenericModel<Search, VocabularyT>, State, VocabularyT>

关于cython的简单说明

cython官网

可以从官网下载最新版本,参考Documentation分类中的Cython Wiki和Cython FAQ了解一些知识。

cython-cpp-test-sample

Wrapping C++ Classes in Cython

cython wrapping of base and derived class

std::string arguments in cython

Cython and constructors of classes

Cython基础--Cython入门

kenlm的python模块封装

接下来,让我们进入正题,在kenlm的源码中实际上已经提供了python的应用。在kenlm/python文件夹中,那么为什么还要再封装python模块呢,因为kenlm中所带的python模块仅仅实现了包含<s>和</s>这种情况下的计算分数的方法,而没有提供不包含这种情况的计算分数的算法,这就是为什么要重新封装python模块的原因。

简单介绍一下python模块使用的必要步骤

  • 安装kenlm.so模块到python的目录下,默认直接运行kenlm目录下的setup.py文件即可安装成功sudo python setup.py install --record log
  • 安装成功后,即可运行python example.py文件,查看运行结果。

如何扩展kenlm的python模块

接下来,正式进入python扩展模块的介绍。kenlm.pxd是cython针对所用到C++类及对象的声明文件,kenlm.pyx是真正要编写的cython功能代码,也是未来python所要调用的类及方法。使用cython的编译命令,可以把kenlm.pxdkenlm.pyx编译出kenlm.cpp文件。setup.py文件会用到编译出来的kenlm.cpp文件。

  • cython编译命令cython --cplus kenlm.pyx

扩展后的kenlm.pxd文件

from libcpp.string cimport string

cdef extern from "lm/word_index.hh":
ctypedef unsigned WordIndex cdef extern from "lm/return.hh" namespace "lm":
cdef struct FullScoreReturn:
float prob
unsigned char ngram_length cdef extern from "lm/state.hh" namespace "lm::ngram":
cdef struct State:
pass ctypedef State const_State "const lm::ngram::State" cdef extern from "lm/virtual_interface.hh" namespace "lm::base":
cdef cppclass Vocabulary:
WordIndex Index(char*)
WordIndex BeginSentence()
WordIndex EndSentence()
WordIndex NotFound() ctypedef Vocabulary const_Vocabulary "const lm::base::Vocabulary" cdef extern from "lm/model.hh" namespace "lm::ngram":
cdef cppclass Model:
const_Vocabulary& GetVocabulary()
const_State& NullContextState()
void Model(char* file)
FullScoreReturn FullScore(const_State& in_state, WordIndex new_word, const_State& out_state) void BeginSentenceWrite(void *)
void NullContextWrite(void *)
unsigned int Order()
const_Vocabulary& BaseVocabulary()
float BaseScore(void *in_state, WordIndex new_word, void *out_state)
FullScoreReturn BaseFullScore(void *in_state, WordIndex new_word, void *out_state)
void * NullContextMemory()

扩展后的kenlm.pyx文件

import os

cdef bytes as_str(data):
if isinstance(data, bytes):
return data
elif isinstance(data, unicode):
return data.encode('utf8')
raise TypeError('Cannot convert %s to string' % type(data)) cdef int as_in(int &Num):
(&Num)[0] = 1 cdef class LanguageModel:
cdef Model* model
cdef public bytes path
cdef const_Vocabulary* vocab def __init__(self, path):
self.path = os.path.abspath(as_str(path))
try:
self.model = new Model(self.path)
except RuntimeError as exception:
exception_message = str(exception).replace('\n', ' ')
raise IOError('Cannot read model \'{}\' ({})'.format(path, exception_message))\
from exception
self.vocab = &self.model.GetVocabulary() def __dealloc__(self):
del self.model property order:
def __get__(self):
return self.model.Order() def score(self, sentence):
cdef list words = as_str(sentence).split()
cdef State state
self.model.BeginSentenceWrite(&state)
cdef State out_state
cdef float total = 0
for word in words:
total += self.model.BaseScore(&state, self.vocab.Index(word), &out_state)
state = out_state
total += self.model.BaseScore(&state, self.vocab.EndSentence(), &out_state)
return total def full_scores(self, sentence):
cdef list words = as_str(sentence).split()
cdef State state
self.model.BeginSentenceWrite(&state)
cdef State out_state
cdef FullScoreReturn ret
cdef float total = 0
for word in words:
ret = self.model.BaseFullScore(&state,
self.vocab.Index(word), &out_state)
yield (ret.prob, ret.ngram_length)
state = out_state
ret = self.model.BaseFullScore(&state,
self.vocab.EndSentence(), &out_state)
yield (ret.prob, ret.ngram_length) def full_scores_n(self, sentence):
cdef list words = as_str(sentence).split()
cdef State state
state = self.model.NullContextState()
cdef State out_state
cdef FullScoreReturn ret
cdef int ovv = 0
for word in words:
ret = self.model.FullScore(state,
self.vocab.Index(word), out_state)
yield (ret.prob, ret.ngram_length)
state = out_state """""""""""
"""count scores when not included <s> and </s>"""
"""""""""""
def score_n(self, sentence):
cdef list words = as_str(sentence).split()
cdef State state
state = self.model.NullContextState()
cdef State out_state
cdef float total = 0
for word in words:
ret = self.model.FullScore(state,
self.vocab.Index(word), out_state)
total += ret.prob
"""print(total)"""
state = out_state
return total def __contains__(self, word):
cdef bytes w = as_str(word)
return (self.vocab.Index(w) != 0) def __repr__(self):
return '<LanguageModel from {0}>'.format(os.path.basename(self.path)) def __reduce__(self):
return (LanguageModel, (self.path,))

【原创】cython and python for kenlm的更多相关文章

  1. 用Cython加速Python程序以及包装C程序简单测试

    用Cython加速Python程序 我没有拼错,就是Cython,C+Python=Cython! 我们来看看Cython的威力,先运行下边的程序: import time def fib(n): i ...

  2. 原创:用python把链接指向的网页直接生成图片的http服务及网站(含源码及思想)

    原创:用python把链接指向的网页直接生成图片的http服务及网站(含源码及思想) 总体思想:     希望让调用方通过 http调用传入一个需要生成图片的网页链接生成一个网页的图片并返回图片链接 ...

  3. 用Cython加速Python代码

    安装Cython pip install Cython 如何使用 要在我们的笔记本中使用Cython,我们将使用IPython magic命令.Magic命令以百分号开始,并提供一些额外的功能,这些功 ...

  4. Cython保护Python代码

    注:.pyc也有一定的保护性,容易被反编译出源码... 项目发布时,为防止源码泄露,需要对源码进行一定的保护机制,本文使用Cython将.py文件转为.so进行保护.这一方法,虽仍能被反编译,但难度会 ...

  5. 利用Cython对python代码进行加密

    利用Cython对python代码进行加密 Cython是属于PYTHON的超集,他首先会将PYTHON代码转化成C语言代码,然后通过c编译器生成可执行文件.优势:资源丰富,适合快速开发.翻译成C后速 ...

  6. 使用cython把python编译so

    1.需求 为了保证线上代码安全和效率,使用python编写代码,pyc可直接反编译,于是把重要代码编译so文件 2.工作 2.1 安装相关库: pip install cython yum insta ...

  7. 用cython提升python的性能

    Boosting performance with Cython     Even with my old pc (AMD Athlon II, 3GB ram), I seldom run into ...

  8. 【原创分享】python获取乌云最新提交的漏洞,邮件发送

    #!/usr/bin/env python # coding:utf-8 # @Date : 2016年4月21日 15:08:44 # @Author : sevck (sevck@jdsec.co ...

  9. [原创博文] 用Python做统计分析 (Scipy.stats的文档)

    [转自] 用Python做统计分析 (Scipy.stats的文档) 对scipy.stats的详细介绍: 这个文档说了以下内容,对python如何做统计分析感兴趣的人可以看看,毕竟Python的库也 ...

随机推荐

  1. (转)Inno Setup入门(二十)——Inno Setup类参考(6)

    本文转载自:http://blog.csdn.net/yushanddddfenghailin/article/details/17251041 存储框 存储框也是典型的窗口可视化组件,同编辑框类似, ...

  2. bzoj 1023: [SHOI2008]cactus仙人掌图 2125: 最短路 4728: 挪威的森林 静态仙人掌上路径长度的维护系列

    %%% http://immortalco.blog.uoj.ac/blog/1955 一个通用的写法是建树,对每个环建一个新点,去掉环上的边,原先环上每个点到新点连边,边权为点到环根的最短/长路长度 ...

  3. print 和 println的区别

    println 输出字符后,下一个输出的字符会换行展示 print 输出字符后,下一个输出字符不会会换展示

  4. oozie工作流相关入门整理

        Oozie支持工作流,其定义通过将多个Hadoop Job的定义按照一定的顺序组织起来,然后作为一个整体按照既定的路径运行.一个工作流已经定义了,通过启动该工作流Job,就会执行该工作流中包含 ...

  5. Hive语句执行优化-简化UDF执行过程

      Hive会将执行的SQL语句翻译成对应MapReduce任务,当SQL语句比较简单时,性能还是可能处于可接受的范围.但是如果涉及到非常复杂的业务逻辑,特别是通过程序的方式(一些模版语言生成)生成大 ...

  6. Visual Studio Online 删除项目

    TFS Online在经过一段很长时间的预览阶段后,现在已经改名成Visual Studio Online(简称VS Online),正式成为微软的开发测试云在线服务.撸主最近在上面建了几个测试项目玩 ...

  7. Nginx加状态监控

    安装Nginx时加上        –with-http_stub_status_module 在nginx.conf server location /nginx_status { stub_sta ...

  8. js中的web加密

    js中的web加密 window.crypto.subtle只会在安全模式下有用,也就是https环境下 创建摘要(硬解) var i = new TextEncoder('utf-8').encod ...

  9. centos 安装php7

    yum安装php7 删除之前的版本 # yum remove php* rpm 安装 Php7 相应的 yum源 CentOS/RHEL 7.x: # rpm -Uvh https://dl.fedo ...

  10. Python if判断语句

    a=input('输入你的用户名:') if a == "lilei": print('李磊,等你好久了') elif a == "wanghui": prin ...