TensorFlow报StridedSlice索引越界InvalidArgumentError如何解决?
TensorFlow维度越界报错解决方法
报错根因
触发错误的核心原因有两个:
- 输入模型的
state没有添加batch维度,导致模型输出的action_probs形状为(动作数,)(仅1个维度),用[0, action]索引相当于尝试访问不存在的第二维度,触发维度错误。 - 动作选择逻辑混淆了动作值和动作索引,直接将采样得到的动作值作为索引取概率,当动作值大于动作总数时就会触发索引越界。
修复步骤
- 第一步:给输入张量增加batch维度
将state = tf.convert_to_tensor(state,np.float32)替换为:
state = tf.expand_dims(tf.convert_to_tensor(state, np.float32), axis=0)
修改后输入形状符合模型要求的(batch_size, 2),输出action_probs形状会变为(1, 动作总数),双维度索引合法。
- 第二步:修复
random_actions方法的冗余逻辑
原方法循环内重复赋值actions变量导致返回值异常,修改为:
def random_actions(self,cur_state): s=[] dest=9 states=self.get_state(cur_state) for index, tuple in enumerate(states): actions=tuple[0] weights=tuple[1] s.append(actions) return s
- 第三步:修正动作采样和概率取值逻辑
区分动作索引和动作值,避免用动作值当索引访问数组:
# 原错误写法 # action = np.random.choice(num_actions, p=np.squeeze(action_probs[0])) # action_probs_history.append(tf.math.log(action_probs[0, action])) # 修正后写法 action_idx = np.random.choice(len(num_actions), p=np.squeeze(action_probs)) action = num_actions[action_idx] action_probs_history.append(tf.math.log(action_probs[0, action_idx]))
验证方法
修改完成后可以在调用模型后打印action_probs.shape,确认输出形状为(1, N),且N等于len(num_actions),即修复完成。
内容的提问来源于stack exchange,提问作者Manz
相关产品推荐
相关产品推荐

