RL-DQN Coding Problem

  • 经验回放类采样一个batch,zip(*)用于将元组解压拆分:
group = random.sample(self.buffer,batchsize)  
s,a,r,n_s,done = zip(*group)
  • DQN的epsilon采用e-greedy方式进行,需要设置epsilon的衰减可以参考
self.frameIdx = 0
self.epsilon_decay = 500
self.epsilon_start = 0.95
self.epsilon_end = 0.01
self.epsilon = lambda frameIdx: self.epsilon_end + math.exp(-1 * self.frameIdx / self.epsilon_decay) * (self.epsilon_start - self.epsilon_end)
  • 判断是否可用GPU
self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
  • 同步targetNet和policyNet
self.target_net.load_state_dict(self.policy_net.state_dict())
  • tensor取max操作的含义:返回一个元组,元组第一个成员表示最大值,第二个成员表示最大值的索引。max中参数是对返回哪个维度上的最大值(通常tensor有两个维度,第一个维度是batchSize,在第二个维度上计算最大值)。b.argmax(dim=1)与b.max(dim=1)[1]效果相同。
import torch
import numpy as np
a = np.array([[1,2,3,4],[5,6,7,8]])
b = torch.tensor(a,dtype = torch.int32)
print(b)
c = b.max(dim=1)
print(c)
# c = b.argmax(dim=1)
# d = b.max(dim=1)[1]
# output:
tensor([[1, 2, 3, 4],
        [5, 6, 7, 8]], dtype=torch.int32)
torch.return_types.max(
values=tensor([4, 8], dtype=torch.int32),
indices=tensor([3, 3]))
  • random.randrange(),Python中的随机数模块:random.randrange([start],stop,step)
# 两种写法等效
a = random.randrange(self.action_dim)
a = random.randrange(0,self.action_dim,1)
  • unsqueeze与squeeze,指定维度升维或者降维,相当于求.shape时在某处增加一个1或者减少1:
import torch
import numpy as np
a = np.array([[1,2,3,4],[5,6,7,8]])
b = torch.tensor(a)
print(b.shape)
c = b.unsqueeze(1)
print(c.shape)
d = c.squeeze(1)
print(d.shape)
# output:
torch.Size([2, 4])
torch.Size([2, 1, 4])
torch.Size([2, 4])
  • b.gather(dim=1,a),表示按照某个维度,以a为索引获取b中的元素并返回新的tensor,需要维度相同,指定索引维度,并且索引类型必须为torch.int64
import torch
b = torch.tensor([[1,2,3,4],[5,6,7,8]])
print(b)
a = torch.as_tensor(np.array([[0],[1]]),dtype = torch.int64)
print(a)
c = b.gather(1,a)
# c = torch.gather(b,1,a)
print(c)
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容