什么是机器学习

Deep Deterministic Policy Gradient(DDPG)是一种用于解决连续动作空间的强化学习问题的算法。DDPG结合了深度学习和策略梯度方法,用于学习一个确定性策略。它适用于具有高维状态空间和连续动作空间的问题。

以下是一个使用 Python 和 TensorFlow/Keras 实现简单的DDPG的示例。在这个例子中,我们将使用 OpenAI Gym 的 Pendulum 环境。

import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Sequential, Model
from tensorflow.keras.layers import Dense, Input
from tensorflow.keras.optimizers import Adam
import gym

# 定义DDPG Agent
class DDPGAgent:
    def __init__(self, state_size, action_size):
        self.state_size = state_size
        self.action_size = action_size
        self.gamma = 0.99  # 折扣因子
        self.tau = 0.001  # 软更新参数
        self.actor_lr = 0.001
        self.critic_lr = 0.001

        # 构建演员(Actor)网络和目标演员网络
        self.actor = self.build_actor()
        self.target_actor = self.build_actor()
        self.target_actor.set_weights(self.actor.get_weights())

        # 构建评论家(Critic)网络和目标评论家网络
        self.critic = self.build_critic()
        self.target_critic = self.build_critic()
        self.target_critic.set_weights(self.critic.get_weights())

    def build_actor(self):
        state_input = Input(shape=(self.state_size,))
        dense1 = Dense(400, activation='relu')(state_input)
        dense2 = Dense(300, activation='relu')(dense1)
        output = Dense(self.action_size, activation='tanh')(dense2)
        model = Model(inputs=state_input, outputs=output)
        model.compile(loss='mse', optimizer=Adam(lr=self.actor_lr))
        return model

    def build_critic(self):
        state_input = Input(shape=(self.state_size,))
        action_input = Input(shape=(self.action_size,))
        concat = tf.keras.layers.concatenate([state_input, action_input])
        dense1 = Dense(400, activation='relu')(concat)
        dense2 = Dense(300, activation='relu')(dense1)
        output = Dense(1, activation='linear')(dense2)
        model = Model(inputs=[state_input, action_input], outputs=output)
        model.compile(loss='mse', optimizer=Adam(lr=self.critic_lr))
        return model

    def get_action(self, state):
        state = np.reshape(state, [1, self.state_size])
        action = self.actor.predict(state)[0]
        return action

    def train(self, state, action, reward, next_state, done):
        state = np.reshape(state, [1, self.state_size])
        next_state = np.reshape(next_state, [1, self.state_size])
        action = np.reshape(action, [1, self.action_size])
        target_action = self.target_actor.predict(next_state)
        target_value = self.target_critic.predict([next_state, target_action])[0][0]
        target = reward + self.gamma * target_value * (1 - done)

        # 训练评论家网络
        critic_loss = self.critic.train_on_batch([state, action], target)

        # 训练演员网络
        actor_loss = self.actor.train_on_batch(state, action)

        # 软更新目标网络
        self.soft_update_target_networks()

        return actor_loss, critic_loss

    def soft_update_target_networks(self):
        actor_weights = np.array(self.actor.get_weights())
        target_actor_weights = np.array(self.target_actor.get_weights())
        self.target_actor.set_weights(self.tau * actor_weights + (1 - self.tau) * target_actor_weights)

        critic_weights = np.array(self.critic.get_weights())
        target_critic_weights = np.array(self.target_critic.get_weights())
        self.target_critic.set_weights(self.tau * critic_weights + (1 - self.tau) * target_critic_weights)

# 初始化环境和Agent
env = gym.make('Pendulum-v0')
state_size = env.observation_space.shape[0]
action_size = env.action_space.shape[0]
agent = DDPGAgent(state_size, action_size)

# 训练DDPG Agent
num_episodes = 500
for episode in range(num_episodes):
    state = env.reset()
    total_reward = 0
    for time in range(500):  # 限制每个episode的步数,防止无限循环
        # env.render()  # 如果想可视化训练过程,可以取消注释此行
        action = agent.get_action(state)
        next_state, reward, done, _ = env.step(action)
        total_reward += reward
        actor_loss, critic_loss = agent.train(state, action, reward, next_state, done)
        state = next_state
        if done:
            print("Episode: {}, Total Reward: {}, Actor Loss: {:.4f}, Critic Loss: {:.4f}".format(
                episode + 1, total_reward, actor_loss, critic_loss))
            break

# 关闭环境
env.close()

在这个例子中,我们定义了一个简单的DDPG Agent,包括演员(Actor)和评论家(Critic)两个神经网络。在训练过程中,我们使用了两个目标网络来提高稳定性,并进行了软更新。

请注意,DDPG算法的实现可能因问题的复杂性而有所不同,可能需要更多的技术和调整,如归一化奖励、使用更复杂的神经网络结构等。

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐