agents: AttributeError: 'tuple' object has no attribute 'rank'

Trying out the most basic example on

  • Windows 10
  • Python 3.7
  • tensorflow 2.1.0
  • tf-agents 0.4.0

Error i get

Traceback (most recent call last):
  File "src\agent.py", line 58, in <module>
    action, _states = agent.policy.action(obs)
  File "C:\Users\andre\.virtualenvs\ZeusTrader\lib\site-packages\tf_agents\policies\tf_policy.py", line 279, in action
    step = action_fn(time_step=time_step, policy_state=policy_state, seed=seed)
  File "C:\Users\andre\.virtualenvs\ZeusTrader\lib\site-packages\tf_agents\utils\common.py", line 154, in with_check_resource_vars
    return fn(*fn_args, **fn_kwargs)
  File "C:\Users\andre\.virtualenvs\ZeusTrader\lib\site-packages\tf_agents\policies\random_tf_policy.py", line 89, in _action
    outer_dims = nest_utils.get_outer_shape(time_step, self._time_step_spec)
  File "C:\Users\andre\.virtualenvs\ZeusTrader\lib\site-packages\tf_agents\utils\nest_utils.py", line 394, in get_outer_shape
    nested_tensor, spec, num_outer_dims=num_outer_dims):
  File "C:\Users\andre\.virtualenvs\ZeusTrader\lib\site-packages\tf_agents\utils\nest_utils.py", line 97, in is_batched_nested_tensors
    if any(spec_shape.rank is None for spec_shape in spec_shapes):
  File "C:\Users\andre\.virtualenvs\ZeusTrader\lib\site-packages\tf_agents\utils\nest_utils.py", line 97, in <genexpr>
    if any(spec_shape.rank is None for spec_shape in spec_shapes):
AttributeError: 'tuple' object has no attribute 'rank'

Code i run

import tensorflow as tf
from collections import Counter, defaultdict
from tf_agents.networks import q_network
from tf_agents.utils import common
from tf_agents.agents.dqn import dqn_agent
from tf_agents.agents.random.random_agent import RandomAgent
from tf_agents.environments import suite_gym
from environment import StockExchangeEnv01

# tried with and without..error persists
# tf.compat.v1.enable_v2_behavior()

learning_rate = 0.0001
optimizer = tf.compat.v1.train.AdamOptimizer(learning_rate=learning_rate)

# tried both my own Environment and the basic "cartpole-v0"
train_env = StockExchangeEnv01()
env_name = 'CartPole-v0'
#train_env = suite_gym.load(env_name)

train_env.reset()
print(train_env.action_spec())
"""
# Neural Net of the Agent. This NN will get x (env) and spit out y (action).
q_net = q_network.QNetwork(
  train_env.observation_spec(),
  train_env.action_spec(),
  fc_layer_params=(100,))
print(train_env.action_spec())

#
agent = dqn_agent.DqnAgent(
  train_env.time_step_spec(),
  train_env.action_spec(),
  q_network=q_net,
  optimizer=optimizer)
"""

# tried both..dqn agent and random agent

agent = RandomAgent(
    train_env.time_step_spec(),
    train_env.action_spec()
)
agent.initialize()

obs = train_env.reset()
actions = Counter()
pnl = defaultdict(float)
total_rewards = 0.0

for i in range(300):
    #action, _states = model.predict(obs)
    action, _states = agent.policy.action(obs)
    obs, rewards, dones, info = train_env.step(action)
    actions[action[0].item()] += 1
    pnl[action[0].item()] += rewards
    total_rewards += rewards
    if dones:
        break

print('actions : {}'.format(actions))
print('rewards : {}'.format(total_rewards))

The code in tf agents gets the ‘shape’ from the action_spec, which is a tuple in my case. Then it tries to retrieve key “rank” from a tuple.

What am i missing?

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 1
  • Comments: 15 (6 by maintainers)

Commits related to this issue

Most upvoted comments

I had a similar problem, that the method _check_action_spec() located in agents/dqn/dqn_agents.py on line 264 threw the same error (‘tuple’ object has no attribute ‘rank’).

I was able to fix it by wrapping a Python Environment in TensorFlow like this:

from tf_agents.environments import tf_py_environment
environment = tf_py_environment.TFPyEnvironment(environment)

Hope this can help those who look for a quick fix.

Fixed it… need to use TensorSpec and BoundedTensorSpec instead of ArraySpec, e.g.:

self.observation_spec = TensorSpec((options['state_dimensions'],), np.dtype('float32'), 'observation')
self.reward_spec = TensorSpec((1,), np.dtype('float32'), 'reward')
self.action_spec = BoundedTensorSpec((1,), np.dtype('int32'), minimum=0, maximum=2, name='action')
self.time_step_spec = time_step.time_step_spec(self.observation_spec)

self.optimizer = tf.compat.v1.train.AdamOptimizer(learning_rate=options['learning_rate'])
self.q_network = q_network.QNetwork(self.observation_spec, self.action_spec, fc_layer_params=options['fc_layer_params'])
self.agent = dqn_agent.DqnAgent(self.time_step_spec, self.action_spec
	, q_network = self.q_network
	, optimizer = self.optimizer
	, td_errors_loss_fn = common.element_wise_squared_loss
	, epsilon_greedy = 0.1
	, gamma = 0.9)

Fixed it… need to use TensorSpec and BoundedTensorSpec instead of ArraySpec, e.g.:

self.observation_spec = TensorSpec((options['state_dimensions'],), np.dtype('float32'), 'observation')
self.reward_spec = TensorSpec((1,), np.dtype('float32'), 'reward')
self.action_spec = BoundedTensorSpec((1,), np.dtype('int32'), minimum=0, maximum=2, name='action')
self.time_step_spec = time_step.time_step_spec(self.observation_spec)

self.optimizer = tf.compat.v1.train.AdamOptimizer(learning_rate=options['learning_rate'])
self.q_network = q_network.QNetwork(self.observation_spec, self.action_spec, fc_layer_params=options['fc_layer_params'])
self.agent = dqn_agent.DqnAgent(self.time_step_spec, self.action_spec
	, q_network = self.q_network
	, optimizer = self.optimizer
	, td_errors_loss_fn = common.element_wise_squared_loss
	, epsilon_greedy = 0.1
	, gamma = 0.9)

Saved me a bunch of time, I was stuck on the same thing. Appreciate you commenting!

I wasn’t quite able to unify the two, but I made the agents try to auto-convert from ArraySpec to TensorSpec whenever possible. This code still hits errors though so I’ll add some additional fixes specific to DQN.

Thanks for the repro! Will look at fixing this.

I got the same error while implementing pure TF-env without python wrappers.

Looks like a bug. Simple repo:

from tf_agents.environments import suite_gym
from tf_agents.utils import nest_utils

train_env = suite_gym.load('CartPole-v0')
time_step = train_env.reset()
print(obs)
print(train_env.time_step_spec())
nest_utils.get_outer_shape(obs, train_env.time_step_spec())

Eugene, could you please take a look?

From your error message, it looks like it’s actually failing at “get_outer_shape(time_step, self._time_step_spec)” - when it was trying to get the rank for the time steps.

Could you print train_env.time_step_spec() and obs and verify that they match?