我有一个model,它有噪声线性层(您可以从mu和sigma参数中采样值),并且需要为它创建两个去相关的输出。
这意味着我有这样的东西:
model.sample_noise()
output_1 = model(input)
with torch.no_grad():
model.sample_noise()
output_2 = model(input)sample_noise实际上根据正态分布修改了附加在model上的权重。
但最终这会导致
RuntimeError:梯度计算所需的变量之一已被内部操作修改
问题是,避免修改这些参数的最佳方法是什么。实际上,每次迭代时,我都可以对模型进行深度复制,然后将其用于第二次前传,但这听起来并不是很有效。
发布于 2019-10-02 08:05:25
如果我正确理解您的问题,您希望有一个具有矩阵M的线性层,然后创建两个输出。
y_1 = (M + μ_1) * x + b
y_2 = (M + μ_2) * x + b在哪里μ_1, μ_2 ~ P。在我看来,最简单的方法是创建一个自定义类。
import torch
import torch.nn.functional as F
from torch import nn
class NoisyLinear(nn.Module):
def __init__(self, n_in, n_out):
super(NoisyLinear, self).__init__()
# or any other initialization you want
self.weight = nn.Parameter(torch.randn(n_out, n_in))
self.bias = nn.Parameter(torch.randn(n_out))
def sample_noise(self):
# implement your noise generation here
return torch.randn(*self.weight.shape) * 0.01
def forward(self, x):
noise = self.sample_noise()
return F.linear(x, self.weight + noise, self.bias)
nl = NoisyLinear(4, 3)
x = torch.randn(2, 4)
y1 = nl(x)
y2 = nl(x)
print(y1, y2)https://stackoverflow.com/questions/58194154
复制相似问题