Keras学习之一:文本与序列预处理

来源:互联网 发布:淘宝聊天记录怎么查 编辑:程序博客网 时间:2024/06/06 05:02

1 简介

在进行自然语言处理之前,需要对文本进行处理。
本文介绍keras提供的预处理包keras.preproceing下的text与序列处理模块sequence模块

2 text模块提供的方法

  • text_to_word_sequence(text,fileter) 可以简单理解此函数功能类str.split
  • one_hot(text,vocab_size) 基于hash函数(桶大小为vocab_size),将一行文本转换向量表示

3 text.Tokenizer类

这个类用来对文本中的词进行统计计数,生成文档词典,以支持基于词典位序生成文本的向量表示。
init(num_words) 构造函数,传入词典的最大值

3.1 成员函数

  • fit_on_text(texts) 使用一系列文档来生成token词典,texts为list类,每个元素为一个文档。
  • texts_to_sequences(texts) 将多个文档转换为word下标的向量形式,shape为[len(texts),len(text)]
  • texts_to_matrix(texts) 将多个文档转换为矩阵表示,shape为[len(texts),num_words]

3.2 成员变量

  • document_count 处理的文档数量
  • word_index 一个dict,保存所有word对应的编号id,从1开始
  • word_counts 一个dict,保存每个word在所有文档中出现的次数
  • word_docs 一个dict,保存每个word出现的文档的数量
  • index_docs 一个dict,保存word的id出现的文档的数量

3.3 示例

import keras.preprocessing.text as Tfrom keras.preprocessing.text import Tokenizertext1='some thing to eat'text2='some thing to drink'texts=[text1,text2]print T.text_to_word_sequence(text1)  #['some', 'thing', 'to', 'eat']print T.one_hot(text1,10)  #[7, 9, 3, 4]print T.one_hot(text2,10)  #[7, 9, 3, 1]tokenizer = Tokenizer(num_words=10)tokenzier.fit_on_text(texts)print tokenizer.word_count #[('some', 2), ('thing', 2), ('to', 2), ('eat', 1), ('drink', 1)]print tokenizer.word_index #{'some': 1, 'thing': 2,'to': 3 ','eat': 4, drink': 5}print tokenizer.word_docs #{'some': 2, 'thing': 2, 'to': 2, 'drink': 1,  'eat': 1}print tokenizer.index_docs #{1: 2, 2: 2, 3: 2, 4: 1, 5: 1}print tokenizer.text_to_sequences(texts) #[[1, 2, 3, 4], [1, 2, 3, 5]]print tokenizer.text_to_matrix(texts) #[[ 0.,  1.,  1.,  1.,  1.,  0.,  0.,  0.,  0.,  0.], [ 0.,  1.,  1.,  1.,  0.,  1.,  0.,  0.,  0.,  0.]]

4 sequence模块

4.1 模块提供的方法

  • pad_sequences(sequences, maxlen, padding=’pre’, truncating=’pre’, value=0.) 将序列填充到maxlen长度,padding取值有pre|post,value指定用何值填充的值

4.2 示例

import keras.preprocessing.sequence as SS.pad_sequences([[1,2,3]],10,padding='post')# [[1, 2, 3, 0, 0, 0, 0, 0, 0, 0]]
原创粉丝点击