zoukankan      html  css  js  c++  java
  • Keras文本预处理

    学习了Keras文档里的文本预处理部分,参考网上代码写了个例子

     1 import keras.preprocessing.text as T
     2 from keras.preprocessing.text import Tokenizer
     3 
     4 text1='some thing to eat'
     5 text2='some thing to drink'
     6 texts=[text1,text2]
     7 
     8 #文本到文本列表
     9 print (T.text_to_word_sequence(text1))  #以空格区分,中文也不例外 ['some', 'thing', 'to', 'eat']
    10 
    11 #文本的ont-hot编码
    12 print (T.one_hot(text1,10))  #[7, 9, 3, 4] -- (10表示数字化向量为10以内的数字)
    13 print (T.one_hot(text2,10))  #[7, 9, 3, 1]
    14 
    15 tokenizer = Tokenizer(num_words=None) #num_words:None或整数,处理的最大单词数量。少于此数的单词丢掉
    16 tokenizer.fit_on_texts(texts)
    17 
    18 #word_counts:字典,将单词(字符串)映射为它们在训练期间出现的次数。仅在调用fit_on_texts之后设置。
    19 print( tokenizer.word_counts) #[('some', 2), ('thing', 2), ('to', 2), ('eat', 1), ('drink', 1)]
    20 
    21 #word_index: 字典,将单词(字符串)映射为它们的排名或者索引。仅在调用fit_on_texts之后设置
    22 print( tokenizer.word_index) #{'some': 1, 'thing': 2,'to': 3 ','eat': 4, drink': 5}
    23 
    24 #word_docs: 字典,将单词(字符串)映射为它们在训练期间所出现的文档或文本的数量。仅在调用fit_on_texts之后设置。
    25 print( tokenizer.word_docs) #{'some': 2, 'thing': 2, 'to': 2, 'drink': 1,  'eat': 1}
    26 
    27 
    28 print( tokenizer.index_docs) #{1: 2, 2: 2, 3: 2, 4: 1, 5: 1}
    29 
    30 # num_words=多少会影响下面的结果,行数=num_words
    31 
    32 #序列的列表,列表中每个序列对应于一段输入文本
    33 print( tokenizer.texts_to_sequences(texts)) #得到词索引[[1, 2, 3, 4], [1, 2, 3, 5]]
    34 #形如(len(sequences), nb_words)的numpy array
    35 print( tokenizer.texts_to_matrix(texts))  # 矩阵化=one_hot
    36 '''
    37 [[ 0.,  1.,  1.,  1.,  1.,  0.,  0.,  0.,  0.,  0.],
    38  [ 0.,  1.,  1.,  1.,  0.,  1.,  0.,  0.,  0.,  0.]]
    39  '''
  • 相关阅读:
    mybatis学习成长之路(一)
    badboy页面脚本发生错误,解决方案
    资料下载地址大全
    excel2003和excel2007文件的创建和读取
    文件的上传下载
    读取.properties的内容1
    Java的垃圾回收机制
    Bell数和Stirling数
    Catalan数计算及应用
    [算法]循环赛日程表
  • 原文地址:https://www.cnblogs.com/cnXuYang/p/8858874.html
Copyright © 2011-2022 走看看