日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

TensorFlow中關于tf.app.flags命令行參數解析模塊_python

作者:打工人小飛 ? 更新時間: 2022-12-05 編程語言

tf.app.flags命令行參數解析模塊

說道命令行參數解析,就不得不提到 python 的 argparse 模塊,詳情可參考我之前的一篇文章:python argparse 模塊命令行參數用法及說明。

在閱讀相關工程的源碼時,很容易發現 tf.app.flags 模塊的身影。其作用與 python 的 argparse 類似。

直接上代碼實例,新建一個名為 test_flags.py 的文件,內容如下:

#coding:utf-8
import tensorflow as tf

FLAGS = tf.app.flags.FLAGS
# tf.app.flags.DEFINE_string("param_name", "default_val", "description")
tf.app.flags.DEFINE_string("train_data_path", "/home/feige", "training data dir")
tf.app.flags.DEFINE_string("log_dir", "./logs", " the log dir")
tf.app.flags.DEFINE_integer("train_batch_size", 128, "batch size of train data")
tf.app.flags.DEFINE_integer("test_batch_size", 64, "batch size of test data")
tf.app.flags.DEFINE_float("learning_rate", 0.001, "learning rate")

def main(unused_argv):
    train_data_path = FLAGS.train_data_path
    print("train_data_path", train_data_path)
    train_batch_size = FLAGS.train_batch_size
    print("train_batch_size", train_batch_size)
    test_batch_size = FLAGS.test_batch_size
    print("test_batch_size", test_batch_size)
    size_sum = tf.add(train_batch_size, test_batch_size)
    with tf.Session() as sess:
        sum_result = sess.run(size_sum)
        print("sum_result", sum_result)

# 使用這種方式保證了,如果此文件被其他文件 import的時候,不會執行main 函數
if __name__ == '__main__':
    tf.app.run()   # 解析命令行參數,調用main 函數 main(sys.argv)

上述代碼已給出較為詳細的注釋,在此不再贅述。

該文件的調用示例以及運行結果如下所示

如果需要修改默認參數的值,則在命令行傳入自定義參數值即可,若全部使用默認參數值,則可直接在命令行運行該 python 文件。

讀者可能會對 tf.app.run() 有些疑問,在上述注釋中也有所解釋,但要真正弄清楚其運行原理

還需查閱其源代碼

def run(main=None, argv=None):
  """Runs the program with an optional 'main' function and 'argv' list."""
  f = flags.FLAGS

  # Extract the args from the optional `argv` list.
  args = argv[1:] if argv else None

  # Parse the known flags from that list, or from the command
  # line otherwise.
  # pylint: disable=protected-access
  flags_passthrough = f._parse_flags(args=args)
  # pylint: enable=protected-access

  main = main or sys.modules['__main__'].main

  # Call the main function, passing through any arguments
  # to the final program.
  sys.exit(main(sys.argv[:1] + flags_passthrough))

flags_passthrough=f._parse_flags(args=args)這里的_parse_flags就是我們tf.app.flags源碼中用來解析命令行參數的函數。

所以這一行就是解析參數的功能;

下面兩行代碼也就是 tf.app.run 的核心意思:執行程序中 main 函數,并解析命令行參數!

原文鏈接:https://huangfei.blog.csdn.net/article/details/81090227

欄目分類
最近更新