php $app->run(),tf.app.run()使用方法的解释
在一些github上公开的代码中,我们经常会看到这样的程序if __name__ == '__main__':tf.app.run()像网上的大多数文章一样,先粘贴一下run()的源码:def run(main=None, argv=None):"""Runs the program with an optional 'main' function and 'argv' list."""f = f
在一些github上公开的代码中,我们经常会看到这样的程序if __name__ == '__main__':
tf.app.run()
像网上的大多数文章一样,先粘贴一下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))
_allowed_symbols = [
'run',
# Allowed submodule.
'flags',
]
remove_undocumented(__name__, _allowed_symbols)
源码中写的很清楚,首先加载flags的参数项,然后执行main()函数,其中参数使用tf.app.flags.FLAGS定义的。
tf.app.flags.FLAGS# fila_name: temp.py
import tensorflow as tf
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string('string', 'train', 'This is a string')
tf.app.flags.DEFINE_float('learning_rate', 0.001, 'This is the rate in training')
tf.app.flags.DEFINE_boolean('flag', True, 'This is a flag')
print('string: ', FLAGS.string)
print('learning_rate: ', FLAGS.learning_rate)
print('flag: ', FLAGS.flag)
输出:string: train
learning_rate: 0.001
flag: True
如果在命令行中执行python3 temp.py --help,得到输出:usage: temp.py [-h] [--string STRING] [--learning_rate LEARNING_RATE]
[--flag [FLAG]] [--noflag]
optional arguments:
-h, --help show this help message and exit
--string STRING This is a string
--learning_rate LEARNING_RATE
This is the rate in training
--flag [FLAG] This is a flag
--noflag
如果要对FLAGS的默认值进行修改,只要输入命令:python3 temp.py --string 'test' --learning_rate 0.2 --flag False
联合使用import tensorflow as tf
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string('string', 'train', 'This is a string')
tf.app.flags.DEFINE_float('learning_rate', 0.001, 'This is the rate in training')
tf.app.flags.DEFINE_boolean('flag', True, 'This is a flag')
def main(unuse_args):
print('string: ', FLAGS.string)
print('learning_rate: ', FLAGS.learning_rate)
print('flag: ', FLAGS.flag)
if __name__ == '__main__':
tf.app.run()
主函数中的tf.app.run()会调用main,并传递参数,因此必须在main函数中设置一个参数位置。如果要更换main名字,只需要在tf.app.run()中传入一个指定的函数名即可。def test(args):
# test
...
if __name__ == '__main__':
tf.app.run(test)
开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!
更多推荐
所有评论(0)