18、使用 tf.app.flags 接口定义命令行参数

来源:互联网 发布:标书制作软件 编辑:程序博客网 时间:2024/05/19 22:44

一、使用 tf.app.flags 接口定义命令行参数

  • 众所周知,深度学习有很多的 Hyperparameter 需要调优,TensorFlow 底层使用了python-gflags项目,然后封装成tf.app.flags接口
  • 使用tf.app.flags接口可以非常方便的调用自带的DEFINE_string, DEFINE_boolean, DEFINE_integer, DEFINE_float设置不同类型的命令行参数及其默认值,在实际项目中一般会提前定义命令行参数,如下所示:
# coding: utf-8# filename: flags.pyimport tensorflow as tf# 定义一个全局对象来获取参数的值,在程序中使用(eg:FLAGS.iteration)来引用参数FLAGS = tf.app.flags.FLAGS# 定义命令行参数,第一个是:参数名称,第二个是:参数默认值,第三个是:参数描述tf.app.flags.DEFINE_integer("iteration", 200000, "Iterations to train [2e5]")tf.app.flags.DEFINE_integer("disp_freq", 1000, "Display the current results every display_freq iterations [1e3]")tf.app.flags.DEFINE_integer("save_freq", 2000, "Save the checkpoints every save_freq iterations [2e3]")tf.app.flags.DEFINE_float("learning_rate", 0.001, "Learning rate of for adam [0.001]")tf.app.flags.DEFINE_integer("train_batch_size", 64, "The size of batch images [64]")tf.app.flags.DEFINE_integer("val_batch_size", 100, "The size of batch images [100]")tf.app.flags.DEFINE_integer("height", 48, "The height of image to use. [48]")tf.app.flags.DEFINE_integer("width", 160, "The width of image to use. [160]")tf.app.flags.DEFINE_integer("depth", 3, "Dimension of image color. [3]")tf.app.flags.DEFINE_string("data_dir", "/path/to/data_sets/", "Directory of dataset in the form of TFRecords.")tf.app.flags.DEFINE_string("checkpoint_dir", "/path/to/checkpoint_save_dir/", "Directory name to save the checkpoints [checkpoint]")tf.app.flags.DEFINE_string("model_name", "40w_grtr", "Model name. [40w_grtr]")tf.app.flags.DEFINE_string("gpu_id", "0", "Which GPU to be used. [0]")tf.app.flags.DEFINE_boolean("continue_train", False, "True for continue training.[False]")tf.app.flags.DEFINE_boolean("per_image_standardization", True, "True for per_image_standardization.[True]")# 定义主函数def main(argv=None):      print(FLAGS.iteration)    print(FLAGS.learning_rate)    print(FLAGS.data_dir)    print(FLAGS.continue_train)# 执行main函数if __name__ == '__main__':    tf.app.run()  

二、执行程序的方法

1、使用程序中的默认参数

  • python flags.py

这里写图片描述

2、在命令行更改程序中的默认参数

  • python flags.py --iteration=500000 --learning_rate=0.01 --data_dir='/home/test/' --continue_train=True

这里写图片描述

原创粉丝点击