【问题标题】:Why is FLAGS necessary?为什么需要标志?
【发布时间】:2017-04-16 13:08:54
【问题描述】:

我不明白为什么在 TensorFlow 中需要 FLAGS。 现在我在书中学习 TensorFlow。

# coding: utf-8

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os

import numpy as np
import tensorflow as tf
from PIL import Image

from reader import Cifar10Reader

FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string('file',None,"path")
tf.app.flags.DEFINE_integer('offset',0,"record")
tf.app.flags.DEFINE_integer('length',16,"change record")

basename = os.path.basename(FLAGS.file)
path = os.path.dirname(FLAGS.file)

reader = Cifar10Reader(FLAGS.file)

stop = FLAGS.offset + FLAGS.length

for index in range(FLAGS.offset,stop):
    image = reader.read(index)

    print('label: %d' % image.label)
    imageshow = Image.fromarray(image.byte_array.astype(np.unit8))

    file_name = '%s-%02d-%d.png' % (basename,index,image.label)
    file = os.path.join(path,file_name)
    with open(file,mode='wb') as out:
        imageshow.save(out,format='png')

reader.close()

我像这些代码一样写,我看不懂

FLAGS = tf.app.flags.FLAGS

这部分。 我读到 FLAGS 是错误消息标签,但是什么时候需要?(也许我的阅读信息是错误的) 为什么这部分是必要的? 这部分有什么作用?

【问题讨论】:

    标签: python python-3.x tensorflow


    【解决方案1】:

    通常FLAGS 用于将命令行参数传递到您的程序中。例如

    import tensorflow as tf
    fs = tf.app.flags
    fs.DEFINE_integer('n_epochs', 25, 'number of epochs to train [25]')
    FLAGS = fs.FLAGS
    
    def main(argv):
        print(FLAGS.n_epochs)
    
    if __name__ == '__main__':
        tf.app.run()
    

    如果你从命令行以python snippet.py 运行这个sn-p,它会打印出来

    25
    

    如果你运行python snippet.py --n_epochs 50,它将打印出来

    50
    

    你可以用python的包argparse实现同样的事情。

    在您发布的示例中,FLAGS 的使用诚然有点奇怪。这里可以直接定义变量来代替它,除非FLAGS 变量在代码中的其他地方使用,这里没有显示。

    【讨论】:

      猜你喜欢
      • 2010-11-12
      • 1970-01-01
      • 2013-11-15
      • 2018-01-23
      • 1970-01-01
      • 2019-06-11
      • 2014-07-08
      • 2016-07-08
      • 1970-01-01
      相关资源
      最近更新 更多