Chinaunix首页 | 论坛 | 博客
  • 博客访问: 3648294
  • 博文数量: 365
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 2522
  • 用 户 组: 普通用户
  • 注册时间: 2019-10-28 13:40
文章分类

全部博文(365)

文章存档

2023年(8)

2022年(130)

2021年(155)

2020年(50)

2019年(22)

我的朋友

分类: Python/Ruby

2022-07-19 17:02:21

import torch

import torch.nn as nn

from torch.autograd import Variable

import torch.nn.functional as F

import torch.optim as optim

import torchvision.transforms as T

from torch import FloatTensor, LongTensor, ByteTensor

from collections import namedtuple

import random

Tensor = FloatTensor

EPSILON = 0    # epsilon used for epsilon greedy approach

GAMMA = 0.9

TARGET_NETWORK_REPLACE_FREQ = 40       # How frequently target netowrk updates

MEMORY_CAPACITY = 100

BATCH_SIZE = 80

LR = 0.01         # learning rate

class DQNNet(nn.Module):

    def __init__(self):

        super(DQNNet,self).__init__()                  

        self.linear1 = nn.Linear(35,35)

        self.linear2 = nn.Linear(35,5)               

    def forward(self,s):

        s=torch.FloatTensor(s)        

        s = s.view(s.size(0),1,35)        

        s = self.linear1(s)

        s = self.linear2(s)

        return s           

class DQN(object):

    def __init__(self):

        self.net,self.target_net = DQNNet(),DQNNet()        

        self.learn_step_counter = 0      

        self.memory = []

        self.position = 0

        self.capacity = MEMORY_CAPACITY       

        self.optimizer = torch.optim.Adam(self.net.parameters(), lr=LR)

        self.loss_func = 外汇跟单gendan5.comnn.MSELoss()

    def choose_action(self,s,e):

        x=np.expand_dims(s, axis=0)

        if np.random.uniform() < 1-e:  

            actions_value = self.net.forward(x)            

            action = torch.max(actions_value,-1)[1].data.numpy()

            action = action.max()           

        else:

            action = np.random.randint(0, 5)

        return action

    def push_memory(self, s, a, r, s_):

        if len(self.memory) < self.capacity:

            self.memory.append(None)

        self.memory[self.position] = Transition(torch.unsqueeze(torch.FloatTensor(s), 0),torch.unsqueeze(torch.FloatTensor(s_), 0),\

torch.from_numpy(np.array([a])),torch.from_numpy(np.array([r],dtype='float32')))#

        self.position = (self.position + 1) % self.capacity

    def get_sample(self,batch_size):

        sample = random.sample(self.memory,batch_size)

        return sample

    def learn(self):

        if self.learn_step_counter % TARGET_NETWORK_REPLACE_FREQ == 0:

            self.target_net.load_state_dict(self.net.state_dict())

        self.learn_step_counter += 1

        transitions = self.get_sample(BATCH_SIZE)

        batch = Transition(*zip(*transitions))

        b_s = Variable(torch.cat(batch.state))

        b_s_ = Variable(torch.cat(batch.next_state))

        b_a = Variable(torch.cat(batch.action))

        b_r = Variable(torch.cat(batch.reward))    

        q_eval = self.net.forward(b_s).squeeze(1).gather(1,b_a.unsqueeze(1).to(torch.int64))

        q_next = self.target_net.forward(b_s_).detach() #

        q_target = b_r + GAMMA * q_next.squeeze(1).max(1)[0].view(BATCH_SIZE, 1).t()           

        loss = self.loss_func(q_eval, q_target.t())        

        self.optimizer.zero_grad() # reset the gradient to zero        

        loss.backward()

        self.optimizer.step() # execute back propagation for one step       

        return loss

Transition = namedtuple('Transition',('state', 'next_state','action', 'reward'))

阅读(542) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~