首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >避免内部操作修改参数的有效方法

问避免内部操作修改参数的有效方法
EN

Stack Overflow用户
提问于 2019-10-02 01:28:36
回答 1查看 214关注 0票数 0

我有一个model,它有噪声线性层(您可以从mu和sigma参数中采样值),并且需要为它创建两个去相关的输出。

这意味着我有这样的东西:

代码语言:javascript
复制
model.sample_noise()
output_1 = model(input)

with torch.no_grad():
     model.sample_noise()
     output_2 = model(input)

sample_noise实际上根据正态分布修改了附加在model上的权重。

但最终这会导致

RuntimeError:梯度计算所需的变量之一已被内部操作修改

问题是,避免修改这些参数的最佳方法是什么。实际上,每次迭代时,我都可以对模型进行深度复制,然后将其用于第二次前传,但这听起来并不是很有效。

EN

回答 1

Stack Overflow用户

发布于 2019-10-02 08:05:25

如果我正确理解您的问题,您希望有一个具有矩阵M的线性层,然后创建两个输出。

代码语言:javascript
复制
y_1 = (M + μ_1) * x + b
y_2 = (M + μ_2) * x + b

在哪里μ_1, μ_2 ~ P。在我看来,最简单的方法是创建一个自定义类。

代码语言:javascript
复制
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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58194154

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档