用tensorflow快速创建语料库词汇索引的方法

前言

在写 快速搭建垃圾分类智能问答机器人 时,发现使用词向量训练模型准确率仅有70左右,考虑了几点问题:一是数字类、英文类的词没有对应的词向量;二是训练语料太少了(百级),导致词向量优势体现不出来。故增加一种词索引的表示方法。

下面介绍用tensorflow快速创建语料库词汇索引的方法

用tensorflow快速创建语料库词汇索引

  • 功能
    建立词汇表和word到index,及index到word的map,这就需要统计词汇表中的所有单词并建立相应的词典。

  • api
    tensorflow.contrib.learn.preprocessing.VocabularyProcessor(
               max_document_length,
                min_frequency=0,
                vocabulary=None,
                tokenizer_fn=None)
     函数有4个参数:
    max_document_length:文档的最大长度。如果文本的长度大于最大长度,那么它会被剪切,反之则用0填充
    min_frequency:词频的最小值,出现次数>最小词频 的词才会被收录到词表中
    vocabulary:词典对象
    tokenizer_fn:分词函数,如:list、jieba等

    (VocabularyProcessor:Maps documents to sequences of word ids)

  • 从语料库中创建词汇映射表

代码示例:

from tensorflow.contrib.learn import preprocessing
import numpy as np

def test():
    text_list = ['苹果 是 什么 垃圾', '塑料瓶 是 那种 垃圾']#先用结巴分好词
    max_words_length = 10
    vocab_processor = preprocessing.VocabularyProcessor(max_document_length=max_words_length)
    x = np.array(list(vocab_processor.fit_transform(text_list)))

    print('x:\n', x)

    print('词-索引映射表:\n', vocab_processor.vocabulary_._mapping)

    print('词汇表:\n', vocab_processor.vocabulary_._reverse_mapping)


    #保存vocabulary
    vocab_processor.save('vocab.pkl')

test()

输出结果:

x:
	 [[1 2 3 4 0 0 0 0 0 0]
	 [5 2 6 4 0 0 0 0 0 0]]
词-索引映射表:
 	{'垃圾': 4, '那种': 6, '塑料瓶': 5, '苹果': 1, '什么': 3, '是': 2, '<UNK>': 0}
词汇表:
	 ['<UNK>', '苹果', '是', '什么', '垃圾', '塑料瓶', '那种']
  • 使用词汇映射表

1、先加载 vocab.pkl
2、再把文本转为index表示

示例代码:

from tensorflow.contrib.learn import preprocessing
import numpy as np

def get_text_idx(text_list, vocab, max_words_length):
    text_array = np.zeros([len(text_list),  max_words_length], dtype=np.int32)

    for i, x in  enumerate(text_list):
        words = x.split(" ")
        for j,  w in enumerate(words):
            if w in vocab:
                text_array[i,  j] = vocab[w]
            else :
                text_array[i,  j] = vocab['<UNK>']

    return text_array

def  test2():
    #加载词汇映射表
    vocabulary = preprocessing.VocabularyProcessor.restore('vocab.pkl')
    
    max_words_length = 10
    text_list2 = ['苹果 属于 那种 ?', '塑料瓶 是 ?']
    x2 = get_text_idx(text_list2, vocabulary.vocabulary_._mapping, max_words_length)
    print('x2:\n', x2)
    
test2()

输出结果:

x2:
 [[1 0 6 0 0 0 0 0 0 0]
 [5 2 0 0 0 0 0 0 0 0]]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

szZack

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值