Skip to content

UnrecognizedFlagError: Unknown command line flag 'f' #17702

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
jinsu-kim opened this issue Mar 14, 2018 · 38 comments
Closed

UnrecognizedFlagError: Unknown command line flag 'f' #17702

jinsu-kim opened this issue Mar 14, 2018 · 38 comments
Labels
stat:awaiting response Status - Awaiting response from author

Comments

@jinsu-kim
Copy link

jinsu-kim commented Mar 14, 2018

System information

  • Have I written custom code (as opposed to using a stock example script provided in TensorFlow): custom code
  • OS Platform and Distribution (e.g., Linux Ubuntu 16.04): Windows 10
  • TensorFlow installed from (source or binary): source
  • TensorFlow version (use command below): tensorflow 1.5.0
  • Python version: pyhton 3.6.3
  • Bazel version (if compiling from source): None
  • GCC/Compiler version (if compiling from source): None
  • CUDA/cuDNN version: None
  • GPU model and memory: GTX960M
  • Exact command to reproduce:

Problem Description

When trying to run this code

import tensorflow as tf

flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_float('learning_rate', 0.01, 'Initial learning rate.')
flags.DEFINE_integer('max_steps', 2000, 'Number of steps to run trainer.')
flags.DEFINE_integer('hidden1', 128, 'Number of units in hidden layer 1.')
flags.DEFINE_integer('hidden2', 32, 'Number of units in hidden layer 2.')
flags.DEFINE_integer('batch_size', 100, 'Batch size. '
'Must divide evenly into the dataset sizes.')
flags.DEFINE_string('train_dir', 'data', 'Directory to put the training data.')
flags.DEFINE_boolean('fake_data', False, 'If true, uses fake data '
'for unit testing.')

FLAGS = flags.FLAGS
print(FLAGS.learning_rate)

I got this error message

---------------------------------------------------------------------------
UnrecognizedFlagError                     Traceback (most recent call last)
<ipython-input-3-1ce89dff3e81> in <module>()
      1 FLAGS = flags.FLAGS
----> 2 print(FLAGS.learning_rate)

c:\users\jinsu\appdata\local\programs\python\python36\lib\site-packages\tensorflow\python\platform\flags.py in __getattr__(self, name)
     82     # a flag.
     83     if not wrapped.is_parsed():
---> 84       wrapped(_sys.argv)
     85     return wrapped.__getattr__(name)
     86 

c:\users\jinsu\appdata\local\programs\python\python36\lib\site-packages\absl\flags\_flagvalues.py in __call__(self, argv, known_only)
    628       suggestions = _helpers.get_flag_suggestions(name, list(self))
    629       raise _exceptions.UnrecognizedFlagError(
--> 630           name, value, suggestions=suggestions)
    631 
    632     self.mark_as_parsed()

UnrecognizedFlagError: Unknown command line flag 'f'

This is another

import tensorflow as tf

FLAGS = tf.app.flags.FLAGS
FLAGS.learning_rate = 0.02
FLAGS.name = 'test'

print(FLAGS.learning_rate)
print(FLAGS.name)
---------------------------------------------------------------------------
UnrecognizedFlagError                     Traceback (most recent call last)
<ipython-input-1-fe17797ba132> in <module>()
      2 
      3 FLAGS = tf.app.flags.FLAGS
----> 4 FLAGS.learning_rate = 0.02
      5 FLAGS.name = 'test'
      6 

c:\users\jinsu\appdata\local\programs\python\python36\lib\site-packages\tensorflow\python\platform\flags.py in __setattr__(self, name, value)
     86 
     87   def __setattr__(self, name, value):
---> 88     return self.__dict__['__wrapped'].__setattr__(name, value)
     89 
     90   def __delattr__(self, name):

c:\users\jinsu\appdata\local\programs\python\python36\lib\site-packages\absl\flags\_flagvalues.py in __setattr__(self, name, value)
    494       raise AttributeError(name)
    495     if name not in fl:
--> 496       return self._set_unknown_flag(name, value)
    497     fl[name].value = value
    498     self._assert_validators(fl[name].validators)

c:\users\jinsu\appdata\local\programs\python\python36\lib\site-packages\absl\flags\_flagvalues.py in _set_unknown_flag(self, name, value)
    372       except NameError:  # Flag name is not valid.
    373         pass
--> 374     raise _exceptions.UnrecognizedFlagError(name, value)
    375 
    376   def append_flag_values(self, flag_values):

UnrecognizedFlagError: Unknown command line flag 'learning_rate'

Did I miss anything??
I cannot figure out what the problem is.

@dketterer
Copy link

dketterer commented Mar 14, 2018

I have the same problem. I build from source against CUDA 8.0 and cuDNN 6.0.
I used git checkout r1.6 before compiling.

flags = tf.app.flags
flags.FLAGS.train_dir = '../data/ckpt'

print(flags.FLAGS) gives a valid a valid output:

object_detection.dataset_tools.create_pet_tf_record:
  --data_dir: Root directory to raw pet dataset.
    (default: '')
  --[no]faces_only: If True, generates bounding boxes for pet faces.  Otherwise
    generates bounding boxes (as well as segmentations for full pet bodies).
    Note that in the latter case, the resulting files are much larger.
    (default: 'true')
  --label_map_path: Path to label map proto
    (default: 'data/pet_label_map.pbtxt')
  --mask_type: How to represent instance segmentation masks. Options are "png"
    or "numerical".
    (default: 'png')
  --output_dir: Path to directory to output TFRecords.
    (default: '')

object_detection.train:
  --[no]clone_on_cpu: Force clones to be deployed on CPU.  Note that even if set
    to False (allowing ops to run on gpu), some ops may still be run on the CPU
    if they have no GPU kernel.
    (default: 'false')
  --input_config_path: Path to an input_reader_pb2.InputReader config file.
    (default: '')
  --master: Name of the TensorFlow master to use.
    (default: '')
  --model_config_path: Path to a model_pb2.DetectionModel config file.
    (default: '')
  --num_clones: Number of clones to deploy per worker.
    (default: '1')
    (an integer)
  --pipeline_config_path: Path to a pipeline_pb2.TrainEvalPipelineConfig config
    file. If provided, other configs are ignored
    (default: '')
  --ps_tasks: Number of parameter server tasks. If None, does not use a
    parameter server.
    (default: '0')
    (an integer)
  --task: task id
    (default: '0')
    (an integer)
  --train_config_path: Path to a train_pb2.TrainConfig config file.
    (default: '')
  --train_dir: Directory to save the checkpoints and training summaries.
    (default: '')
  --worker_replicas: Number of worker+trainer replicas.
    (default: '1')
    (an integer)

absl.flags:
  --flagfile: Insert flag definitions from the given file into the command line.
    (default: '')
  --undefok: comma-separated list of flag names that it is okay to specify on
    the command line even if the program does not define a flag with that name.
    IMPORTANT: flags in this list that have arguments MUST use the --flag=value
    format.
    (default: '')

print(flags.FLAGS.train_dir) gives an error:

---------------------------------------------------------------------------
UnrecognizedFlagError                     Traceback (most recent call last)
<ipython-input-23-d8c0abc56bc4> in <module>()
----> 1 print(flags.FLAGS.train_dir)

~/workspace/marvin-workspace/.env/lib/python3.6/site-packages/tensorflow/python/platform/flags.py in __getattr__(self, name)
     82     # a flag.
     83     if not wrapped.is_parsed():
---> 84       wrapped(_sys.argv)
     85     return wrapped.__getattr__(name)
     86 

~/workspace/marvin-workspace/.env/lib/python3.6/site-packages/absl/flags/_flagvalues.py in __call__(self, argv, known_only)
    628       suggestions = _helpers.get_flag_suggestions(name, list(self))
    629       raise _exceptions.UnrecognizedFlagError(
--> 630           name, value, suggestions=suggestions)
    631 
    632     self.mark_as_parsed()

UnrecognizedFlagError: Unknown command line flag 'f'

This example works directly on the command line python interpreter but it does not work in my jupyter notebook

import tensorflow as tf
flags = tf.app.flags
flags.DEFINE_integer("age", 17, "age of user(default:20)")
print(flags.FLAGS.age)

@PiyushDatta
Copy link
Contributor

@magicmutal
For the first code snippet:

import tensorflow as tf

flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_float('learning_rate', 0.01, 'Initial learning rate.')
flags.DEFINE_integer('max_steps', 2000, 'Number of steps to run trainer.')
flags.DEFINE_integer('hidden1', 128, 'Number of units in hidden layer 1.')
flags.DEFINE_integer('hidden2', 32, 'Number of units in hidden layer 2.')
flags.DEFINE_integer('batch_size', 100, 'Batch size. '
'Must divide evenly into the dataset sizes.')
flags.DEFINE_string('train_dir', 'data', 'Directory to put the training data.')
flags.DEFINE_boolean('fake_data', False, 'If true, uses fake data '
'for unit testing.')

FLAGS = flags.FLAGS
print(FLAGS.learning_rate)

This works on Tensorflow version 1.6.0 and on the source version.

For the second code snippet:

import tensorflow as tf

FLAGS = tf.app.flags.FLAGS
FLAGS.learning_rate = 0.02
FLAGS.name = 'test'

print(FLAGS.learning_rate)
print(FLAGS.name)

You must define the learning rate and name within tf.app.flags before you can change it within tf.app.flags.FLAGS (notice the different flags). Therefore you can make this code work by doing this:

import tensorflow as tf

flags = tf.app.flags 
FLAGS = tf.app.flags.FLAGS
flags.DEFINE_float('learning_rate', 0.02, 'Initial learning rate.')
flags.DEFINE_string('name', 'test', 'The name of our flag')
# FLAGS.learning_rate = 0.03
# FLAGS.name = 'Testing'

print(FLAGS.learning_rate)
print(FLAGS.name)

You can un-comment FLAGS.learning_rate = 0.03 and FLAGS.name = 'Testing' if you want to change the values of learning rate or name, but you MUST declare both these variables within tf.app.flags as shown by the lines above. @dketterer the explanation for the second code snippet is similar to your problem. I have not looked at the jupyter notebook issue however, maybe make a different issue for that.

Hope that helps!

As a PR idea/suggestion, maybe documentation could be made on this? Not too sure.

@jinsu-kim jinsu-kim changed the title UnrecognizedFlagError: Unknown command line flag UnrecognizedFlagError: Unknown command line flag 'f' Mar 15, 2018
@jinsu-kim
Copy link
Author

@PiyushDatta
Thanks a lot. There was a progress!!
I upgraded Tensorflow to 1.6.0 and ran the codes but I got another error message.

the first code

import tensorflow as tf

flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_float('learning_rate', 0.01, 'Initial learning rate.')
flags.DEFINE_integer('max_steps', 2000, 'Number of steps to run trainer.')
flags.DEFINE_integer('hidden1', 128, 'Number of units in hidden layer 1.')
flags.DEFINE_integer('hidden2', 32, 'Number of units in hidden layer 2.')
flags.DEFINE_integer('batch_size', 100, 'Batch size. '
'Must divide evenly into the dataset sizes.')
flags.DEFINE_string('train_dir', 'data', 'Directory to put the training data.')
flags.DEFINE_boolean('fake_data', False, 'If true, uses fake data '
'for unit testing.')

FLAGS = flags.FLAGS
print(FLAGS.learning_rate)
--------------------------------------------------------------------------------
DuplicateFlagError                        Traceback (most recent call last)
<ipython-input-5-95226cf0354f> in <module>()
      3 flags = tf.app.flags
      4 FLAGS = flags.FLAGS
----> 5 flags.DEFINE_float('learning_rate', 0.01, 'Initial learning rate.')
      6 flags.DEFINE_integer('max_steps', 2000, 'Number of steps to run trainer.')
      7 flags.DEFINE_integer('hidden1', 128, 'Number of units in hidden layer 1.')

c:\users\jinsu\appdata\local\programs\python\python36\lib\site-packages\tensorflow\python\platform\flags.py in wrapper(*args, **kwargs)
     56           'Use of the keyword argument names (flag_name, default_value, '
     57           'docstring) is deprecated, please use (name, default, help) instead.')
---> 58     return original_function(*args, **kwargs)
     59 
     60   return tf_decorator.make_decorator(original_function, wrapper)

c:\users\jinsu\appdata\local\programs\python\python36\lib\site-packages\absl\flags\_defines.py in DEFINE_float(name, default, help, lower_bound, upper_bound, flag_values, **args)
    289   parser = _argument_parser.FloatParser(lower_bound, upper_bound)
    290   serializer = _argument_parser.ArgumentSerializer()
--> 291   DEFINE(parser, name, default, help, flag_values, serializer, **args)
    292   _register_bounds_validator_if_needed(parser, name, flag_values=flag_values)
    293 

c:\users\jinsu\appdata\local\programs\python\python36\lib\site-packages\absl\flags\_defines.py in DEFINE(parser, name, default, help, flag_values, serializer, module_name, **args)
     80   """
     81   DEFINE_flag(_flag.Flag(parser, serializer, name, default, help, **args),
---> 82               flag_values, module_name)
     83 
     84 

c:\users\jinsu\appdata\local\programs\python\python36\lib\site-packages\absl\flags\_defines.py in DEFINE_flag(flag, flag_values, module_name)
    102   # Copying the reference to flag_values prevents pychecker warnings.
    103   fv = flag_values
--> 104   fv[flag.name] = flag
    105   # Tell flag_values who's defining the flag.
    106   if module_name:

c:\users\jinsu\appdata\local\programs\python\python36\lib\site-packages\absl\flags\_flagvalues.py in __setitem__(self, name, flag)
    425         # module is simply being imported a subsequent time.
    426         return
--> 427       raise _exceptions.DuplicateFlagError.from_flag(name, self)
    428     short_name = flag.short_name
    429     # If a new flag overrides an old one, we need to cleanup the old flag's

DuplicateFlagError: The flag 'learning_rate' is defined twice. First from C:\Users\Jinsu\python code\MEMN2N\ipykernel_launcher.py, Second from C:\Users\Jinsu\python code\MEMN2N\ipykernel_launcher.py.  Description from first occurrence: Initial learning rate.

the second code

import tensorflow as tf

flags = tf.app.flags 
FLAGS = tf.app.flags.FLAGS
flags.DEFINE_float('learning_rate', 0.02, 'Initial learning rate.')
flags.DEFINE_string('name', 'test', 'The name of our flag')
# FLAGS.learning_rate = 0.03
# FLAGS.name = 'Testing'

print(FLAGS.learning_rate)
print(FLAGS.name)
--------------------------------------------------------------------------------
DuplicateFlagError                        Traceback (most recent call last)
<ipython-input-6-19d9c11b9a80> in <module>()
      3 flags = tf.app.flags
      4 FLAGS = tf.app.flags.FLAGS
----> 5 flags.DEFINE_float('learning_rate', 0.02, 'Initial learning rate.')
      6 flags.DEFINE_string('name', 'test', 'The name of our flag')
      7 # FLAGS.learning_rate = 0.03

c:\users\jinsu\appdata\local\programs\python\python36\lib\site-packages\tensorflow\python\platform\flags.py in wrapper(*args, **kwargs)
     56           'Use of the keyword argument names (flag_name, default_value, '
     57           'docstring) is deprecated, please use (name, default, help) instead.')
---> 58     return original_function(*args, **kwargs)
     59 
     60   return tf_decorator.make_decorator(original_function, wrapper)

c:\users\jinsu\appdata\local\programs\python\python36\lib\site-packages\absl\flags\_defines.py in DEFINE_float(name, default, help, lower_bound, upper_bound, flag_values, **args)
    289   parser = _argument_parser.FloatParser(lower_bound, upper_bound)
    290   serializer = _argument_parser.ArgumentSerializer()
--> 291   DEFINE(parser, name, default, help, flag_values, serializer, **args)
    292   _register_bounds_validator_if_needed(parser, name, flag_values=flag_values)
    293 

c:\users\jinsu\appdata\local\programs\python\python36\lib\site-packages\absl\flags\_defines.py in DEFINE(parser, name, default, help, flag_values, serializer, module_name, **args)
     80   """
     81   DEFINE_flag(_flag.Flag(parser, serializer, name, default, help, **args),
---> 82               flag_values, module_name)
     83 
     84 

c:\users\jinsu\appdata\local\programs\python\python36\lib\site-packages\absl\flags\_defines.py in DEFINE_flag(flag, flag_values, module_name)
    102   # Copying the reference to flag_values prevents pychecker warnings.
    103   fv = flag_values
--> 104   fv[flag.name] = flag
    105   # Tell flag_values who's defining the flag.
    106   if module_name:

c:\users\jinsu\appdata\local\programs\python\python36\lib\site-packages\absl\flags\_flagvalues.py in __setitem__(self, name, flag)
    425         # module is simply being imported a subsequent time.
    426         return
--> 427       raise _exceptions.DuplicateFlagError.from_flag(name, self)
    428     short_name = flag.short_name
    429     # If a new flag overrides an old one, we need to cleanup the old flag's

DuplicateFlagError: The flag 'learning_rate' is defined twice. First from C:\Users\Jinsu\python code\MEMN2N\ipykernel_launcher.py, Second from C:\Users\Jinsu\python code\MEMN2N\ipykernel_launcher.py.  Description from first occurrence: Initial learning rate.

Actually, I got same error message.
Should I edit the ipykernel_launcher.py file??

@PiyushDatta
Copy link
Contributor

@magicmutal
I think you are trying to run both code snippets in the same file. If so, that is the reason you are getting this error:
DuplicateFlagError: The flag 'learning_rate' is defined twice.

If you want to run two flag objects in the same code snippet you must change the variable names for learning rate, try the code below:

import tensorflow as tf

flags = tf.app.flags 
FLAGS = tf.app.flags.FLAGS
flags.DEFINE_float('learning_rate_1', 0.02, 'Initial learning rate.')
flags.DEFINE_string('name', 'test', 'The name of our flag')
# FLAGS.learning_rate = 0.03
# FLAGS.name = 'Testing'

print(FLAGS.learning_rate_1)
print(FLAGS.name)


flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_float('learning_rate_2', 0.01, 'Initial learning rate.')
flags.DEFINE_integer('max_steps', 2000, 'Number of steps to run trainer.')
flags.DEFINE_integer('hidden1', 128, 'Number of units in hidden layer 1.')
flags.DEFINE_integer('hidden2', 32, 'Number of units in hidden layer 2.')
flags.DEFINE_integer('batch_size', 100, 'Batch size. '
'Must divide evenly into the dataset sizes.')
flags.DEFINE_string('train_dir', 'data', 'Directory to put the training data.')
flags.DEFINE_boolean('fake_data', False, 'If true, uses fake data '
'for unit testing.')

FLAGS = flags.FLAGS
print(FLAGS.learning_rate_2)

As you can see learning rate was changed to learning_rate_1 and learning_rate_2.
Let me know if that fixes it.

@quangvu0702
Copy link

quangvu0702 commented Apr 3, 2018

I run that code but still get the same error:

UnrecognizedFlagError Traceback (most recent call last)
in ()
8 # FLAGS.name = 'Testing'
9
---> 10 print(FLAGS.learning_rate_1)
11 print(FLAGS.name)
12

~/projects/thanos/recently_action/env3/lib/python3.6/site-packages/tensorflow/python/platform/flags.py in getattr(self, name)
82 # a flag.
83 if not wrapped.is_parsed():
---> 84 wrapped(_sys.argv)
85 return wrapped.getattr(name)
86

~/projects/thanos/recently_action/env3/lib/python3.6/site-packages/absl/flags/_flagvalues.py in call(self, argv, known_only)
628 suggestions = _helpers.get_flag_suggestions(name, list(self))
629 raise _exceptions.UnrecognizedFlagError(
--> 630 name, value, suggestions=suggestions)
631
632 self.mark_as_parsed()

UnrecognizedFlagError: Unknown command line flag 'f'

@moguzozcan
Copy link

Is there any progress on this issue, I am having the same problem?

@PiyushDatta
Copy link
Contributor

@quangvu0702 @moguzozcan are you both running tensorflow 1.6.0? And which code snippet gives you the error?

@moguzozcan
Copy link

I was getting the error first at 1.5.0 then I upgraded to the latest version 1.7.0. When I call cifar10.maybe_download_and_extract() method it gives the error. I am using anaconda.

`UnrecognizedFlagError Traceback (most recent call last)
in ()
----> 1 cifar10.maybe_download_and_extract()

D:\Google Drive\Akademik\Ozyegin\CS566\Project 2\cifar10.py in maybe_download_and_extract()
381 def maybe_download_and_extract():
382 """Download and extract the tarball from Alex's website."""
--> 383 dest_directory = FLAGS.data_dir
384 if not os.path.exists(dest_directory):
385 os.makedirs(dest_directory)

~\anaconda3\lib\site-packages\tensorflow\python\platform\flags.py in getattr(self, name)
82 # a flag.
83 if not wrapped.is_parsed():
---> 84 wrapped(_sys.argv)
85 return wrapped.getattr(name)
86

~\anaconda3\lib\site-packages\absl\flags_flagvalues.py in call(self, argv, known_only)
628 suggestions = _helpers.get_flag_suggestions(name, list(self))
629 raise _exceptions.UnrecognizedFlagError(
--> 630 name, value, suggestions=suggestions)
631
632 self.mark_as_parsed()

UnrecognizedFlagError: Unknown command line flag 'f'`

@abdullahselek
Copy link
Contributor

I had the same issue and I figured out now it works with version 1.7.0. It might be useful for the others:
import tensorflow as tf
Then define your flags with using tf.app.flags. When you finished defining flags do your assignment as FLAGS = tf.app.flags.FLAGS.

And if you need to run tf.app.run run on main function.

@chenghuige
Copy link

But how to run using jupter ?

@H-xie
Copy link

H-xie commented Apr 30, 2018

I face this problem when running code in jupyter notebook. And I don't set any flag named f.
When using command line to run the same .py file, there's no more Unknown command line flag 'f'.
May this info could help.

@drabastomek
Copy link

Same here. Any suggestions? Updated to the latest 1.8.0 version of TF

@aDataGuy
Copy link

aDataGuy commented May 2, 2018

Same here in Jupyter Notebook
(Working well in terminal)

TF version is latest (1.8.0)
Anaconda2(Python2.7) Jupyter notebook

print(FLAGS.learning_rate)
throws

UnrecognizedFlagErrorTraceback (most recent call last)
in ()
----> 1 print(FLAGS.learning_rate)

/home/budweiser/anaconda2/lib/python2.7/site-packages/tensorflow/python/platform/flags.pyc in getattr(self, name)
82 # a flag.
83 if not wrapped.is_parsed():
---> 84 wrapped(_sys.argv)
85 return wrapped.getattr(name)
86

/home/budweiser/anaconda2/lib/python2.7/site-packages/absl/flags/_flagvalues.pyc in call(self, argv, known_only)
628 suggestions = _helpers.get_flag_suggestions(name, list(self))
629 raise _exceptions.UnrecognizedFlagError(
--> 630 name, value, suggestions=suggestions)
631
632 self.mark_as_parsed()

UnrecognizedFlagError: Unknown command line flag 'f'
-----------------------------------------------------------------------------------------------------------EO.Error

This is working ...
print(FLAGS['learning_rate'].value)
0.001

@babaMar
Copy link

babaMar commented May 3, 2018

Same here:

import tensorflow as tf

flags = tf.app.flags
FLAGS = flags.FLAGS

flags.DEFINE_string("positive_data_file", "./data/raw_comments.pos", "Data source for the positive data.")
flags.DEFINE_string("neutral_data_file", "./data/raw_comments.neu", "Data source for the neutral data.")
flags.DEFINE_string("negative_data_file", "./data/raw_comments.neg", "Data source for the negative data.")

print(FLAGS.negative_data_file)

gives

---------------------------------------------------------------------------
UnrecognizedFlagError                     Traceback (most recent call last)
<ipython-input-1-27f35e1d55fc> in <module>()
      8 flags.DEFINE_string("negative_data_file", "./data/raw_comments.neg", "Data source for the negative data.")
      9 
---> 10 print(FLAGS.negative_data_file)

~/venvs/scipylearn/lib/python3.5/site-packages/tensorflow/python/platform/flags.py in __getattr__(self, name)
     82     # a flag.
     83     if not wrapped.is_parsed():
---> 84       wrapped(_sys.argv)
     85     return wrapped.__getattr__(name)
     86 

~/venvs/scipylearn/lib/python3.5/site-packages/absl/flags/_flagvalues.py in __call__(self, argv, known_only)
    628       suggestions = _helpers.get_flag_suggestions(name, list(self))
    629       raise _exceptions.UnrecognizedFlagError(
--> 630           name, value, suggestions=suggestions)
    631 
    632     self.mark_as_parsed()

UnrecognizedFlagError: Unknown command line flag 'f'

@javadba
Copy link

javadba commented May 6, 2018

I get this error on google colab. What is the way forward/workaround?

@taixhi
Copy link

taixhi commented May 8, 2018

I solved this issue by adding the line:
tf.app.flags.DEFINE_string('f', '', 'kernel')
what this essentially does is that it creates a flag f. This is effective as jupyter notebook supplies a flag "-f" to pass a name for a JSON file, likely for the kernel.

@MILAB-yhg
Copy link

@taixhi simple but cool solution there. thanks a lot.

@durakkerem
Copy link

Thanks @taixhi, that solved it for me too.

@Interstella12
Copy link

same issue, 1.8.0 and python 3.6.5.
And solved with @taixhi 's method. thanks

@iliTheFallen
Copy link

Thanks @taixhi . It is only valid for jupyter env. guys!

@ghost
Copy link

ghost commented Jul 27, 2018

Thanks a lot @taixhi, it works.

@showgood163
Copy link

This is still a bug, I'm using the native pip environment.

Have I written custom code (as opposed to using a stock example script provided in TensorFlow): custom code
OS Platform and Distribution (e.g., Linux Ubuntu 16.04): Arch Linux
TensorFlow installed from (source or binary): binary
TensorFlow version (use command below): tensorflow 1.9.0
Python version: pyhton 3.6.6
Bazel version (if compiling from source): None
GCC/Compiler version (if compiling from source): None
CUDA/cuDNN version: 9.2.148/7.1.4
GPU model and memory: GTX770m

@lucidyan
Copy link

lucidyan commented Aug 5, 2018

Your solutions works like a charm. Thanks, @taixhi !
And yes, it's still a bug

@AliMiraftab
Copy link

@taixhi very neat solution! Tnx.

@balloch
Copy link

balloch commented Sep 11, 2018

this is still a bug, and there isn't a known cause. please reopen

@ymodak
Copy link
Contributor

ymodak commented Oct 5, 2018

@magicmutal Is this still an issue? Did you get a chance to try taixhi's suggestion?

I solved this issue by adding the line:
tf.app.flags.DEFINE_string('f', '', 'kernel')
what this essentially does is that it creates a flag f. This is effective as jupyter notebook supplies a flag "-f" to pass a name for a JSON file, likely for the kernel.

@ymodak ymodak added the stat:awaiting response Status - Awaiting response from author label Oct 5, 2018
@tensorflowbutler
Copy link
Member

It has been 14 days with no activity and the awaiting response label was assigned. Is this still an issue?

@ymodak
Copy link
Contributor

ymodak commented Oct 26, 2018

Closing due to staleness. Please use the latest version for TensorFLow and build again. Feel free to open a new issue if it still persists. Thanks!

@ymodak ymodak closed this as completed Oct 26, 2018
@spotiris
Copy link

spotiris commented Dec 6, 2018

For those who are having issues using the flags module in jupyter notebooks, it is because sys.argv is populated from jupyter, not your notebook code.
Put the following in your first cell:

import sys
sys.argv = " --your flags --placed here".split(" ")
# Note the space at the beginning

@kornesh
Copy link

kornesh commented Jul 20, 2019

As @spotiris mentioned you could just remove all the cli args by

import sys
sys.argv = sys.argv[:1]

@sehargul-123
Copy link

I want to train my model but I am receiving this error kindly help me + [ ! -f DeepSpeech.py ] + python -u DeepSpeech.py --train_files /home/sehar/urdu/train/urdu-train.csv --dev_files /home/sehar/urdu/urdu-train.csv --test_files /home/sehar/urdu/train/urdu-train.csv --train_batch_size 80 --dev_batch_size 80 --test_batch_size 40 --n_hidden 375 --epochs 33 --validation_step 1 --early_stop True --earlystop_nsteps 6 --estop_mean_thresh 0.1 --dropout_rate 0.22 --learning_rate 0.00095 --report_count 100 --use_seq_length False --export_dir /home/sehar/urdu-models --checkpoint_dir /home/nvidia/DeepSpeech/checkout/ --alphabet_config_path /home/sehar/urdu-models/native_client/alphabet.txt/ /home/sehar/DeepSpeech/tensorflow/python/framework/dtypes.py:516: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint8 = np.dtype([("qint8", np.int8, 1)]) /home/sehar/DeepSpeech/tensorflow/python/framework/dtypes.py:517: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint8 = np.dtype([("quint8", np.uint8, 1)]) /home/sehar/DeepSpeech/tensorflow/python/framework/dtypes.py:518: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint16 = np.dtype([("qint16", np.int16, 1)]) /home/sehar/DeepSpeech/tensorflow/python/framework/dtypes.py:519: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint16 = np.dtype([("quint16", np.uint16, 1)]) /home/sehar/DeepSpeech/tensorflow/python/framework/dtypes.py:520: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint32 = np.dtype([("qint32", np.int32, 1)]) /home/sehar/DeepSpeech/tensorflow/python/framework/dtypes.py:525: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. np_resource = np.dtype([("resource", np.ubyte, 1)]) /home/sehar/venv/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:541: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint8 = np.dtype([("qint8", np.int8, 1)]) /home/sehar/venv/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:542: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint8 = np.dtype([("quint8", np.uint8, 1)]) /home/sehar/venv/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:543: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint16 = np.dtype([("qint16", np.int16, 1)]) /home/sehar/venv/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:544: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint16 = np.dtype([("quint16", np.uint16, 1)]) /home/sehar/venv/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:545: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint32 = np.dtype([("qint32", np.int32, 1)]) /home/sehar/venv/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:550: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. np_resource = np.dtype([("resource", np.ubyte, 1)]) FATAL Flags parsing error: Unknown command line flag 'validation_step' Pass --helpshort or --helpfull to see help on flags.

@Austinzhenghua
Copy link

I want to train my model but I am receiving this error kindly help me + [ ! -f DeepSpeech.py ] + python -u DeepSpeech.py --train_files /home/sehar/urdu/train/urdu-train.csv --dev_files /home/sehar/urdu/urdu-train.csv --test_files /home/sehar/urdu/train/urdu-train.csv --train_batch_size 80 --dev_batch_size 80 --test_batch_size 40 --n_hidden 375 --epochs 33 --validation_step 1 --early_stop True --earlystop_nsteps 6 --estop_mean_thresh 0.1 --dropout_rate 0.22 --learning_rate 0.00095 --report_count 100 --use_seq_length False --export_dir /home/sehar/urdu-models --checkpoint_dir /home/nvidia/DeepSpeech/checkout/ --alphabet_config_path /home/sehar/urdu-models/native_client/alphabet.txt/ /home/sehar/DeepSpeech/tensorflow/python/framework/dtypes.py:516: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint8 = np.dtype([("qint8", np.int8, 1)]) /home/sehar/DeepSpeech/tensorflow/python/framework/dtypes.py:517: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint8 = np.dtype([("quint8", np.uint8, 1)]) /home/sehar/DeepSpeech/tensorflow/python/framework/dtypes.py:518: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint16 = np.dtype([("qint16", np.int16, 1)]) /home/sehar/DeepSpeech/tensorflow/python/framework/dtypes.py:519: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint16 = np.dtype([("quint16", np.uint16, 1)]) /home/sehar/DeepSpeech/tensorflow/python/framework/dtypes.py:520: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint32 = np.dtype([("qint32", np.int32, 1)]) /home/sehar/DeepSpeech/tensorflow/python/framework/dtypes.py:525: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. np_resource = np.dtype([("resource", np.ubyte, 1)]) /home/sehar/venv/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:541: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint8 = np.dtype([("qint8", np.int8, 1)]) /home/sehar/venv/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:542: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint8 = np.dtype([("quint8", np.uint8, 1)]) /home/sehar/venv/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:543: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint16 = np.dtype([("qint16", np.int16, 1)]) /home/sehar/venv/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:544: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint16 = np.dtype([("quint16", np.uint16, 1)]) /home/sehar/venv/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:545: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint32 = np.dtype([("qint32", np.int32, 1)]) /home/sehar/venv/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:550: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. np_resource = np.dtype([("resource", np.ubyte, 1)]) FATAL Flags parsing error: Unknown command line flag 'validation_step' Pass --helpshort or --helpfull to see help on flags.

same to me

@Jitudebz
Copy link

Jitudebz commented Mar 9, 2020

@taixhi Could you please help me in solving for different DEFINED Parameters. As your solution just solves it for DEFINE_string by using
tf.app.flags.DEFINE_string('f', '', 'kernel')

How can I declare the flags for the below code which has integer, string and float ?

flags = tf.app.flags
FLAGS = tf.app.flags.FLAGS
flags.DEFINE_integer('hidden1', 128, 'Number of units in hidden layer 1.')
flags.DEFINE_string('train_dir', 'tf_logs', 'Directory to put the training data.')
flags.DEFINE_float('reg_constant', 0.1, 'Regularization constant.')

@chokosabe
Copy link

I can confirm this bug is very much still there. What makes it worse is a lot of the tf-agents example scripts out there have the bug baked in... It really needs fixing....

@signalprime
Copy link

bump

@zhuyuanxiang
Copy link

As @spotiris mentioned you could just remove all the cli args by

import sys
sys.argv = sys.argv[:1]

It can help me.

@zflina
Copy link

zflina commented Jul 20, 2022

Here is my code:

def Demo(inputs, labels):
"""Load the data"""
x = pd.read_csv(inputs, header = None).iloc[:,:].values
label = pd.read_csv(labels, header = None).iloc[:,:].values
batch_size = label.shape[0]
num_timestep = x.shape[0]
num_channel = 3
num_joints = 25
"""Load the scaling object"""
sc_x = joblib.load("sc_x.save")
sc_y = joblib.load("sc_y.save")

X = np.zeros((x.shape[0],num_joints*num_channel)).astype('float32')
for row in range(x.shape[0]):
    counter = 0
    for parts in body_part:
        for i in range(num_channel):
            X[row, counter+i] = x[row, parts+i]
        counter += num_channel 

X = sc_x.transform(X)         

X_ = np.zeros((batch_size, num_timestep, num_joints, num_channel))

for batch in range(X_.shape[0]):
    for timestep in range(X_.shape[1]):
        for node in range(X_.shape[2]):
            for channel in range(X_.shape[3]):
                X_[batch,timestep,node,channel] = X[timestep+(batch*num_timestep),channel+(node*num_channel)]
           
X = X_

"""Load the model and weights"""
with open('rehabilitation.json', 'r') as f:
    model_json = f.read()

model = tf.keras.models.model_from_json(model_json, custom_objects={'tf': tf})
model.load_weights("best_model.hdf5")

y_pred = model.predict(X)
y_pred = sc_y.inverse_transform(y_pred) 
print("predicted value:", y_pred[0,0])
#print()
print("actual value:", label[0,0])       

Demo(FLAGS.inputs, FLAGS.labels)

Errors are:


UnrecognizedFlagError Traceback (most recent call last)
in ()
44 print("actual value:", label[0,0])
45
---> 46 Demo(FLAGS.inputs, FLAGS.labels)

1 frames
/usr/local/lib/python3.7/dist-packages/absl/flags/_flagvalues.py in call(self, argv, known_only)
648 ValueError: Raised on flag value parsing error.
649 """
--> 650 if _helpers.is_bytes_or_string(argv):
651 raise TypeError(
652 'argv should be a tuple/list of strings, not bytes or string.')

UnrecognizedFlagError: Unknown command line flag 'f'

How I will get the solution? Please help.

@mrqorib
Copy link

mrqorib commented Aug 5, 2022

How I will get the solution? Please help.
@zflina3e You can try one of the solutions above that have the 👍emoji

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
stat:awaiting response Status - Awaiting response from author
Projects
None yet
Development

No branches or pull requests