Skip to main content
 首页 » 编程设计

python之为什么需要 FLAGS

2025年02月15日8powertoolsteam

我无法理解为什么 FLAGS 在 TensorFlow 中是必需的。 现在我在书中学习 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是错误信息标签,但是什么时候需要呢?(可能是我看的信息有误) 为什么这部分是必要的? 这部分有什么作用?

请您参考如下方法:

通常 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 的形式运行此代码段,它将打印

25 

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

50 

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

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