Tensorflow圖像生成文本(2)詞表詞頻的構建

前言

瞭解了Tensorflow圖像生成文本實現(1)flickr30k數據集介紹數據集之後,需要對其中的token文件進行解析,對數據進行初步處理。

詞表詞頻構建

因爲是一句句的描述,因此需要進行分詞,並統計出每個詞的詞頻,將其對應的儲存在一個文件中。這個文件的作用有兩個:

  1. 在後序程序中,需要中該詞表文件中讀取內容,組成兩個字典,一個是從文字到文字id的映射,另一個是從文字id到文字的映射。
  2. 通過詞頻,可以將詞頻過低的詞直接去掉,這些詞對模型的訓練貢獻率非常低,所以就排除掉。

代碼如下

import os
import sys
import pprint

input_description_file = "./data/results_20130124.token"
output_vocab_file = "./data/vocab.txt"

def count_vocab(input_description_file):
    with open(input_description_file) as f:
        lines = f.readlines()
    max_length_of_sentences = 0 # 所有句子中 最長長度
    length_dict = {} # 統計 句子長度字典 {長度:句子總數}
    vocab_dict = {} # 詞表字典 {詞:詞頻}
    for line in lines:
        image_id, description = line.strip('\n').split('\t')
        words = description.strip(' ').split() # 分詞
        # words 的 格式 ['Two', 'young', 'guys', 'with', 'shaggy', 'hair', ……]

        max_length_of_sentences = max(max_length_of_sentences, len(words)) # 選擇一個最大值放入
        length_dict.setdefault(len(words), 0)
        length_dict[len(words)] += 1

        # 詞表 統計
        for word in words:
            vocab_dict.setdefault(word, 0)
            vocab_dict[word] += 1

    print(max_length_of_sentences)
    pprint.pprint(length_dict)
    return vocab_dict

vocab_dict = count_vocab(input_description_file)
sorted_vocab_dict = sorted(vocab_dict.items(), key = lambda d:d[1], reverse=True) #對 詞表進行排序

with open(output_vocab_file, 'w') as f:
    f.write('<UNK>\t1000000\n')
    for item in sorted_vocab_dict:
        f.write('%s\t%d\n' % item)

生成的詞表格式如下:

<UNK>	1000000
a	181627
.	151039
A	90071
in	83224
the	57402
on	45538
and	44253
is	41108
man	40277
of	38773
with	36171
,	25285
woman	21236
are	20189
to	17603
Two	16446
at	16157
wearing	15694
people	14148
white	13039
shirt	12975
black	12084
young	12021
while	11650
his	11489
blue	11268
an	11119
red	9857
sitting	9608
...
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章