1、如何使用强化学习玩游戏?
强化学习本身就是一种不断试错的的优化方法。重复做一件事无数次,从那些能够获得大量收益的行为当中进行学习。也就是model-free的方法,我们做出某个动作之后无法无法知道具体的环境状态STATE。因此只能不断地玩游戏采集环境状态样本或者从别人那里获取环境样本。
故玩游戏有两种思路:
- 针对每一种状态做出最佳动作;
- 精心设定一组动作,按照这组动作去操作就能够获得最完美的环境状态。
很明显,第2种才是最好的。
2、DDPG的简介
DDPG(Deep Deterministic Policy Gradient)是一种基于深度学习的确定性策略梯度强化学习方法。是一种无模型Model-Free、离线策略Off-policy、基于Actor-Critic结构、具有目标网络的强化学习算法。适用于:具有连续动作取值的智能体在简单环境当中进行生存。最终生成:根据环境状态生成对应的动作。最终目标:每一步的动作都是最优的,因此产生的环境状态也是最优,一直到游戏通关。
3、目标网络的作用?
目标网络用于生成确定性的动作和Return汇报,保证他们不参与梯度更新。
4、Actor Network
这个网络的目标就是根据当前的输入状态State生成对应的动作。
# Actor Network
class Actor(nn.Module):
def __init__(self, state_dim, action_dim, hidden_dim=64):
super(Actor, self).__init__()
self.fc1 = nn.Linear(state_dim, hidden_dim)
self.fc2 = nn.Linear(hidden_dim, hidden_dim)
self.fc3 = nn.Linear(hidden_dim, action_dim)
def forward(self, x):
# x是State特征
x = torch.relu(self.fc1(x))
x = torch.relu(self.fc2(x))
x = torch.tanh(self.fc3(x)) # Pendulum action space is [-2, 2]
return x * 2
5、 Critic Network
这个网络用于评估针对当前的状态,也就是所做出动作的好坏。之后,还需要通过这个网络间接更新Policy网络。
# Critic Network
class Critic(nn.Module):
def __init__(self, state_dim, action_dim, hidden_dim=64):
super(Critic, self).__init__()
self.fc1 = nn.Linear(state_dim + action_dim, hidden_dim)
self.fc2 = nn.Linear(hidden_dim, hidden_dim)
self.fc3 = nn.Linear(hidden_dim, 1)
def forward(self, x, a):
x = torch.cat([x, a], 1)
x = torch.relu(self.fc1(x))
x = torch.relu(self.fc2(x))
return self.fc3(x)
6、Replay Buffer经验回放池
由于DDPG是无模型的,需要不断地试错获取样本,也就是一些状态序列及对应地reward序列。这个容器类就是存放试错样本的。
# Replay Buffer
class ReplayMemory:
def __init__(self, capacity): # 构造函数
self.buffer = deque(maxlen=capacity) # deque是双向队列,可以从两端append和pop
def add_memo(self, state, action, reward, next_state, done):
state = np.expand_dims(state, 0) # np.expand_dims()是为了增加一个维度,从(3,)变成(1,3)
next_state = np.expand_dims(next_state, 0)
self.buffer.append((state, action, reward, next_state, done)) # 从右端插入
# print(self.buffer)
def sample(self, batch_size):
state, action, reward, next_state, done = zip(*random.sample(self.buffer, batch_size))
# * is to unpack the list; zip is to combine the elements of the tuple
return np.concatenate(state), action, reward, np.concatenate(next_state), done
'''
对state使用 np.concatenate()函数是因为state是一个list,里面的元素是ndarray,所以要把它们拼接起来
'''
def __len__(self): # a special method to get the length of the buffer
return len(self.buffer)