Friday, June 25, 2021

AttributeError: module 'tensorflow' has no attribute 'app'

 I was following this article, which uses tf.app in its second point. When I ran the code, I got : 

AttributeError: module 'tensorflow' has no attribute 'app'


The reason for this error is that Tensorflow 2.x no more supports tf.app.module. 

But hold on, there are alternatives! The alternatives are gflags ( for FLAGS) and  google.apputils.app (for tf.app).

To use gflags, you first need to pip install gflags:

pip install python-gflags


Now, you can use them in a similar way to tf.app.FLAG. There are slight name changes in parameter names:

flag_name becomes name, default_value becomes default & docstring becomes help.


Old code with tf.app.FLAGS

import sys
import tensorflow as tf

flags = tf.app.flags
flags.DEFINE_string(flag_name='color',
                    default_value='green',
                    docstring='the color to make a flower')

def main():
    flags.FLAGS._parse_flags(args=sys.argv[1:])
    print('a {} flower'.format(flags.FLAGS.color))

if __name__ == '__main__':
    main()





New code with gflags :

import sys
import gflags

gflags.DEFINE_string(name='color',
                      default='green',
                      help='the color to make a flower')

def main():
     gflags.FLAGS(sys.argv)
     print('a {} flower'.format(gflags.FLAGS.color))

    if __name__ == '__main__':
        main()


If you want to use app also , like tf.app , you can use
google.apputils.app


Or alternatively you can use tf.compat.v1 if you like, then the good old tf.app will work!
import tensorflow.compat.v1 as tf

No comments:

Post a Comment

 using Microsoft.AspNetCore.Mvc; using System.Xml.Linq; using System.Xml.XPath; //<table class="common-table medium js-table js-stre...