欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

TensorFlow中關(guān)于tf.app.flags命令行參數(shù)解析模塊

 更新時(shí)間:2022年11月02日 10:29:17   作者:打工人小飛  
這篇文章主要介紹了TensorFlow中關(guān)于tf.app.flags命令行參數(shù)解析模塊,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

tf.app.flags命令行參數(shù)解析模塊

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

在閱讀相關(guān)工程的源碼時(shí),很容易發(fā)現(xiàn) tf.app.flags 模塊的身影。其作用與 python 的 argparse 類似。

直接上代碼實(shí)例,新建一個(gè)名為 test_flags.py 的文件,內(nèi)容如下:

#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的時(shí)候,不會(huì)執(zhí)行main 函數(shù)
if __name__ == '__main__':
    tf.app.run()   # 解析命令行參數(shù),調(diào)用main 函數(shù) main(sys.argv)

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

該文件的調(diào)用示例以及運(yùn)行結(jié)果如下所示

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

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

還需查閱其源代碼

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源碼中用來解析命令行參數(shù)的函數(shù)。

所以這一行就是解析參數(shù)的功能;

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

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論