未经允许不可转载

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行的

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

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

  1. #ifdef WITH_NPLM
  2. } else if (lm::np::Model::Recognize(file)) {
  3. lm::np::Model model(file);
  4. if (show_words) {
  5. Query<lm::np::Model, lm::ngram::FullPrint>(model, sentence_context);
  6. } else {
  7. Query<lm::np::Model, lm::ngram::BasicPrint>(model, sentence_context);
  8. }
  9. #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文件

  1. from libcpp.string cimport string
  2. cdef extern from "lm/word_index.hh":
  3. ctypedef unsigned WordIndex
  4. cdef extern from "lm/return.hh" namespace "lm":
  5. cdef struct FullScoreReturn:
  6. float prob
  7. unsigned char ngram_length
  8. cdef extern from "lm/state.hh" namespace "lm::ngram":
  9. cdef struct State:
  10. pass
  11. ctypedef State const_State "const lm::ngram::State"
  12. cdef extern from "lm/virtual_interface.hh" namespace "lm::base":
  13. cdef cppclass Vocabulary:
  14. WordIndex Index(char*)
  15. WordIndex BeginSentence()
  16. WordIndex EndSentence()
  17. WordIndex NotFound()
  18. ctypedef Vocabulary const_Vocabulary "const lm::base::Vocabulary"
  19. cdef extern from "lm/model.hh" namespace "lm::ngram":
  20. cdef cppclass Model:
  21. const_Vocabulary& GetVocabulary()
  22. const_State& NullContextState()
  23. void Model(char* file)
  24. FullScoreReturn FullScore(const_State& in_state, WordIndex new_word, const_State& out_state)
  25. void BeginSentenceWrite(void *)
  26. void NullContextWrite(void *)
  27. unsigned int Order()
  28. const_Vocabulary& BaseVocabulary()
  29. float BaseScore(void *in_state, WordIndex new_word, void *out_state)
  30. FullScoreReturn BaseFullScore(void *in_state, WordIndex new_word, void *out_state)
  31. void * NullContextMemory()

扩展后的kenlm.pyx文件

  1. import os
  2. cdef bytes as_str(data):
  3. if isinstance(data, bytes):
  4. return data
  5. elif isinstance(data, unicode):
  6. return data.encode('utf8')
  7. raise TypeError('Cannot convert %s to string' % type(data))
  8. cdef int as_in(int &Num):
  9. (&Num)[0] = 1
  10. cdef class LanguageModel:
  11. cdef Model* model
  12. cdef public bytes path
  13. cdef const_Vocabulary* vocab
  14. def __init__(self, path):
  15. self.path = os.path.abspath(as_str(path))
  16. try:
  17. self.model = new Model(self.path)
  18. except RuntimeError as exception:
  19. exception_message = str(exception).replace('\n', ' ')
  20. raise IOError('Cannot read model \'{}\' ({})'.format(path, exception_message))\
  21. from exception
  22. self.vocab = &self.model.GetVocabulary()
  23. def __dealloc__(self):
  24. del self.model
  25. property order:
  26. def __get__(self):
  27. return self.model.Order()
  28. def score(self, sentence):
  29. cdef list words = as_str(sentence).split()
  30. cdef State state
  31. self.model.BeginSentenceWrite(&state)
  32. cdef State out_state
  33. cdef float total = 0
  34. for word in words:
  35. total += self.model.BaseScore(&state, self.vocab.Index(word), &out_state)
  36. state = out_state
  37. total += self.model.BaseScore(&state, self.vocab.EndSentence(), &out_state)
  38. return total
  39. def full_scores(self, sentence):
  40. cdef list words = as_str(sentence).split()
  41. cdef State state
  42. self.model.BeginSentenceWrite(&state)
  43. cdef State out_state
  44. cdef FullScoreReturn ret
  45. cdef float total = 0
  46. for word in words:
  47. ret = self.model.BaseFullScore(&state,
  48. self.vocab.Index(word), &out_state)
  49. yield (ret.prob, ret.ngram_length)
  50. state = out_state
  51. ret = self.model.BaseFullScore(&state,
  52. self.vocab.EndSentence(), &out_state)
  53. yield (ret.prob, ret.ngram_length)
  54. def full_scores_n(self, sentence):
  55. cdef list words = as_str(sentence).split()
  56. cdef State state
  57. state = self.model.NullContextState()
  58. cdef State out_state
  59. cdef FullScoreReturn ret
  60. cdef int ovv = 0
  61. for word in words:
  62. ret = self.model.FullScore(state,
  63. self.vocab.Index(word), out_state)
  64. yield (ret.prob, ret.ngram_length)
  65. state = out_state
  66. """""""""""
  67. """count scores when not included <s> and </s>"""
  68. """""""""""
  69. def score_n(self, sentence):
  70. cdef list words = as_str(sentence).split()
  71. cdef State state
  72. state = self.model.NullContextState()
  73. cdef State out_state
  74. cdef float total = 0
  75. for word in words:
  76. ret = self.model.FullScore(state,
  77. self.vocab.Index(word), out_state)
  78. total += ret.prob
  79. """print(total)"""
  80. state = out_state
  81. return total
  82. def __contains__(self, word):
  83. cdef bytes w = as_str(word)
  84. return (self.vocab.Index(w) != 0)
  85. def __repr__(self):
  86. return '<LanguageModel from {0}>'.format(os.path.basename(self.path))
  87. def __reduce__(self):
  88. 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. Linux c- libevent

    libevent是一个事件触发的网络库,适用于windows.linux.bsd等多种平台,内部使用select.epoll.kqueue等系统调用管理事件机制.著名分布式缓存软件memcached也 ...

  2. Tomcat 8.5 架构分析

    官方文档:Apache Tomcat 8 Architecture 以下分析的是 Version 8.5. Tomcat 组件关系图 根据 Architecture Overview 绘制: Serv ...

  3. 数据结构与算法JavaScript描述——队列

    注:澄清一个bug: /** * 删除队首的元素: */ function dequeue(){ return this.dataStore.shift(); } 应该有return:   队列是一种 ...

  4. java代码----数据类型的转换-----int --->String

    总结:int ----->String package com.a.b; //测试..char--->int // int--->String public class Yue2 { ...

  5. python稀疏矩阵得到每列最大k项的值,对list内为类对象的排序(scipy.sparse.csr.csr_matrix)

    print(train_set.tdm) print(type(train_set.tdm)) 输出得到: (0, 3200) 0.264940780338 (0, 1682) 0.356545827 ...

  6. ApacheOFBiz的相关介绍以及使用总结(三)

    Ofbiz中还提供了一些基础性服务,可以直接用来使用,下面就简单介绍说明一下.   ofbiz邮件发送服务   ofbiz中提供发送邮件相关功能:sendMailFromScreen   contex ...

  7. hdu-1052-Tian Ji -- The Horse Racing(经典)

    /* hdu-1052 Tian Ji -- The Horse Racing Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/3 ...

  8. Cisco交换机配置VLAN与TRUNK

    0x00前言: 今日在学校里学习了如何搭建vlan和配置等等还有trunk. 由于快下课了.尽快写. 0x01准备: Cisco模拟器 0x02正文: 要求: VLAN 10 左边的IP:192.16 ...

  9. How To Move a MySQL Data Directory to a New Location on Ubuntu 16.04

    16 How To Move a MySQL Data Directory to a New Location on Ubuntu 16.04 PostedJuly 21, 2016 62.1kvie ...

  10. Android屏幕适配方案——基于最小宽度(Smallest-width)限定符

    转自:https://www.cnblogs.com/error404/p/3815739.html 一.关于布局适配建议 1.不要使用绝对布局 2.尽量使用match_parent 而不是fill_ ...