理解这个错误的关键在于区分 tf_agents 中 timestepspec 的作用和实际 timestep 张量的结构。
TimeStepSpec (时间步规范):
TimeStep 张量 (实际时间步数据):
InvalidArgumentError: 'then' and 'else' must have the same size. but received: [1] vs. [] 这个错误通常发生在 tf_agents 内部的 tf.where 操作中,尤其是在 EpsilonGreedyPolicy(collect_policy 通常是这种策略)的探索逻辑里。tf.where(condition, x, y) 函数要求 x 和 y 具有兼容的形状。当 TimeStepSpec 和实际 TimeStep 张量的形状定义出现不一致时,就会导致这种错误。
最常见的误区是,当某个时间步组件(如 step_type, reward, discount)本质上是标量时,在 TimeStepSpec 中将其 shape 定义为 (1,) 而非 ()。
错误定义示例 (在 TimeStepSpec 中):
reward = tensor_spec.TensorSpec(shape=(1,), dtype=tf.float32) # 错误:期望单样本是一个1维向量
这里,shape=(1,) 意味着每个样本是一个包含一个元素的1维向量。然而,reward 通常是一个标量。当 collect_policy 内部处理这些标量值时,如果它期望一个真正的标量(即形状为 ()),但实际从 TimeStep 张量中得到的是一个形状为 (1,) 的张量,或者在与 TensorSpec 匹配时发生隐式形状转换,就可能导致 [1] vs [] 的不匹配。
实际张量 (当 batch_size=1 时):
reward_tensor = tf.convert_to_tensor([reward_value], dtype=tf.float32) # 形状为 (1,)
这个 (1,) 形状是正确的,它表示一个批次中包含一个标量。问题在于 TimeStepSpec 没有正确地将它视为一个批次中的标量。
解决此问题的关键在于确保 TimeStepSpec 中的 shape 定义反映单个样本的真实形状,并且实际 TimeStep 张量在构造时包含正确的批处理维度。
这些组件在每个时间步通常都是单个数值(标量)。
TimeStepSpec 中的正确定义: 将 shape=(1,) 更正为 shape=(),表示一个标量。
from tf_agents.specs import tensor_spec import tensorflow as tf from tf_agents.trajectories.time_step import TimeStep # ... 其他导入 ... # 修正后的 TimeStepSpec 定义 time_step_spec = TimeStep( step_type=tensor_spec.BoundedTensorSpec(shape=(), dtype=tf.int32, minimum=0, maximum=2), reward=tensor_spec.TensorSpec(shape=(), dtype=tf.float32), discount=tensor_spec.TensorSpec(shape=(), dtype=tf.float32), # 观测值根据其本身的维度定义,见下文 observation=tensor_spec.TensorSpec(shape=(amountMachines,), dtype=tf.int32) )
实际 TimeStep 张量的正确构造 (针对 batch_size=1): 使用 tf.convert_to_tensor([value], dtype=...) 来创建一个形状为 (1,) 的张量,表示一个批次中包含一个标量。
# 假设 step_type_value, reward_value, discount_value 是Python标量 time_step = TimeStep( step_type=tf.convert_to_tensor([step_type_value], dtype=tf.int32), # 形状 (1,) reward=tf.convert_to_tensor([reward_value], dtype=tf.float32), # 形状 (1,) discount=tf.convert_to_tensor([discount_value], dtype=tf.float32), # 形状 (1,) observation=current_state_batch # 观测值构造见下文 )
观测值通常是向量或更高维的张量。
# ... 在 time_step_spec 定义中 ... observation=
以上就是TensorFlow DQNAgent collect_policy InvalidArgumentError 解决方案:TimeStepSpec 与 TimeStep 张量形状匹配指南的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号