【问题标题】:element 0 of tensors does not require grad and does not have a grad_fn张量的元素 0 不需要 grad 并且没有 grad_fn
【发布时间】:2019-07-17 21:20:49
【问题描述】:

我正在尝试将强化学习机制应用于分类任务。 我知道这样做是没有用的,因为深度学习在任务中的表现可能超过 rl。无论如何,我正在做的研究目的。

我奖励代理,如果他是正确的正面 1 或不是负面的 -1 并用predicted_action(predicted_class) 和奖励计算损失函数。

但我得到一个错误:

张量的元素 0 不需要 grad 也没有 grad_fn

 # creating model
class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()

        self.pipe = nn.Sequential(nn.Linear(9, 120),
                                 nn.ReLU(),
                                 nn.Linear(120, 64),
                                 nn.ReLU(),
                                 nn.Linear(64,2),
                                 nn.Softmax()
                                 )

    def forward(self, x):
        return self.pipe(x)


def env_step(action, label, size):
    total_reward = []

    for i in range(size):
        reward = 0

        if action[i] == label[i]:
            total_reward.append(reward+1)
            continue
        else:
            total_reward.append(reward-1)
            continue

    return total_reward




if __name__=='__main__':
    epoch_size = 100
    net = Net()
    criterion = nn.MSELoss()
    optimizer = optim.Adam(params=net.parameters(), lr=0.01)

    total_loss = deque(maxlen = 50)

    for epoch in range(epoch_size):
        batch_index = 0
        for i in range(13):
            # batch sample
            batch_xs = torch.FloatTensor(train_state[batch_index: batch_index+50])   # make tensor
            batch_ys = torch.from_numpy(train_label[batch_index: batch_index+50]).type('torch.LongTensor')  # make tensor

            # action_prob; e.g classification prob
            actions_prob = net(batch_xs)                                
            #print(actions_prob)
            action = torch.argmax(actions_prob, dim=1).unsqueeze(1)    
            #print(action)
            reward = np.array(env_step(action, batch_ys, 50))  
            #print(reward)

            reward = torch.from_numpy(reward).unsqueeze(1).type('torch.FloatTensor')
            #print(reward)
            action = action.type('torch.FloatTensor')

            optimizer.zero_grad()
            loss = criterion(action, reward)    
            loss.backward()
            optimizer.step()


            batch_index += 50

【问题讨论】:

    标签: python pytorch classification reinforcement-learning


    【解决方案1】:

    action 由 argmax 函数产生,不可微分。相反,您希望承担奖励和所采取行动的负责任概率之间的损失。

    通常,在强化学习中为策略选择的“损失”是所谓的score function:

    这是采取行动a 的责任概率与获得的奖励的对数的乘积。

    【讨论】:

    • 谢谢克里斯,我会努力的!我怀疑可区分的东西......
    猜你喜欢
    • 2020-03-26
    • 2020-08-31
    • 2020-10-23
    • 2021-07-23
    • 2019-04-07
    • 2021-10-26
    • 2022-01-11
    • 2021-07-01
    • 2021-11-11
    相关资源
    最近更新 更多