阅读cifar10_train.py代码发现几个问题,在这里记录下。
1、tf.app.run()
if __name__ == '__main__':
tf.app.run()
阅读源码:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys as _sys
from tensorflow.python.platform import flags
from tensorflow.python.util.all_util import remove_undocumented
def _benchmark_tests_can_log_memory():
return True
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)
调用run(),经过命令解析后,调用main()
2、tf.app.flags
用于命令行解析
例:
import tensorflow as tf
FLAGS=tf.app.flags.FLAGS
tf.app.flags.DEFINE_float('flags_float',0.001,'input a float')
tf.app.flags.DEFINE_float('flags_float2',0.001,'input a float')
a=FLAGS.flags_float
b=FLAGS.flags_float2
c=a+b
print(c)
print('end')
输入:
python XXX.py -h
结果:
usage: test_parse.py [-h] [--flags_float FLAGS_FLOAT]
[--flags_float2 FLAGS_FLOAT2]
optional arguments:
-h, --help show this help message and exit
--flags_float FLAGS_FLOAT
input a float
--flags_float2 FLAGS_FLOAT2
input a float
3、__future__模块
Python的每个新版本都会增加一些新的功能,或者对原来的功能作一些改动。有些改动是不兼容旧版本的,也就是在当前版本运行正常的代码,到下一个版本运行就可能不正常了。
从Python 2.7到Python 3.x就有不兼容的一些改动,比如2.x里的字符串用'xxx'表示str,Unicode字符串用u'xxx'表示unicode,而在3.x中,所有字符串都被视为unicode,因此,写u'xxx'和'xxx'是完全一致的,而在2.x中以'xxx'表示的str就必须写成b'xxx',以此表示“二进制字符串”。
要直接把代码升级到3.x是比较冒进的,因为有大量的改动需要测试。相反,可以在2.7版本中先在一部分代码中测试一些3.x的特性,如果没有问题,再移植到3.x不迟。
Python提供了__future__模块,把下一个新版本的特性导入到当前版本,于是我们就可以在当前版本中测试一些新版本的特性。
参考:使用__future__