当前位置:   article > 正文

【PaddlePaddle】自然语言处理:句词预测

词语预测是自然语言处理的一个重要领域,请对词语预测这个概念进行定义,并对其

前言

预测词汇的相关性算是自然语言中的HelloWolrd。本文主要根据百度PaddlePaddle示例word2vec,对句子中下一个单词的预测。该示例使用4个词语来预测下一个词。

 

1. 数据集以及字典、Reader构建

示例采用Penn Treebank (PTB)数据集(经Tomas Mikolov预处理过的版本),直接使用数据集中的data文件夹下的ptb.train.txt和ptb.test.txt即可。这两个文件是英语语句组成的训练集,所以直接读取文件再用split将句子分开既可以得到单词列表。

单词是不定长的,所以往往将单词映射为一个序号。例如'a'用1表示,‘an’用2表示等等。这样以来我们就必须构建字典,然后对字典中的单词进行编号。示例使用了训练集和数据集制作字典,同时统计单词出现的次数,设置了min_word_freq来对出现次数少的单词进行剔除。

def word_count(f, word_freq=None):
    if word_freq is None:
        word_freq = collections.defaultdict(int)
    for l in f:
        for w in l.strip().split(): #删除前后端空格,并且切分单词,每个单词计数
            word_freq[w] += 1
        word_freq['<s>'] += 1
        word_freq['<e>'] += 1
    return word_freq

def build_dict(data_path,min_word_freq=50):
    """
    构建字典
    """
    train_filename = './simple-examples/data/ptb.train.txt'
    test_filename  = './simple-examples/data/ptb.valid.txt'
    with tarfile.open(data_path) as tf:
        trainf = tf.extractfile(train_filename)
        testf = tf.extractfile(test_filename)
        word_freq = word_count(testf, word_count(trainf))
        if '<unk>' in word_freq:
            # remove <unk> for now, since we will set it as last index
            del word_freq['<unk>']
        word_freq = filter(lambda x: x[1] > min_word_freq, word_freq.items()) #滤除掉小于min_word的单词
        word_freq_sorted
声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号