tf.app.run()的作用

if __name__ == "__main__":

means current file is executed under a shell instead of imported as a module.

tf.app.run()

As you can see through the file app.py

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))

Let's break line by line:

flags_passthrough = f._parse_flags(args=args)

This ensures that the argument you parse through command line is valid,e.g. python my_model.py --data_dir='...' --max_iteration=10000 Acturally, this feature is implemented based on python standardargparse model.

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

The first main in right side of = is the first argument of current functionrun(main=None, argv=None). While sys.modules['__main__'] means current running file(e.g.my_model.py).

So there are two cases:

  1. You don't have a main function in my_model.py Then you have tocalltf.app.run(my_main_running_function)

  2. you have a main function in my_model.py. (This is most the case.)

Last line:

sys.exit(main(sys.argv[:1] + flags_passthrough))

ensures your main(argv) or my_main_running_function(argv) function is called with parsed arguments properly.


A missing piece of the puzzle for beginner Tensorflow users: Tensorflow has some builtin command line flag handling mechanism. You can define your flags like tf.flags.DEFINE_integer('batch_size', 128, 'Number of images to process in a batch.') and then if you use tf.app.run() it will set things up so that you can globally access the passed values of the flags you defined, like tf.flags.FLAGS.batch_size from wherever you need it in your code

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值