absl.flags._exceptions.UnparsedFlagAccessError: Trying to access flag --model_dir before flags were parsed.
when I run python research/object_detection/model_main.py --pipeline_config_path='./research/object_detection/trainmodels/ssd_mobilenet_v1_pets.config' --model_dir='./research/object_detection/trained2012/'
Traceback (most recent call last):
File "research/object_detection/model_main.py", line 103, in
Thank you for your post. We noticed you have not filled out the following field in the issue template. Could you update them if they are relevant in your case, or leave them as N/A? Thanks. What is the top-level directory of the model you are using Have I written custom code OS Platform and Distribution TensorFlow installed from TensorFlow version Bazel version CUDA/cuDNN version GPU model and memory Exact command to reproduce
I had the same issue, it got resolved by using the flags = tf.app.flags instead of absl
@pkulzc I'm facing the same issue. @sujaybabruwad could you tell me more how exactly you fixed this issue?
ERROR: absl.flags._exceptions.UnparsedFlagAccessError: Trying to access flag --model_dir before flags were parsed.
What is the top-level directory of the model you are using: models/ Have I written custom code: No OS Platform and Distribution: OSX 10.13.6 TensorFlow installed from: Official Website TensorFlow version: 1.4.0 Bazel version: 0.13.0-homebrew CUDA/cuDNN version: N/A GPU model and memory: N/A Exact command to reproduce
python object_detection/model_main.py --pipeline_config_path=$PIPELINE_CONFIG_PATH --model_dir=$MODEL_DIR --num_train_steps=$NUM_TRAIN_STEPS --num_eval_steps=$NUM_EVAL_STEPS --alsologtostderr
Thank you @sujaybabruwad,I have solved the problem! I modified the model_main.py as follows: comment:from absl import flags change:flags.DEFINE_string => tf.app.flags.DEFINE_string add:FLAGS = tf.app.flags.FLAGS comment:flags.mark_flag_as_required('model_dir') comment:flags.mark_flag_as_required('pipeline_config_path') add: if not FLAGS.model_dir: raise ValueError('You must supply the model_dir') if not FLAGS.pipeline_config_path: raise ValueError('You must supply the pipeline_config_path')
Thanks @AlloyMe for the solution.
There are more errors from other modules.
object_detection/builders/dataset_builder.py", line 76, in read_dataset
tf.contrib.data.parallel_interleave(
AttributeError: 'module' object has no attribute 'parallel_interleave'
object_detection/model_lib.py", line 217, in model_fn
labels[fields.InputDataFields.groundtruth_boxes].get_shape()
TypeError: 'NoneType' object has no attribute '__getitem__'
hello @ajinkyapuar,I also meet this problem, AttributeError: module 'tensorflow.contrib.data' has no attribute 'parallel_interleave' I find a solution in a blog that says you should update your tensorflow version.
@AlloyMei @pkulzc After updating tensorflow 1.9
$ python object_detection/model_main.py --pipeline_config_path=$PIPELINE_CONFIG_PATH --model_dir=$MODEL_DIR --num_train_steps=$NUM_TRAIN_STEPS --num_eval_steps=$NUM_EVAL_STEPS --alsologtostderr
/Users/username/anaconda/envs/tensorflow/lib/python2.7/site-packages/h5py/init.py:36: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected 96, got 88 from ._conv import register_converters as _register_converters /Users/username/anaconda/envs/tensorflow/lib/python2.7/site-packages/h5py/init.py:45: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected 96, got 88 from . import h5a, h5d, h5ds, h5f, h5fd, h5g, h5r, h5s, h5t, h5p, h5z /Users/username/anaconda/envs/tensorflow/lib/python2.7/site-packages/h5py/_hl/group.py:22: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected 96, got 88 from .. import h5g, h5i, h5o, h5r, h5t, h5l, h5p /Users/username/anaconda/envs/tensorflow/lib/python2.7/site-packages/matplotlib/init.py:1405: UserWarning: This call to matplotlib.use() has no effect because the backend has already been chosen; matplotlib.use() must be called before pylab, matplotlib.pyplot, or matplotlib.backends is imported for the first time.
warnings.warn(_use_error_msg)
WARNING:tensorflow:Estimator's model_fn (<function model_fn at 0x12e07b6e0>) includes params argument, but params are not passed to Estimator.
2018-07-31 19:17:36.553418: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA
Traceback (most recent call last):
File "object_detection/model_main.py", line 105, in
Caused by op u'save/Assign_3', defined at:
File "object_detection/model_main.py", line 105, in
InvalidArgumentError (see above for traceback): Assign requires shapes of both tensors to match. lhs shape= [1,1,512,6] rhs shape= [1,1,512,273] [[Node: save/Assign_3 = Assign[T=DT_FLOAT, _class=["loc:@BoxPredictor_0/ClassPredictor/weights"], use_locking=true, validate_shape=true, _device="/job:localhost/replica:0/task:0/device:CPU:0"](BoxPredictor_0/ClassPredictor/weights, save/RestoreV2:3)]]
@ajinkyapuar maybe this discussion may help you:https://github.com/tensorflow/tensorflow/issues/6883
@AlloyMei I'm facing the same issue.I have modified my code according to your answer, but it raised another problem.
Traceback (most recent call last):
File "D:/2 索恒信息/TensorFlow/tensorflow-models/research/object_detection/model_main.py", line 110, in
Could you give me any suggestion? Thank you very much. My QQ number is 740052959
FLAGS arguments should be used in main() function where they are parsed, like:
flags.DEFINE_string('x', "", "some explation")
FLAGS = flags.FLAGS
x = FLAGS.x # produce such error
def main(unused_argv):
x = FLAGS.x # work fine!
Traceback (most recent call last): File "DeepSpeech.py", line 11, in import absl.app File "/home/sehar/venv/lib/python3.6/site-packages/absl/app.py", line 40, in from absl import flags File "/home/sehar/venv/lib/python3.6/site-packages/absl/flags/init.py", line 41, in from absl.flags import _defines File "/home/sehar/venv/lib/python3.6/site-packages/absl/flags/_defines.py", line 31, in from absl.flags import _flagvalues File "/home/sehar/venv/lib/python3.6/site-packages/absl/flags/_flagvalues.py", line 27, in import logging File "/home/sehar/DeepSpeech/logging.py", line 6, in from util.flags import FLAGS File "/home/sehar/DeepSpeech/util/flags.py", line 6, in FLAGS = absl.flags.FLAGS AttributeError: module 'absl' has no attribute 'flags' kindly help me to slove this error
当我运行python research / object_detection / model_main.py --pipeline_config_path ='。/ research / object_detection / trainmodels / ssd_mobilenet_v1_pets.config'--model_dir ='。/ research / object_detection / trained2012 /'
追溯(最近一次通话最近): tf.app.run()中的 文件“ research / object_detection / model_main.py”,行103,文件“ /home/hd/.local/lib/python3.5/site-packages/ tensorflow / python / platform / app.py”,第48行,在运行 _sys.exit(main(_sys.argv [:1] + flags_passthrough)) 文件“ research / object_detection / model_main.py”,第57行,在主 配置中= tf.estimator.RunConfig(model_dir = FLAGS.model_dir) 文件“ /home/hd/.local/lib/python3.5/site-packages/absl/flags/_flagvalues.py”,第488行,在getattr中 引发_exceptions。 UnparsedFlagAccessError (error_message)absl.flags._exceptions.UnparsedFlagAccessError:尝试在解析标志之前访问标志--model_dir。
亲,我和你一样的问题,想请问一下您当时是怎么解决的?
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you.
Closing as stale. Please reopen if you'd like to work on this further.
When I run train.py, show an error: absl.flags._exceptions.UnparsedFlagAccessError What is the top-level directory of the model you are using:python3.8_tf220/CFR-RL Have I written custom code:No OS Platform and Distribution: window 10 TensorFlow installed from:Anaconda and Official Website TensorFlow version :2.2.0 CUDA/cuDNN version: cuda10.1 and cudnn 7.6.5 `from future import print_function
import numpy as np from tqdm import tqdm import multiprocessing as mp from absl import app from absl import flags
import tensorflow as tf from env import Environment from game import CFRRL_Game from model import Network from config import get_config
FLAGS = flags.FLAGS flags.DEFINE_integer('num_agents', 2, 'number of agents') flags.DEFINE_string('baseline', 'avg', 'avg: use average reward as baseline, best: best reward as baseline') flags.DEFINE_integer('num_iter', 1, 'Number of iterations each agent would run')
GRADIENTS_CHECK = False
def central_agent(config, game, model_weights_queues, experience_queues): network = Network(config, game.state_dims, game.action_dim, game.max_moves, master=True) network.save_hyperparams(config) start_step = network.restore_ckpt() for step in tqdm(range(start_step, config.max_step), ncols=70, initial=start_step): network.ckpt.step.assign_add(1) model_weights = network.model.get_weights()
for i in range(FLAGS.num_agents):
model_weights_queues[i].put(model_weights)
if config.method == 'actor_critic':
# assemble experiences from the agents
s_batch = []
a_batch = []
r_batch = []
for i in range(FLAGS.num_agents):
s_batch_agent, a_batch_agent, r_batch_agent = experience_queues[i].get()
assert len(s_batch_agent) == FLAGS.num_iter, \
(len(s_batch_agent), len(a_batch_agent), len(r_batch_agent))
s_batch += s_batch_agent
a_batch += a_batch_agent
r_batch += r_batch_agent
assert len(s_batch) * game.max_moves == len(a_batch)
# used shared RMSProp, i.e., shared g
actions = np.eye(game.action_dim, dtype=np.float32)[np.array(a_batch)]
value_loss, entropy, actor_gradients, critic_gradients = network.actor_critic_train(np.array(s_batch),
actions,
np.array(
r_batch).astype(
np.float32),
config.entropy_weight)
if GRADIENTS_CHECK:
for g in range(len(actor_gradients)):
assert np.any(np.isnan(actor_gradients[g])) == False, (
'actor_gradients', s_batch, a_batch, r_batch, entropy)
for g in range(len(critic_gradients)):
assert np.any(np.isnan(critic_gradients[g])) == False, (
'critic_gradients', s_batch, a_batch, r_batch)
if step % config.save_step == config.save_step - 1:
network.save_ckpt(_print=True)
# log training information
actor_learning_rate = network.lr_schedule(network.actor_optimizer.iterations.numpy()).numpy()
avg_value_loss = np.mean(value_loss)
avg_reward = np.mean(r_batch)
avg_entropy = np.mean(entropy)
network.inject_summaries({
'learning rate': actor_learning_rate,
'value loss': avg_value_loss,
'avg reward': avg_reward,
'avg entropy': avg_entropy
}, step)
print('lr:%f, value loss:%f, avg reward:%f, avg entropy:%f' % (
actor_learning_rate, avg_value_loss, avg_reward, avg_entropy))
elif config.method == 'pure_policy':
# assemble experiences from the agents
s_batch = []
a_batch = []
r_batch = []
ad_batch = []
for i in range(FLAGS.num_agents):
s_batch_agent, a_batch_agent, r_batch_agent, ad_batch_agent = experience_queues[i].get()
assert len(s_batch_agent) == FLAGS.num_iter, \
(len(s_batch_agent), len(a_batch_agent), len(r_batch_agent), len(ad_batch_agent))
s_batch += s_batch_agent
a_batch += a_batch_agent
r_batch += r_batch_agent
ad_batch += ad_batch_agent
assert len(s_batch) * game.max_moves == len(a_batch)
# used shared RMSProp, i.e., shared g
actions = np.eye(game.action_dim, dtype=np.float32)[np.array(a_batch)]
entropy, gradients = network.policy_train(np.array(s_batch),
actions,
np.vstack(ad_batch).astype(np.float32),
config.entropy_weight)
if GRADIENTS_CHECK:
for g in range(len(gradients)):
assert np.any(np.isnan(gradients[g])) == False, (s_batch, a_batch, r_batch)
if step % config.save_step == config.save_step - 1:
network.save_ckpt(_print=True)
# log training information
learning_rate = network.lr_schedule(network.optimizer.iterations.numpy()).numpy()
avg_reward = np.mean(r_batch)
avg_advantage = np.mean(ad_batch)
avg_entropy = np.mean(entropy)
network.inject_summaries({
'learning rate': learning_rate,
'avg reward': avg_reward,
'avg advantage': avg_advantage,
'avg entropy': avg_entropy
}, step)
print('lr:%f, avg reward:%f, avg advantage:%f, avg entropy:%f' % (
learning_rate, avg_reward, avg_advantage, avg_entropy))
def agent(agent_id, config, game, tm_subset, model_weights_queue, experience_queue): global ad_batch, policy random_state = np.random.RandomState(seed=agent_id) network = Network(config, game.state_dims, game.action_dim, game.max_moves, master=False)
# initial synchronization of the model weights from the coordinator
model_weights = model_weights_queue.get()
network.model.set_weights(model_weights)
idx = 0
s_batch = []
a_batch = []
r_batch = []
if config.method == 'pure_policy':
ad_batch = []
run_iteration_idx = 0
num_tms = len(tm_subset)
random_state.shuffle(tm_subset)
run_iterations = FLAGS.num_iter
while True:
tm_idx = tm_subset[idx]
# state
state = game.get_state(tm_idx)
s_batch.append(state)
# action
if config.method == 'actor_critic':
policy = network.actor_predict(np.expand_dims(state, 0)).numpy()[0]
elif config.method == 'pure_policy':
policy = network.policy_predict(np.expand_dims(state, 0)).numpy()[0]
assert np.count_nonzero(policy) >= game.max_moves, (policy, state)
actions = random_state.choice(game.action_dim, game.max_moves, p=policy, replace=False)
for a in actions:
a_batch.append(a)
# reward
reward = game.reward(tm_idx, actions)
r_batch.append(reward)
if config.method == 'pure_policy':
# advantage
if config.baseline == 'avg':
ad_batch.append(game.advantage(tm_idx, reward))
game.update_baseline(tm_idx, reward)
elif config.baseline == 'best':
best_actions = policy.argsort()[-game.max_moves:]
best_reward = game.reward(tm_idx, best_actions)
ad_batch.append(reward - best_reward)
run_iteration_idx += 1
if run_iteration_idx >= run_iterations:
# Report experience to the coordinator
if config.method == 'actor_critic':
experience_queue.put([s_batch, a_batch, r_batch])
elif config.method == 'pure_policy':
experience_queue.put([s_batch, a_batch, r_batch, ad_batch])
# print('report', agent_id)
# synchronize the network parameters from the coordinator
model_weights = model_weights_queue.get()
network.model.set_weights(model_weights)
del s_batch[:]
del a_batch[:]
del r_batch[:]
if config.method == 'pure_policy':
del ad_batch[:]
run_iteration_idx = 0
# Update idx
idx += 1
if idx == num_tms:
random_state.shuffle(tm_subset)
idx = 0
def main(_): # cpu only tf.config.experimental.set_visible_devices([], 'GPU') tf.get_logger().setLevel('INFO') # tf.debugging.set_log_device_placement(True)
config = get_config(FLAGS) or FLAGS
env = Environment(config, is_training=True)
game = CFRRL_Game(config, env)
model_weights_queues = []
experience_queues = []
if FLAGS.num_agents == 0 or FLAGS.num_agents >= mp.cpu_count():
FLAGS.num_agents = mp.cpu_count() - 1
print('Agent num: %d, iter num: %d\n' % (FLAGS.num_agents + 1, FLAGS.num_iter))
for _ in range(FLAGS.num_agents):
model_weights_queues.append(mp.Queue(1))
experience_queues.append(mp.Queue(1))
tm_subsets = np.array_split(game.tm_indexes, FLAGS.num_agents)
coordinator = mp.Process(target=central_agent, args=(config, game, model_weights_queues, experience_queues))
coordinator.start()
agents = []
for i in range(FLAGS.num_agents):
agents.append(mp.Process(target=agent,
args=(i, config, game, tm_subsets[i], model_weights_queues[i], experience_queues[i])))
for i in range(FLAGS.num_agents):
agents[i].start()
coordinator.join()
if name == 'main': app.run(main) `
When I run train.py, show an error: absl.flags._exceptions.UnparsedFlagAccessError:
[!] Unmatched hyperparameter: learning_rate_decay_step 500 1
Save hyper parameters: ./tf_ckpts/TE_v2-CFR-RL_actor_critic_Conv_Abilene_TM/hyper_parameters
Initializing from scratch.
0%| | 0/1 [00:00<?, ?it/s]
Process Process-1:
Traceback (most recent call last):
File "D:\Anaconda3\envs\tensorflow220\lib\multiprocessing\process.py", line 315, in _bootstrap
self.run()
File "D:\Anaconda3\envs\tensorflow220\lib\multiprocessing\process.py", line 108, in run
self._target(*self._args, **self._kwargs)
File "D:\PythonProjects\python3.8_tf220\CFR-RL\train.py", line 31, in central_agent
for i in range(FLAGS.num_agents):
File "D:\Anaconda3\envs\tensorflow220\lib\site-packages\absl\flags\_flagvalues.py", line 499, in __getattr__
raise _exceptions.UnparsedFlagAccessError(error_message)
absl.flags._exceptions.UnparsedFlagAccessError: Trying to access flag --num_agents before flags were parsed.