HanLP icon indicating copy to clipboard operation
HanLP copied to clipboard

按照《自然语言处理入门》随书代码复现时,发现自定义词典不能完全生效。

Open Lilydark opened this issue 6 years ago • 2 comments

注意事项

请确认下列注意事项:

  • 我已仔细阅读下列文档,都没有找到答案:
  • 我已经通过Google和issue区检索功能搜索了我的问题,也没有找到答案。
  • 我明白开源社区是出于兴趣爱好聚集起来的自由社区,不承担任何责任或义务。我会礼貌发言,向每一个帮助我的人表示感谢。
  • [x] 我在此括号内输入x打钩,代表上述事项确认完毕

版本号

当前最新版本号是:1.7.5 我使用的版本是:1.7.5

我的问题

我按照《自然语言处理入门》的随书代码进行3.4节内容的复现,在3.4.1的“预测”一节中,使用范例代码调用先前生成的语言模型,并生成对应的词频时,仅1-gram模型的词频统计有效,ngram(实际上是2gram)模型的词频统计无效。

复现问题

步骤

  1. 删除各词典缓存bin文件
  2. 把随书对应章节的范例代码写入Jupyter Notebook,期间未出现报错。
  3. 代码具体内容为:先加载自定义的简易语料库,然后创建NatureDictionaryMaker对象,训练得到并保存1gram与2gram模型为词典形式。然后重新调用这些模型时,输出却与实际不符,也不同于原书中的应有输出。

触发代码

import zipfile
import os
from pyhanlp import *
from pyhanlp.static import download, remove_file, HANLP_DATA_PATH


def test_data_path():
    """
    获取测试数据路径,位于$root/data/test,根目录由配置文件指定。
    :return:
    """
    data_path = os.path.join(HANLP_DATA_PATH, 'test')
    if not os.path.isdir(data_path):
        os.mkdir(data_path)
    return data_path


def ensure_data(data_name, data_url):
    root_path = test_data_path()
    dest_path = os.path.join(root_path, data_name)
    if os.path.exists(dest_path):
        return dest_path
    if data_url.endswith('.zip'):
        dest_path += '.zip'
    download(data_url, dest_path)
    if data_url.endswith('.zip'):
        with zipfile.ZipFile(dest_path, "r") as archive:
            archive.extractall(root_path)
        remove_file(dest_path)
        dest_path = dest_path[:-len('.zip')]
    return dest_path

def my_cws_corpus():
    data_root = test_data_path()
    corpus_path = os.path.join(data_root, 'my_cws_corpus.txt')
    if not os.path.isfile(corpus_path):
        with open(corpus_path, 'w', encoding='utf8') as out:
            out.write('''商品\t和\t服务
商品\t和服\t物美价廉
服务\t和\t货币''')
    return corpus_path

#CorpusLoader = SafeJClass('com.hankcs.hanlp.corpus.document.CorpusLoader')

def train_bigram(corpus_path, model_path):
    sents = CorpusLoader.convert2SentenceList(corpus_path) #加载语料库
    for sent in sents:
        for word in sent:
            word.setLabel('n') #标注
    maker = NatureDictionaryMaker()
    maker.compute(sents)
    maker.saveTxtTo(model_path)
    
def load_bigram(model_path):
    HanLP.Config.CoreDictionaryPath = model_path + '.txt' #1gram模型
    HanLP.Config.BiGramDictionaryPath = model_path + '.ngram.txt' #ngram模型
    CoreDictionary = SafeJClass('com.hankcs.hanlp.dictionary.CoreDictionary')
    CoreBiGramTableDictionary = SafeJClass('com.hankcs.hanlp.dictionary.CoreBiGramTableDictionary')
    print(CoreDictionary.getTermFrequency("商品")) # 获取对应词语的词频
    print(CoreBiGramTableDictionary.getBiFrequency("商品", "和")) #获取二元语法的频次

NatureDictionaryMaker = SafeJClass('com.hankcs.hanlp.corpus.dictionary.NatureDictionaryMaker')
CorpusLoader = SafeJClass('com.hankcs.hanlp.corpus.document.CorpusLoader')
WordNet = JClass('com.hankcs.hanlp.seg.common.WordNet')
Vertex = JClass('com.hankcs.hanlp.seg.common.Vertex')
ViterbiSegment = JClass('com.hankcs.hanlp.seg.Viterbi.ViterbiSegment')
DijkstraSegment = JClass('com.hankcs.hanlp.seg.Dijkstra.DijkstraSegment')
CoreDictionary = LazyLoadingJClass('com.hankcs.hanlp.dictionary.CoreDictionary')
Nature = JClass('com.hankcs.hanlp.corpus.tag.Nature')

corpus_path = my_cws_corpus()
model_path = os.path.join(test_data_path(), 'my_cws_model')
train_bigram(corpus_path, model_path)
load_bigram(model_path)

期望输出

2
1

实际输出

2
0

第二行的输出频数与实际不符,因为对应的词典my_cws_model.ngram.txt中的确记述了: 商品@和 1

因此输出的频数统计结果应当为1而不是0,这两个词也均在1gram模型词典中有出现,应当不是这方面的原因。

其他信息

使用的自定义词典都是由maker.saveTxtTo(model_path)得到的,未做任何改动。 如果ngram模型并不调用这个自定义词典,而是使用自带的词典,则词频统计并无问题 如果ngram词典中出现了1gram不曾出现的词,则其词频统计也会是0,但是我遇到的情况不属于此类。 我的系统是Windows10,语言环境为Python 3.7.4 anaconda环境 ngram模型生成的缓存文件:my_cws_model.ngram.txt.table.bin大小仅有1kb,我不清楚这是否正常

Lilydark avatar Dec 24 '19 11:12 Lilydark

https://github.com/hankcs/HanLP/issues/1320

hankcs avatar Dec 24 '19 17:12 hankcs

已生效,十分感谢。 很抱歉没有详细确认Issue中已有类似提问。

Lilydark avatar Dec 25 '19 01:12 Lilydark