Tensor2Tensor使用入門

1. 簡介

Tensor2Tensor是google出品的一個神仙級工具包辣卒,能大大簡化類似模型的開發(fā)調試時間掷贾。在眾多的深度學習工具中,個人認為這貨屬于那種門檻還比較高的工具荣茫。并且google家的文檔一向做得很辣雞想帅,都是直接看源碼注釋摸索怎么使用。

Tensor2Tensor的版本和Tensorflow版本是對應的啡莉,我電腦上是tensorflow 1.14.0博脑,就這樣安裝了pip install tensor2tensor==1.14.1

2. 基礎模塊

import os
import tensorflow as tf

from tensor2tensor.utils import registry
from tensor2tensor.data_generators import text_encoder
from tensor2tensor.data_generators import problem
from tensor2tensor.data_generators.text_problems import Text2TextProblem
from tensor2tensor.data_generators.text_problems import VocabType
from tensor2tensor.models import transformer

text_encoder中預定義了一些把string轉化為ids的類型票罐。

problem不知道怎么說叉趣,看官方解釋就行了,反正新增加任務都需要自己寫個Problem類型该押。

Problems consist of features such as inputs and targets, and metadata such
as each feature's modality (e.g. symbol, image, audio) and vocabularies. Problem
features are given by a dataset, which is stored as a TFRecord file with tensorflow.Example protocol buffers. All
problems are imported in all_problems.py or are registered with @registry.register_problem.

這里是直接調用了models里面的transformers疗杉,如果自己該模型,還需要使用@registry.register_model注冊模型。

3. Problems寫法

最好看下Text2TextProblem模塊的源碼看下google的結構思路烟具,以文本生成任務為例梢什。

# 數(shù)據(jù)格式
想看你的美照<TAB>親我一口就給你看

我親兩口<TAB>討厭人家拿小拳拳捶你胸口
......

新建文件my_task.py

@registry.register_problem
class Seq2SeqDemo(Text2TextProblem):
    TRAIN_FILES = "train.txt"
    EVAL_FILES = "dev.txt"

    @property
    def vocab_type(self):
        # 見父類的說明

        return VocabType.TOKEN

    @property
    def oov_token(self):
        return "<UNK>"

    def _generate_vocab(self, tmp_dir):
        vocab_list = [self.oov_token]
        user_vocab_file = os.path.join(tmp_dir, "vocab.txt")
        with tf.gfile.GFile(user_vocab_file, "r") as vocab_file:
            for line in vocab_file:
                token = line.strip().split("\t")[0]
                vocab_list.append(token)
        token_encoder = text_encoder.TokenTextEncoder(None, vocab_list=vocab_list)
        return token_encoder

    def _generate_samples(self, data_dir, tmp_dir, dataset_split):
        del data_dir
        is_training = dataset_split == problem.DatasetSplit.TRAIN
        files = self.TRAIN_FILES if is_training else self.EVAL_FILES
        files = os.path.join(tmp_dir, files)
        with tf.gfile.GFile(files, "r") as fin:
            for line in fin:
                inputs, targets = line.strip().split("\t")
                yield {"inputs": inputs, "targets": targets}

    def generator_samples(self, data_dir, tmp_dir, dataset_split):
        vocab_filepath = os.path.join(data_dir, self.vocab_filename)
        if not tf.gfile.Exists(vocab_filepath):
            token_encoder = self._generate_vocab(tmp_dir)
            token_encoder.store_to_file(vocab_filepath)
        return self._generate_samples(data_dir, tmp_dir, dataset_split)

tmp_dir是真實的訓練文本和字典存放的地方,data_dir是處理后的字典和TFRcord存在的地方朝聋。

關鍵就一個方法generator_samples嗡午,它有兩個作用,讀入字典轉換數(shù)據(jù)文件方便后面轉化為TFRecord的形式冀痕。

其中有個天坑荔睹,generator_samples_generator_samples我是故意拆開寫的。如果合并了言蛇,因為生成器的性質僻他,在沒有遍歷之前generator_samplesreturn之前的代碼都不會執(zhí)行。但是注意到父類中有個有個方法generate_encoded_samples其中有兩行:

generator = self.generate_samples(data_dir, tmp_dir, dataset_split)
encoder = self.get_or_create_vocab(data_dir, tmp_dir)

generator_samples如果沒有執(zhí)行到token_encoder = self._generate_vocab(tmp_dir)腊尚,self.get_or_create_vocab這邊就直接炸了吨拗,找不到字典。因此婿斥,這兩個函數(shù)不能拆開劝篷,problem調用結構就這樣,暫時只知道這么改民宿。

最后娇妓,還要添加transformer的模型參數(shù),想了解參數(shù)請看transformer.transformer_base源碼(°ー°〃)勘高。

@registry.register_hparams
def my_param():
    hparams = transformer.transformer_base()
    hparams.summarize_vars = True
    hparams.num_hidden_layers = 4
    hparams.batch_size = 64
    hparams.max_length = 40
    hparams.hidden_size = 512
    hparams.num_heads = 8
    hparams.dropout = 0.1
    hparams.attention_dropout = 0.1
    hparams.filter_size = 1024
    hparams.layer_prepostprocess_dropout = 0.1
    hparams.learning_rate_warmup_steps = 1000
    hparams.learning_rate_decay_steps = 800
    hparams.learning_rate = 3e-5
    return hparams

4. 運行

首先生成TFRecod文件峡蟋,執(zhí)行命令

t2t_datagen \
    --t2t_usr_dir=/code_path (to my_task.py)
    --data_dir=/record_data_path
    --tmp_dir=/data_path
    --problem=Seq2SeqDemo

然后訓練

t2t_trainer \
    --data_dir=/same_as_above
    --problem=Seq2SeqDemo
    --model=transformer
    --hparams_set=my_param
    --output_dir=~/output_dir
    --job-dir=~/output_dir
    --train_steps=8000
    --eval_steps=2000

訓練好的模型進行預測(decode)

t2t_decoder \
    --data_dir=/same_as_above
    --problem=Seq2SeqDemo
    --model=transformer
    --hparams_set=my_param
    --output_dir=~/output_dir
    --decode_from_file=/dev_file_path
    --decode_to_file=/file_save_path
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末坟桅,一起剝皮案震驚了整個濱河市华望,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌仅乓,老刑警劉巖赖舟,帶你破解...
    沈念sama閱讀 212,454評論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異夸楣,居然都是意外死亡宾抓,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,553評論 3 385
  • 文/潘曉璐 我一進店門豫喧,熙熙樓的掌柜王于貴愁眉苦臉地迎上來石洗,“玉大人,你說我怎么就攤上這事紧显〗采溃” “怎么了?”我有些...
    開封第一講書人閱讀 157,921評論 0 348
  • 文/不壞的土叔 我叫張陵孵班,是天一觀的道長涉兽。 經常有香客問我招驴,道長,這世上最難降的妖魔是什么枷畏? 我笑而不...
    開封第一講書人閱讀 56,648評論 1 284
  • 正文 為了忘掉前任别厘,我火速辦了婚禮,結果婚禮上拥诡,老公的妹妹穿的比我還像新娘触趴。我一直安慰自己,他們只是感情好袋倔,可當我...
    茶點故事閱讀 65,770評論 6 386
  • 文/花漫 我一把揭開白布雕蔽。 她就那樣靜靜地躺著,像睡著了一般宾娜。 火紅的嫁衣襯著肌膚如雪批狐。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,950評論 1 291
  • 那天前塔,我揣著相機與錄音嚣艇,去河邊找鬼。 笑死华弓,一個胖子當著我的面吹牛食零,可吹牛的內容都是我干的。 我是一名探鬼主播寂屏,決...
    沈念sama閱讀 39,090評論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼贰谣,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了迁霎?” 一聲冷哼從身側響起吱抚,我...
    開封第一講書人閱讀 37,817評論 0 268
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎考廉,沒想到半個月后秘豹,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經...
    沈念sama閱讀 44,275評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡昌粤,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 36,592評論 2 327
  • 正文 我和宋清朗相戀三年既绕,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片涮坐。...
    茶點故事閱讀 38,724評論 1 341
  • 序言:一個原本活蹦亂跳的男人離奇死亡凄贩,死狀恐怖,靈堂內的尸體忽然破棺而出袱讹,到底是詐尸還是另有隱情疲扎,我是刑警寧澤,帶...
    沈念sama閱讀 34,409評論 4 333
  • 正文 年R本政府宣布,位于F島的核電站评肆,受9級特大地震影響债查,放射性物質發(fā)生泄漏。R本人自食惡果不足惜瓜挽,卻給世界環(huán)境...
    茶點故事閱讀 40,052評論 3 316
  • 文/蒙蒙 一盹廷、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧久橙,春花似錦俄占、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,815評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至祝拯,卻和暖如春甚带,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背佳头。 一陣腳步聲響...
    開封第一講書人閱讀 32,043評論 1 266
  • 我被黑心中介騙來泰國打工鹰贵, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人康嘉。 一個月前我還...
    沈念sama閱讀 46,503評論 2 361
  • 正文 我出身青樓碉输,卻偏偏與公主長得像,于是被迫代替她去往敵國和親亭珍。 傳聞我的和親對象是個殘疾皇子敷钾,可洞房花燭夜當晚...
    茶點故事閱讀 43,627評論 2 350

推薦閱讀更多精彩內容