edo1z blog

プログラミングなどに関するブログです

TensorFlow - tf.app.flags.FLAGS(ファイル実行時にパラメタを付与できるようにする)

tf.app.flags.FLAGSを使うと、TensorFlowのPythonファイルを実行する際にパラメタを付与できるようになる。

下記のようにすると、パラメタ付与が可能になり、デフォルト値やヘルプ画面の説明文を登録できる。tf.app.flags.DEFINE_stringは、String型用で、他にtf.app.flags.DEFINE_boolean、tf.app.flags.DEFINE_integer等を型に合わせて使う。

tf.app.flags.DEFINE_string('変数名', 'デフォルト値', """説明文""")

コードサンプル (test.py)

import tensorflow as tf

FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_integer('data_num', 100, """データ数""")
tf.app.flags.DEFINE_string('img_path', './img', """画像ファイルパス""")

def main(argv):
    print(FLAGS.data_num, FLAGS.img_path)

if __name__ == '__main__':
    tf.app.run()

ヘルプを表示する

$ python test.py --help

結果

usage: test.py [-h] [--data_num DATA_NUM] [--img_path IMG_PATH]

optional arguments:
  -h, --help           show this help message and exit
  --data_num DATA_NUM  データ数
  --img_path IMG_PATH  画像ファイルパス

実行例

$ python test.py --data_num 35

結果

35 ./img