【发布时间】:2022-01-22 08:10:02
【问题描述】:
我有一个输出output 的神经网络。我想在损失和反向传播发生之前转换output。
这是我的通用代码:
with torch.set_grad_enabled(training):
outputs = net(x_batch[:, 0], x_batch[:, 1]) # the prediction of the NN
# My issue is here:
outputs = transform_torch(outputs)
loss = my_loss(outputs, y_batch)
if training:
scheduler.step()
loss.backward()
optimizer.step()
按照How to transform output of neural network and still train? 中的建议,我有一个转换函数,我将输出通过:
def transform_torch(predictions):
new_tensor = []
for i in range(int(len(predictions))):
arr = predictions[i]
a = arr.clone().detach()
# My transformation, which results in a positive first element, and the other elements represent decrements of the first positive element.
b = torch.negative(a)
b[0] = abs(b[0])
new_tensor.append(torch.cumsum(b, dim = 0))
# new_tensor[i].requires_grad = True
new_tensor = torch.stack(new_tensor, 0)
return new_tensor
注意:除了clone().detach(),我还尝试了Pytorch preferred way to copy a tensor中描述的方法,结果相似。
我的问题是,这个被转换的张量实际上并没有进行任何训练。
如果我尝试就地修改张量(例如直接修改arr),Torch 会抱怨我无法就地修改带有渐变的张量。
有什么建议吗?
【问题讨论】:
-
绝对不要调用
detach,这会清除渐变。b有什么意义?没用过。 -
我修复了
b变量。我目前调用detach的原因是,如果我不调用 detach,我无法在没有 Pytorch 抱怨的情况下编辑张量。
标签: python deep-learning neural-network pytorch backpropagation