You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TensorFlow+Keras-rl2训练CartPole-v1时遇AttributeError问题求助

解决Keras-RL2与TensorFlow 2.x兼容导致的_compile_time_distribution_strategy属性错误

问题原因

该错误源于Keras-RL2对TensorFlow 2.x的tf.keras接口存在兼容性问题:Keras-RL2底层基于旧版独立Keras实现,而你使用的是tf.keras的Sequential模型,两者在模型内部属性定义上存在差异,导致编译DQN Agent时触发属性找不到的异常。此外,TensorFlow 2.x后Adam优化器的参数命名变更(lr改为learning_rate)也会加剧兼容性冲突。

修复步骤

1. 锁定兼容的TensorFlow版本

Colab默认的TensorFlow版本通常过高,与Keras-RL2存在冲突,先安装兼容版本:

!pip install tensorflow==2.10
!pip install gym[classic_control]
!pip install keras-rl2

2. 替换为兼容的Adam优化器

使用TensorFlow提供的旧版兼容Adam优化器,并修正参数名称:

from tensorflow.keras.optimizers.legacy import Adam

编译时将原参数lr=1e-3改为learning_rate=1e-3。

3. 完整修正后的代码

!pip install tensorflow==2.10
!pip install gym[classic_control]
!pip install keras-rl2

import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten
from tensorflow.keras.optimizers.legacy import Adam
import gym

# 初始化CartPole环境
env = gym.make('CartPole-v1')
states = env.observation_space.shape[0]
actions = env.action_space.n

# 构建神经网络模型
def build_model(states, actions):
    model = Sequential()
    model.add(Flatten(input_shape=(1, states)))
    model.add(Dense(24, activation='relu'))
    model.add(Dense(24, activation='relu'))
    model.add(Dense(actions, activation='linear'))
    return model

model = build_model(states, actions)
model.summary()

# 构建DQN智能体
from rl.agents import DQNAgent
from rl.policy import BoltzmannQPolicy
from rl.memory import SequentialMemory

def build_agent(model, actions):
    policy = BoltzmannQPolicy()
    memory = SequentialMemory(limit=50000, window_length=1)
    dqn = DQNAgent(
        model=model,
        memory=memory,
        policy=policy,
        nb_actions=actions,
        nb_steps_warmup=10,
        target_model_update=1e-2
    )
    return dqn

dqn = build_agent(model, actions)
# 编译智能体(使用兼容优化器与正确参数)
dqn.compile(Adam(learning_rate=1e-3), metrics=['mae'])
# 开始训练
dqn.fit(env, nb_steps=50000, visualize=False, verbose=1)

额外说明

  • 若不想降级TensorFlow,也可尝试使用独立Keras而非tf.keras,但该方式在Colab中易引发环境依赖冲突,不推荐。
  • 训练完成后,可通过dqn.test(env, nb_episodes=5, visualize=True)测试智能体的实际运行效果。

内容的提问来源于stack exchange,提问作者Fawaz hussain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 07:45:37