DQN算法打印历代奖励值代码
时间: 2023-12-20 08:03:21 浏览: 92
好的,以下是使用DQN算法打印历代奖励值的代码示例:
```python
import gym
import numpy as np
import tensorflow as tf
from collections import deque
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_min = 0.01
self.epsilon_decay = 0.995
self.learning_rate = 0.001
self.model = self._build_model()
def _build_model(self):
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Dense(24, input_dim=self.state_size, activation='relu'))
model.add(tf.keras.layers.Dense(24, activation='relu'))
model.add(tf.keras.layers.Dense(self.action_size, activation='linear'))
model.compile(loss='mse', optimizer=tf.keras.optimizers.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 np.random.choice(self.action_size)
act_values = self.model.predict(state)
return np.argmax(act_values[0])
def replay(self, batch_size):
minibatch = np.array(random.sample(self.memory, batch_size))
states = np.concatenate(minibatch[:,0], axis=0)
actions = np.concatenate(minibatch[:,1], axis=0)
rewards = minibatch[:,2]
next_states = np.concatenate(minibatch[:,3], axis=0)
dones = minibatch[:,4]
targets = self.model.predict(states)
next_state_targets = self.model.predict(next_states)
for i in range(batch_size):
if dones[i]:
targets[i][actions[i]] = rewards[i]
else:
targets[i][actions[i]] = rewards[i] + self.gamma * np.amax(next_state_targets[i])
self.model.fit(states, targets, epochs=1, verbose=0)
if self.epsilon > self.epsilon_min:
self.epsilon *= self.epsilon_decay
def load(self, name):
self.model.load_weights(name)
def save(self, name):
self.model.save_weights(name)
if __name__ == "__main__":
env = gym.make('CartPole-v1')
state_size = env.observation_space.shape[0]
action_size = env.action_space.n
agent = DQNAgent(state_size, action_size)
done = False
batch_size = 32
num_episodes = 1000
rewards = []
for e in range(num_episodes):
state = env.reset()
state = np.reshape(state, [1, state_size])
total_reward = 0
for time in range(500):
action = agent.act(state)
next_state, reward, done, _ = env.step(action)
reward = reward if not done else -10
next_state = np.reshape(next_state, [1, state_size])
agent.remember(state, action, reward, next_state, done)
state = next_state
total_reward += reward
if done:
print("episode: {}/{}, score: {}".format(e+1, num_episodes, time))
rewards.append(total_reward)
break
if len(agent.memory) > batch_size:
agent.replay(batch_size)
if (e+1) % 10 == 0:
agent.save("cartpole-dqn.h5")
env.close()
print("Average reward for last 100 episodes: ", np.mean(rewards[-100:]))
```
在上面的代码中,我们定义了一个`DQNAgent`类来实现DQN算法。`remember`方法用于存储经验回放,`act`方法用于选择动作,`replay`方法用于训练模型。在主程序中,我们使用`for`循环来运行多个episode,并在每个episode结束时打印分数。最后,我们通过计算最后100个episode的平均奖励来评估算法的性能。
阅读全文