DQN算法训练atari游戏breakout,训练越往后越慢,游戏停滞不前

在Atari游戏breakout-v0中,智能体的action_space包括4个动作。重要的是,要启动游戏并发射小球,必须执行动作1-FIRE。然而,作者遇到的问题是其训练的模型在经历失败后未能学习到执行此动作,导致游戏无法进展。这需要对模型进行调整,使其能正确响应游戏状态并适时发射小球。
摘要由CSDN通过智能技术生成

breakout-v0的action_space有4个动作,分别是0-NOOP,1-FIRE,2-RIGHT,3-LEFT。之前一直以为环境默认发出小球供击打,其实发出小球需要智能体做出动作1-FIRE。而我的模型没有学会在一小轮失败后做出动作1,故一直环境停滞不前。

DQN算法对Atari训练的代码如下: ```python import gym import numpy as np import tensorflow as tf env = gym.make('SpaceInvaders-v0') state_size = env.observation_space.shape action_size = env.action_space.n # Hyperparameters learning_rate = 0.001 memory_size = 1000000 batch_size = 32 gamma = 0.99 epsilon = 1.0 epsilon_min = 0.01 epsilon_decay = 0.995 target_update_frequency = 10000 num_episodes = 10000 max_steps = 5000 # Replay Memory memory = [] # Q-Network class QNetwork: def __init__(self, state_size, action_size, learning_rate): self.state_size = state_size self.action_size = action_size self.learning_rate = learning_rate self.inputs = tf.placeholder(tf.float32, [None, *state_size]) self.actions = tf.placeholder(tf.float32, [None, action_size]) self.targets = tf.placeholder(tf.float32, [None]) conv1 = tf.layers.conv2d(inputs=self.inputs, filters=32, kernel_size=[8,8], strides=[4,4], padding="VALID", activation=tf.nn.relu) conv2 = tf.layers.conv2d(inputs=conv1, filters=64, kernel_size=[4,4], strides=[2,2], padding="VALID", activation=tf.nn.relu) conv3 = tf.layers.conv2d(inputs=conv2, filters=64, kernel_size=[3,3], strides=[1,1], padding="VALID", activation=tf.nn.relu) flatten = tf.layers.flatten(conv3) fc1 = tf.layers.dense(inputs=flatten, units=512, activation=tf.nn.relu) self.output = tf.layers.dense(inputs=fc1, units=action_size) self.loss = tf.reduce_mean(tf.square(self.targets - tf.reduce_sum(tf.multiply(self.output, self.actions), axis=1))) self.optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate).minimize(self.loss) # DQN Agent class DQNAgent: def __init__(self, state_size, action_size, learning_rate, memory_size, batch_size, gamma, epsilon, epsilon_min, epsilon_decay, target_update_frequency): self.state_size = state_size self.action_size = action_size self.learning_rate = learning_rate self.memory_size = memory_size self.batch_size = batch_size self.gamma = gamma self.epsilon = epsilon self.epsilon_min = epsilon_min self.epsilon_decay = epsilon_decay self.target_update_frequency = target_update_frequency self.q_network = QNetwork(state_size, action_size, learning_rate) self.target_network = QNetwork(state_size, action_size, learning_rate) self.replay_memory = [] self.timestep = 0 self.sess = tf.Session() self.sess.run(tf.global_variables_initializer()) def act(self, state): if np.random.rand() <= self.epsilon: return np.random.choice(self.action_size) q_values = self.sess.run(self.q_network.output, feed_dict={self.q_network.inputs: state.reshape(1, *self.state_size)}) return np.argmax(q_values[0]) def remember(self, state, action, reward, next_state, done): self.replay_memory.append((state, action, reward, next_state, done)) if len(self.replay_memory) > self.memory_size: self.replay_memory.pop(0) def replay(self): if len(self.replay_memory) < self.batch_size: return samples = np.random.choice(self.replay_memory, self.batch_size) states, actions, rewards, next_states, dones = map(np.array, zip(*samples)) targets = rewards + self.gamma * (np.amax(self.target_network.output.eval(feed_dict={self.target_network.inputs: next_states}), axis=1)) * (1 - dones) targets_full = self.q_network.output.eval(feed_dict={self.q_network.inputs: states}) targets_full[np.arange(self.batch_size), actions] = targets self.q_network.optimizer.run(feed_dict={self.q_network.inputs: states, self.q_network.actions: np.eye(self.action_size)[actions], self.q_network.targets: targets_full}) if self.timestep % self.target_update_frequency == 0: self.target_network = self.q_network self.timestep += 1 def train(self, num_episodes, max_steps): for i in range(num_episodes): state = env.reset() done = False total_reward = 0 for j in range(max_steps): action = self.act(state) next_state, reward, done, _ = env.step(action) self.remember(state, action, reward, next_state, done) state = next_state total_reward += reward self.replay() if done: break if self.epsilon > self.epsilon_min: self.epsilon *= self.epsilon_decay print("Episode: {}, Reward: {}".format(i, total_reward)) agent = DQNAgent(state_size, action_size, learning_rate, memory_size, batch_size, gamma, epsilon, epsilon_min, epsilon_decay, target_update_frequency) agent.train(num_episodes, max_steps) ``` 这个代码实现了DQN算法,使用TensorFlow实现了Q-Network和Target-Network。在每个episode中,循环执行以下步骤: 1. 根据当前状态选择一个动作。 2. 执行所选动作并观察下一个状态和奖励。 3. 将当前状态、所选动作、奖励、下一个状态、以及是否终止的标志存储到replay memory中。 4. 从replay memory中随机选择一批经验进行训练,更新Q-Network的参数。 5. 如果需要,更新Target-Network的参数。 6. 如果达到终止条件,则结束循环。 在训练过程中,epsilon值会逐渐减小,从而使得智能体在开始阶段更多的进行探索,然后逐渐转向利用已有知识。同时,也会定期更新Target-Network的参数,以提高算法的稳定性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值