1 Star 5 Fork 1

Desny/traffic_light_rl_basic

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
replay.py 1.57 KB
一键复制 编辑 原始数据 按行查看 历史
xuyanjiao 提交于 2023-03-09 10:07 . initial basic version of sumo-rl
from collections import namedtuple
import numpy as np
import torch
Transition = namedtuple('Transition',
('state', 'action', 'next_state', 'reward'))
device = "cuda" if torch.cuda.is_available() else "cpu"
class ReplayBuffer:
def __init__(
self,
capacity: int,
):
self._capacity = capacity
self._num_added = 0
self._storage = [None] * capacity
def add(self, state, next_state, reward, action) -> None:
if reward is not None:
state = torch.from_numpy(state).unsqueeze(0).to(device)
next_state = torch.from_numpy(next_state).unsqueeze(0).to(device)
action = torch.tensor(action).unsqueeze(0).to(device)
reward = torch.tensor(reward, dtype=torch.float32).unsqueeze(0).to(device)
self._storage[self._num_added % self._capacity] = Transition(state,
action,
next_state,
reward)
self._num_added += 1
def sample(self, batch_size: int = 1):
indices = np.random.randint(0, self.size, batch_size)
samples = [self._storage[i] for i in indices]
return samples
@property
def capacity(self) -> int:
return self._capacity
@property
def size(self) -> int:
return min(self._num_added, self._capacity)
@property
def steps_done(self) -> int:
return self._num_added
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/desny/traffic_light_rl_basic.git
git@gitee.com:desny/traffic_light_rl_basic.git
desny
traffic_light_rl_basic
traffic_light_rl_basic
master

搜索帮助