我有一个和这个类似的问题:
有一个(n1, n2)形式的输入向量,我想要一个f(n1, n2) = f(n2, n1)的模型。我希望这个模型是线性的。例如,我想学习的2x2矩阵。2x2矩阵有4个权重,训练将尝试学习这些权重。但是,这种限制可以巧妙地减少问题。作为nvec=(n1, n2),f(nvec) = W*nvec。因此,假设X = [[0, 1],[1, 0]]是一个反转向量的2x2矩阵,然后是f(n2,n1) = W*X*(n1, n2) = f(n1, n2) = W (n1, n2)。
基本上,等式意味着W*X = W,或者如果是W = [[w1, w2], [w3, w4]],那么等式意味着W = [[w1, w1], [w3, w3]],即矩阵只有2个自由参数。我如何在pytorch中定义这样的模型呢?
谢谢。
发布于 2020-01-29 14:21:18
如果您的参数具有特殊的结构,并且您不想使用由缺省层存储的缺省参数,则可以自行定义一个层并使用nn.Parameter存储参数。
例如,
class CustomLayer(nn.Module): # layer must be derived from nn.Module class
def __init__(self): # you can have arguments here...
super(CustomLayer, self).__init__()
self.params = nn.Parameter(data=torch.rand((2, 1), dtype=torch.float), requires_grad=True)
def forward(self, x):
w = self.params.repeat(1, 2) # create a 2x2 matrix from the two parameters
y = torch.bmm(x, w)
return yhttps://stackoverflow.com/questions/59960545
复制相似问题