図 2.11 : 誤差の変化 グリッドベースの物体検出 0.0040 0.0035 0.0030 0.0025 0.0020 0.0015 0.0010 0.0005 0 modelO be 凵 055 20000 0.00008 0.00007 0.00006 0.00005 0.00004 0.00003 0.00002 0.00001 0 20000 modelO IOC b55 60000 2 つの誤差は、概ね順調に下がっているように見えます。特に座標の誤差 (model@-toc ユ oss) は、確信度誤差 (modet@_label-loss) と比較して誤差が小さく、ステップ数を重ねるにつ れて下がっています。 次に、この学習済みモデルを使って、実際にイラスト画像から顔領域を検出します。 2.5 検証 リスト 2.14 は、画像を学習済みモデルに入力して結果を出力するプログラムです。 リスト 2.14 : eval_ssd. py import json nmport OS import numpy as np import tensorftow as tf from PIL import lmage, ImageDraw import box—util from tfbook_model import model@ as base—model # 使用するモデル from tfbook—model import model@ as model tf. app . ftags . FLAGS FLAGS tf. app. flags . DEF 工 NE—string('image_dir' , None, " 処理対象のディレクトリ " ) tf. app. flags. DEFINE—string('output—dir' , None, " 出力するディレクトリ " ) tf. app . flags . DEFINE—string('train_path' None, " 訓練結果のファイルバス " ) 48 第 2 章
writer. write(example. SeriaIizeToString()) 領域についてはすべて labet を 1 としています。これは筆者が作成したデータセットが、顔 をさらに分類してラベル付けしている ( 1 より上の値のラベルが存在する ) ためです。 変換の実行 リスト 2.9 は、画像とアノテーションを読み込んで TFRecord へ変換するプログラムです。 リスト 2.9 : create_dataset. py import OS import sys import gflags import numpy as np import tensorflow as tf from P 工 L import lmage import box_util from entity. region_list import RegionList # 使用するモデル from tfbook_model import model@ as model FLAGS = gflags . FLAGS gflags . DEFINE—string('base—dir' . /base—dir' " 処理する対象データのディレクトリ " ) gflags . DEF 工 NE—string('output—dir' . /output' "TFReco rd を出力するティレクトリ " ) , 256 , " 画像をリサイズする大きさ " ) gflags . DEFINE_integer( 'image_size' def _load_image(image—path, image_size) : return lmage. open(image—path) . convert( 'RGB' ) \ . resize((image_size, image_size) ) def _process—file(annotation—fite, output—di r) : dir OS . path. dirname(annotation_file) annotation = Annotation() annotation . load(annotation_file) 第 2 章グリッドベースの物体検出 37
リスト 2.12 : train_ssd. py def _init_optimizer(learning—rate) : return tf. train. AdamOptimizer(Iearning—rate=Iearning—rate) tf ・ app ・ flags tf ・ app ・ flags tf ・ app. flags tf ・ app ・ ftags tf ・ app . flags tf ・ app . flags リスト 2.13 は、これまで作成したプログラムを使ってモデルの学習を行います。 学習の実行 dataset_loader.load_ssd_dataset でデータセットを読み込み、 tf. train. shuffle ー batch を通してバッチサイズの数だけまとめます。 model-base. prepare-layers に与えて得た中間結果 ([batch-size, を、さらに model. output ユ ayers に与えて出力を得ます。 リスト 2.13 : train_ssd. py import OS import tensorftow as tf import numpy as np from tfbook_model import modet@ as model—base # 使用するモデル from tfbook_model import modet@ as modet 21 , 21 , 256 ] ) nmport FLAGS tf ・ app ・ dataset_loader tf. app . flags . FLAGS flags . DEF 工 NE . DEF 工 NE . DEFINE . DEFINE . DEFINE . DEFINE . DEF 工 NE string( 'tfrecords_di None, " 学習データを出力したディレクトリ " ) string('train_dir' . /train' " 学習結果のディレクトリ " ) 32 , 、ニバッチのサイズ " ) float( 'learning—rate' integer( 'batch_size integer('capacity' , integer( 'min—after—dequeue' 600 , ー 1 , " 学習するステップ数 " ) integer( 'max—step' , 44 第 2 章グリッドベースの物体検出
42 return file_name, positive_labets, \ box labels, box—regions, image def _distort(image) : tf. image. random—contrast(distorted_image, tf. image. random—brightness(image, max—delta=6@) distorted image distorted—image upper=l . 5, 第 2 章 model—output—count(model) output—count print(output—count) tf. parse—single-example( features value, features={ tf. FixedLenFeature()] , tf. string) , ' file_name' tf. FixedLenFeature()] , tf. string) , tf. FixedLenFeature( positive—labels' ・ [output—count] , tf. f10at32 tf. FixedLenFeature( [output—count] , 'box_tabets' tf. FixedLenFeature( 'box_regnons' [output—count 夫 4 ] , tf. f10at32 グリッドベースの物体検出 tf. f10at32 ) , raw_l mage features['file_name'] features['image'] features['positive_labets'] positive—labels features['box-labels'] box_labels features['box—regions'] box_regions tf. reshape(positive—labets, [ ー 1 , 1 ] ) positive_labels tf. reshape(box-tabels, [ ー 1 , 1 ] ) box_labets box—regions = tf. reshape(box—regions, [ ー 1 , 4 ] ) 1 mage 1 mage 1 mage 1 mage tf. image. decode—jpeg(raw—image, channels=channets) tf. image. resize_images(image, (image—snze, image—size) ) distort(image) tf. image. rgb—to—grayscale(image) tf. image. per_image—standardization(image)
fite_tist = filter( tambda f: not f. startswith(' ' ) , os ユ istdir(path)) result_list tist(map(tambda f: os . path. join(path, f) , file_tist) ) print('96s 96cP % (path, len(result—list))) return resutt_list def _modet—output—count(modet) : S 1 Z e for s in modet . OUTPUT_SHAPES: print(s) size + = sC@] ☆ sC1] return snze def toad_ssd_dataset(tfrecords-di r, image_size, with tf. name_scope( 'image_loader' ) : tfrecord_list os ユ istdir(tfrecords_dir) model, channeIs=3) : labet_list lambda f: labet_list tambda f: tabel_list fitter( ' ) , tfrecord—list) map( not f. startswith( ' list(filter( os . path . join(tfrecords_dir, f) , labet—list) lambda path: os. path. isdir(path) , label—list)) file list for path in label—list: file_list. extend(—get—filelist(path) ) fite_list list(fitter( lambda f: f. endswith(' . tfrecord') , file_tist)) tf. train. string_input—producer(file—list, shuffle=True) filename_queue options tf. python_io. TFRecordOptions( tf. python_io. TFRecordCompressionType. GZIP) reader tf. TFRecordReader(options=options) vatue reader. read(filename_queue) 第 2 章グリッドベースの物体検出 41
表 1 .1 : Tensor の Rank と Shape Rank Shape 1 DI] 2 CD@, DI, D2] 3 DI , 伊 > E Dimension 0 次元 1 次元 2 次元 3 次元 n 次元 713 [ 1.1 , 2 . 2 , 3 . 3 ] [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] . Dn-1] 表 1 .2 : Tensor のデータ型 ( 抜粋 ) python での型 tf . f10at32 tf . f10at64 tf . int8 t f . i nt16 t f . i nt32 tf . int64 tf. uint8 tf. uint16 tf. string tf . b001 解説 32 ビット浮動小数点形式 64 ピット浮動小数点形式 8 ピット整数 16 ビット整数 32 ビット整数 64 ピット整数 符号無し 8 ビット整数 符号無し 16 ピット整数 可変長文字列 真偽値 TensorFIow のウエプサイト 4 に、より詳細な表があります。 Rank が一致しないテンソルは演算できないなど、 Tensor に起因するエラーに遭遇すること は少なくありません。必要に応じて確認してください。 Tensor の操作 Tensor は、 Tens 。 r 同士の計算だけでなく、形を変えたり、一部を切り出したり、結合した り、さまざまな操作ができます。操作のオペレーションは、 Tens 。 rFl 。 w 特有のものを除けば、 NumPy と互換性を保つように開発されています。 変形 (reshape) 前述したように、 Tensor には「形」があります。 tf. reshape を使うと、これを変形できます。 リスト 1.5 では、 Rank 1 の Tensor を Rank3 に変換するオペレーション tf. reshape を実行 しています。 リスト 1 .5 : Tensor を変形 array = tf. range(@, TensorFIow の基礎 11 第 1 章