如何使用 PyTorch 将自定义类型作为观察值传递给 DQN 代理?

问题描述 投票:0回答:1

我想将自定义状态(观察)传递给我的代理,其中包括一组自定义类型对象(属于我定义的名为 Task 的类)、电池电量(整数)、资源(整数)和信道增益(整数) ), 当我通过所描述的状态时,它在下面的行中给出了这个错误“必须是实数,而不是任务”

state = T.tensor([observation],dtype=T.float32).to(self.q_eval.device)

我该如何解决?

def select_action(self, observation,episode):
        #update epsilon 
        epsilon  = self.INITIAL_EPSILON - episode * (self.INITIAL_EPSILON - self.FINAL_EPSILON) / self.max_episode
        M = observation.shape[0]   #the number of observations's features 
        state = T.tensor([observation],dtype=T.float32).to(self.q_eval.device)
        actions = self.q_eval.forward(state)
        a_hat=T.argmax(T.squeeze(actions),dim=1).detach().numpy()
        random_index = np.array(np.random.uniform(size = (M)) < epsilon, dtype = np.int32)
        random_action = np.random.randint(0, high = self.n_actions , size = (M))
        action_set = np.vstack([a_hat, random_action])
        action = action_set[random_index, range(M)] #[M]
        return  action
python pytorch reinforcement-learning dqn
1个回答
0
投票

首先,

state = T.tensor([observation],dtype=T.float32).to(self.q_eval.device)
在这里,您指定希望张量中的每个元素都具有
float32
的数据类型。由于您声明
observation
包含自定义类,因此不能将其转换为浮点数。

https://pytorch.org/docs/stable/tensors.html 此链接向您展示了构造火炬张量时允许的数据类型。通常只允许实数,因为在计算反向传播的梯度时有必要。

您可以将自定义类中的属性编码为实数。例如:

class Task:
    def __init__(self, attr1: float, attr2: int):
        self.attr1 = attr1
        self.attr2 = attr2
    
    def encodeToTensor(self):
        return torch.tensor([self.attr1, self.attr2], dtype=torch.float32)

然后你可以将这个张量与其余实数连接起来形成一个输入张量,前提是你实际上可以以某种方式将必要的属性编码为实数。

© www.soinside.com 2019 - 2024. All rights reserved.