この行程は Tens 。 rFI 。 w を学ぶ上では必要ありませんが、画像データの操作の練習として試して みてください。 リスト 2.2 : convert_cifarl O_png. py # coding: UTF—8- from future -import absolute—import from future__ importädivision from=—future—」を月mP0「t-~ print—function ぐ 0 ( X LL. ) 一を 1 0 彎 : 1 V 0 —import OS import numpy as= np import; tensorflow as tf from PIL -import lmage from reader import Ci farI@Reader 、 FLAGS• tf,app. f1agsvFLAGS tfJapp. flags. DEF 工 NE—string(? 、 filey; NoneÜ”処理するファイルのパスⅱ ) tf. app. flags. DEFINELinteger(Üoffset' , 0 " 読み飛ばすレコード数 " ) -tf. app. flags. DEF 工 NE-integer('1ength% 1 鮖 = 夛読み込んで変換するレコード数” ) -basename 三 os. path ・ basename(FLAGSJfi1ey patm = OS. path. di name(FLAG4 file) Ci far1öReader(FLAGSJfite) reader print('labett %d 1 .96*mage,IabeIY imageshow = lmage •fromarray(image. byte—array. astype (np. ui れ (8) ) = '96s-96@2d-%d.png'z % {basename, index,- nmage .labet)- fåle n arne file = os ・ path 、 joi n (path 、 ,"te—name) with open(file; mode—'wb' ) as out: -imageshow. save (out,d format= 'png' ) reader. close() 第 2 章 CIFAR-IO の学習と評価 21
tf 、 FixedLengthRecordReader(record—bytes=record—bytesj self. reader. read(setf.filename—queue) byte—buffer ー tf. decode—raw(vatue/ tf. uint8) keyy vatue setf. reader transpose の処理を、 こでは tf. reshape と tf. transpose に置き換えています CifarI@Record クラスの set—image メソッドも同様に、以前は numpy で行っていた reshape や オペレーションを使います。 使います。読み込んだデータ byte ー buffer からラベルと画像データを分離する処理には、 tf. slice していましたが、リスト 4.13 では、固定長のレコードを読み込む tf. FixedLengthRecordReader を 以前 ( 第 2 章「 CIFAR -10 の学習と評価」を参照 ) は、レコードの読み込みにはインデックスを指定して return result result. set•mage (tf• stice(byte—buffer, [ 1 ] 。 ,ÆimageLbytesj)) [label-bytes])) resutt. set—labet(tfvslice(byte-buffer, ~ [ 0 ] , de€ main (argv;None) : 」 リスト 4.14 : train_vgg_adam minibatch distort. py ログラムです。 リスト 4.14 は、データセットの読み込みから画像データの加工 ( 標準化含む ) 、訓練を実行するプ 画像テータの加工とミニバッチによる訓練 ~ 一 global—step* = tf.Variab1e()ß trainab1e=Fatse) keepprob—plaeeholder= tf. placehotder—with—default(tf. constantCI, の , reader record shape=[] name= 'keep—prob') Ci far1@Readen(fitenames) reader. read ( ) 66 distort( record. byte—array) distorted—image ま 3 曇 standarcfized—image = Å 第 4 章 CIFAR-I()f 闘記 FLAGS. batch—size) ~ [standardized—image' record ユ abel] ” batch—imagey 、 :batch—1abeÜ= tf. train. batch( tf. image ・ per•fmage—standardization (distorted—imagey
0 C 一 V ( bD 1 bD 一 0 FLAGS etf 、 app. ft 目 g 、 FLAGS tf 、 app. flags 、 bEF 工 NE—string('graph_dir's None, ! ! 処理するグラフファイルのあるバスり tf, app.flags. DEF 工 NE=string(' test—data ' ' . /data/test—batch. bin' ーリテストデータのパス , ! ) 一 def eval(graph—file) : # 現在のグラフをリセット tf. reset—defaultzgraph() 'rb') as ft with tEgfiIe.FastGFile(graph—fiIe, graph—def = tf. GraphDef() graph—def. ParseFromString(f 、 d ( ) ) ー tf. import—graph—def(graph-def, :name=j' with tf.SessionCYas sessv image—reader = Ci far1@Reader(FLAGS.test=data) ætrue=coun€h—= 0 for index in range(@/i 10000 ) : image デ image—reader. read (index) 11 0 “ 1 」一 1 true—count 十に np. sum(predictions) =print( '96sy %. 2f を % (graph—file, (true—count / らユ 0000 : 0 ) ) ) 'image—reader ・ ctose() ma 1 n gtob. g10b(FLAGSLgraph-di r + Y*'Pb' ) if _—name— ;file list = 第 3 章データ保存とフィルターの可視化
sesserun(Ltrain—opototaI—IossJ; loss—vatue feed—dict={ train—placehotder: = zimage. byte—array, tabel—placehotder:•mage. 1目be1 ( 、 1 」 0 C 第 3 3 「 0 assert not np. isnan(toss—value) , 、 =OM0det diverged with ユ .oss = NaN 第 «reader. ctose() prediction = •ceval(sess, -top—k—op, train—ptaceholder, "labetuplacehotder) -print ('epoch- "6d prediction = 96J3f' % (epoch Hduration„ prediction) ) tf.summary. FiIeWriter(FLAGS. checkpoint—di % sess. graph) → pri nt( 'TotaV duration = %d sec ' % total—duration) リスト 2.17 は、オペレーション top ー k ー op を実行する関数です。引数のセッション (sess ) 内で 評価を実行します。 リスト 2.17 : train with_eval.py def —evat(sess,r top 」 k—op, input—image' labet—placeholder) : if not FLAGS.test—data : returnnp. nan -ßmage—reader— Cifar1@Reader(FLAGS.test—data) 土 ru e—c ou n t = 0 ndeßn range くユ 0000 ) image =&iage—reader. read(i ndex) —predictions• sessyrun( [tOP—k—OP] , feed—dict=C → = ー nput—image: image. image, -labet—ptacehotder: image. labet 38 第 2 章 CIFAR-IO の学習と評価
Cifar1@Reader の read メソッドで読み込んだ CIFAR -10 レコードの画像データを一 distort と tf. image ・ per_image—standardization で標準化し、ラベル (record. label) と合わせて tf. train . batch に与えています batch-image と batch-label は、読み込んだデータを指定したサイズ分まとめた値が格納され ます。 図 4.1 1 tf. train. batch を使ったグラフ Cifa 「 10Record byte-a 「「 ay [ 32. 32. 3 ] Cifar 10Reader label whitening—image -distort batch 」 mage [batch-size, 32 , 32 , 3 ] tf. train. batch batch_label [batch-s ize] TensorFIow には、データの読み込みからミニバッチにまとめる処理を並列で実行する仕組みが あります。これを「インブット・パイプライン (input pipeline) 」と呼びます。 インブット・パイプラインを使うには、 queue ー runner を用意する必要があります。リスト 4.14 では、 tf. train. start_queue—runner で、セッション (sess に紐付く queue_runner を起動 しています。 評価 リスト 4.15 は、読み込んだモデルを、テストデータセットで評価するプログラムです。 訓練の時にインブット・パイプラインを作りましたが、訓練データの読み込みに限定されていま す。そのため、リスト 4.15 ではテストデータセットを読み込むためのインブット・パイプライン ( 標 準化処理のみ ) を別に作成しています。 リスト 4.15 : eval_minibatch_without distort. py def evat(gfäph—file) : 68 井現在のグラフをリセッ ~ ト tf. reset—default—graph( ) reader =ÆifarIöReader( [FLAGS. test—data] ) record read ( ) standardized—image tf.*mage 、 per—image—standardization(record. byte—array) batch—image, bätch 」 tabel ヒ tfvtrain 、 batchC CstandardizecLimage *. labet 第 4 章 CIFAR-10f 闘記
0 % Q) 一 E / 0 b0 ー 1 一文三 ・ 1 ・ 1 0 E C= bD 、 1 】 を」 C V 0 ~ V ー # (hei ght, width „Gepth) ー > (batch, height, width, depthY 一一 image—node = tf. expand—dims(train—placeholder, の flogits —imodet einference(image—node) with tf. Session() as sess: sess. run(tf. gtobat—var ables initializer() ) を ;totaV—duration •for fi 、 le—index -in range(5) : print ( 'Epoch- %d: %s を % E(epochÄi1enames [file—index] ) ) reader Ci farIØReader(fiIenames げ 11e ー i れ de 灯 ) reader.ctose ( ) duration = €åme. time() start—time ー。。ー totaV•、 duration + = duration print('epo&%d duration = %dsec' % (epoch, ・ duration)) tf. summary. FiIeWriter(FLAGS. checkpoint—diresess. graph) ~ print(PTotaI duration %d secy % totat—duration) name 第 2 章 CIFAR-IO の学習と評価
リスト 2.16 : train with_eval.py FLAGS *. flags 、下 LAGS tf. app. ftags. DEFINE—integer(Yepoch', 30 い " 訓練するモ PO ( h 数リ ”訓練データのディ、レクト屮ツ ytf•app. flags. 、 DEFINE—sfring('data-dir' /data/ ' 第 2 章 CIFAR-IO の学習と評価 image reader . read(index) fo 「•index in 「 ange ( 10e0 のは「 reader 三 Ci far1@Reader(fi1enames [file—index] ) print( ' Epoch %d : % 、、 % (epoch' fitenames[file—index) ) ) fo&file—indexs* n range ( 5 ) : +total—duration = 0 globa!+step = tf 、 Variab1e(), trainabte=Fa1se) def mai n argv=None) い startU€ime 一 time. ( ) をを→ = fo 「第 epoch n range い : , FLAGS. epoch+& 1 ) ・ sess ・ run(tf.gtobal—variables—initializer()) with tf. Session() as sess: 。・ top ー k ー 0 のダは f は nn. in—topLk(Vogits»ユ abel—placeholderj 1 ) t に 2 i n こ 0 p —trai n(total—loss/ gtobal—step) logits• model.i nference(image-node) t oexpand—dims(train—ptaceholderr-@ # —(height, width ep セ h 濵ト > (batch,ftlei ght/ width+h depth)- tabel—ptaceholder• tf.pIaceh01der(tf.int32,r shape=[1Jy name='labet') name—hnputuimage ' ) 一 shape=C32, 32 , 3 ] , tfäin—ptacehotder ゴ。 ~ tf. placehotder(tf. f10at32 , tf. app.flags'DEF 工 NE—string( ' test-datat; None, ' ! テストデータのパス ! ! ) 。 = = → = = 。。 " チェックポイントを保存する歹イとグトリ " ) ./checkpoints/@, tf. app. f1ags.DEF 工 NE—string( ' checkpoint—dir? 37
クトが得られます。 リスト 4.13 : reader_minibatch. py # coding: UTF—8 future——ämport$ absolute—import from from -æfuture—3mport division frorw —_future—u import pri nt function 〔 C 1 」 一工 bD 00 0 C C C V 、 0 】 00 C ( as "tf class Ci far1@Record(0bject) : —widtW = 32 ・ height = 32 depth = 3 ±def .set-tabet(Setf, label) : self,tabet tf. cast(label, tfJint32) ödef set—image(self» image) : reshaped—image-= tf. reshape(imagej Csetf.depth, setf•height , = setf. width) ) = setf. byte—arraw— tf. cast(reshaped—image, tf. f10at32 ) *&label—bytes = ユ result. height ま - result. w*dth ☆ result. depth =nmage—bytes label—bytest + を image—bytes record—bytes cIassCifar1@Reader(object) : filename_queue Non e def に」 nit こニ←き , filenames); self. fitename—queue = tf. >train. string—input—producer (filenames) → ~ def read (setf) : result = Cifar1@Record ( ) 第 4 章 CIFAR-10f 闘記
なお、 TensorFlow の畳み込みニューラルネットワーク関係のオペレーションは、 1 つ以上のデー タをまとめて処理するように作られています。そこで、プレースホルダ—train_placehotder で 画像データを受け取った後、オペレーション tf. expand ー dims を使って次元を拡張しています。 図 2.5 : inference が構築するグラフから logits を得る t 「謝 n ー p ( 2h0 [ de 「 ・ input-image' inference logi ts expand-dims 「練 8 ー』レ 0 ョ司 O , u ( る , 保 , 「ー 1 ポ 0 】 / 人 0 ・ 1- C ) 「 bD tO 竊 0 C 0 0 ~ 0 1 工〔〔工 H bD bD 0 >E E ( E 「」 0 】 0 0 nmport OS vimport tensorflow as tf importunodet- as modet -from reader import Ci farI@Reader fitenames OS ・ path. join(É 一 .FLAGS. data—dir, 'data_batch %d. bin\ % i) ー for i range()/ 6 ) definain(argv=None) : train—placeholder = 弌 f. placeholder(t€. f10at32 , shape=t32ß32, 31 , = narne='i nput—image') 30 第 2 章 CIFAR-IO の学習と評価
as—text=Fatse) convert-variables-to-constants にはセッションと、保存したいグラフ定義、保存するオペ レーションの名前をリストで記述します。 オペレーションの名前は、スコープ ( 名前空間 ) と名前を区切り文字列 ( / ) で区切って記述しま す。保存するオペレーション logits のスコープは output なので、 output/togits を指定します。 続く serializeToString でグラフと変数をシリアライズしています。 ProtocoI Buffersl フォー マットで保存されるため、ファイル名の拡張子には . pb を指定しています。 読み込み 保存したグラフの読み込みには ParseFromString を使います。また、 tf. import ー graph ー def を使ってデフォルトのグラフに設定しています。 リスト 3.4 : グラフと変数の読み込み with tEgfiIe. FastGFiIe(graph—fi te, lrb' ) as f; graphLdef tf. GÉaphDefC) graph—defLParseFromString()L read ( ) ) ! tfvämport—graph—def(graph—defvname= グラフデータによる評価 グラフを読み込んだ後、 リスト 3.5 は、 graph ー utit で書き出したグラフと変数を使ってモデルを評価するプログラムです。 コマンドラインの引数ーー graph ー dir にディレクトリを指定すると、そのディレクトリにあるすべて の拡張子 . pb のファイルを評価して結果を表示します。 リスト 3.5 : eval.py # 。 = coding: UTF-8 ← from ——future from =future from ——future— import g10b #import absolute—import : nmport •division print—function 42 import- tensorflow as tf from reader import Cifar1@Reader import numpy as np 第 3 章データ保存とフィルターの可視化