强化学习 - Deep Q Network (DQN)

什么是机器学习

Deep Q NetworkDQN)是一种结合深度学习和强化学习的方法,用于解决离散动作空间的强化学习问题。DQN 是由DeepMind团队提出的,首次应用于解决Atari游戏,但也被广泛用于其他领域,如机器人学自动驾驶

以下是一个使用Python和TensorFlow / Keras 实现简单的DQN的示例代码。请注意,这是一个基本的实现,实际应用中可能需要进行更多的优化和调整。

import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import Adam
from collections import deque
import random
import gym

# 定义DQN Agent
class DQNAgent:
    def __init__(self, state_size, action_size):
        self.state_size = state_size
        self.action_size = action_size
        self.memory = deque(maxlen=2000)  # 经验回放内存
        self.gamma = 0.95  # 折扣因子
        self.epsilon = 1.0  # 探索概率
        self.epsilon_decay = 0.995  # 探索概率衰减
        self.epsilon_min = 0.01  # 最小探索概率
        self.learning_rate = 0.001
        self.model = self.build_model()

    def build_model(self):
        model = Sequential()
        model.add(Dense(24, input_dim=self.state_size, activation='relu'))
        model.add(Dense(24, activation='relu'))
        model.add(Dense(self.action_size, activation='linear'))
        model.compile(loss='mse', optimizer=Adam(lr=self.learning_rate))
        return model

    def remember(self, state, action, reward, next_state, done):
        self.memory.append((state, action, reward, next_state, done))

    def act(self, state):
        if np.random.rand() <= self.epsilon:
            return random.randrange(self.action_size)
        else:
            return np.argmax(self.model.predict(state)[0])

    def replay(self, batch_size):
        minibatch = random.sample(self.memory, batch_size)
        for state, action, reward, next_state, done in minibatch:
            target = reward
            if not done:
                target = reward + self.gamma * np.amax(self.model.predict(next_state)[0])
            target_f = self.model.predict(state)
            target_f[0][action] = target
            self.model.fit(state, target_f, epochs=1, verbose=0)
        if self.epsilon > self.epsilon_min:
            self.epsilon *= self.epsilon_decay

# 初始化环境和Agent
env = gym.make('CartPole-v1')
state_size = env.observation_space.shape[0]
action_size = env.action_space.n
agent = DQNAgent(state_size, action_size)

# 训练DQN
batch_size = 32
num_episodes = 1000

for episode in range(num_episodes):
    state = env.reset()
    state = np.reshape(state, [1, state_size])
    total_reward = 0
    for time in range(500):  # 限制每个episode的步数,防止无限循环
        # env.render()  # 如果想可视化训练过程,可以取消注释此行
        action = agent.act(state)
        next_state, reward, done, _ = env.step(action)
        reward = reward if not done else -10  # 对于未结束的episode,奖励为1;结束则为-10
        total_reward += reward
        next_state = np.reshape(next_state, [1, state_size])
        agent.remember(state, action, reward, next_state, done)
        state = next_state
        if done:
            print("Episode: {}, Total Reward: {}, Epsilon: {:.2}".format(episode + 1, total_reward, agent.epsilon))
            break
    if len(agent.memory) > batch_size:
        agent.replay(batch_size)

# 关闭环境
env.close()

在这个例子中,我们使用 OpenAI Gym 提供的 CartPole 环境作为示例。DQN Agent 的神经网络模型使用简单的全连接层。训练过程中,Agent通过经验回放(experience replay)来学习,并使用ε-greedy策略选择动作。通过运行多个episode,Agent逐渐学习到达得分较高的策略。

请注意,DQN的具体实现可能因问题的复杂性而有所不同,而且可能需要更多的技术来提高稳定性和性能,如双Q网络优先级经验回放等。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值