【问题标题】:How to implement a diagonal data for a linear layer in pytorch如何在pytorch中实现线性层的对角线数据
【发布时间】:2022-01-15 17:01:44
【问题描述】:

我想在 pytorch 中建立一个仅扩展数据的网络。

我的请求的数学符号是:

这意味着如果我的输入是 [1, 2] 并且我的输出是 [2, 6]。 那么线性层将如下所示:

[ [ 2, 0],
  [ 0, 3] ].

我有这个网络是用 pytorch 写的:

class ScalingNetwork(nn.Module):
    def __init__(self, input_shape, output_shape):
        super().__init__()
        self.linear_layer = nn.Linear(in_features=input_shape, out_features=output_shape)
        self.mask = torch.diag(torch.ones(input_shape))
        self.linear_layer.weight.data = self.linear_layer.weight * self.mask
        self.linear_layer.weight.requires_grad = True

    def get_tranformation_matrix(self):
        return self.linear_layer.weight


    def forward(self, X):
        X = self.linear_layer(X)
        return X

但在训练结束时,我的 self.linear 不是对角线。 我做错了什么?

【问题讨论】:

    标签: python deep-learning neural-network pytorch


    【解决方案1】:

    这里似乎有一个明显的限制条件是self.linear_layer 必须是一个方阵。您可以使用对角矩阵self.mask 将前向传播中的所有非对角元素归零:

    class ScalingNetwork(nn.Module):
        def __init__(self, in_features):
            super().__init__()
            self.linear = nn.Linear(in_features, in_features, bias=False)
            self.mask = torch.eye(in_features, dtype=bool)
    
        def forward(self, x):
            self.linear.weight.data *= self.mask
            print(self.linear.weight)
            x = self.linear(x)
            return x
    

    例如:

    >>> m = ScalingNetwork(5)
    
    >>> m(torch.rand(1,5))
    Parameter containing:
    tensor([[-0.2987, -0.0000, -0.0000, -0.0000, -0.0000],
            [ 0.0000, -0.1042, -0.0000, -0.0000, -0.0000],
            [-0.0000,  0.0000, -0.4267,  0.0000, -0.0000],
            [ 0.0000, -0.0000, -0.0000,  0.1758,  0.0000],
            [ 0.0000,  0.0000,  0.0000, -0.0000, -0.3208]], requires_grad=True)
    tensor([[-0.1032, -0.0087, -0.1709,  0.0035, -0.1496]], grad_fn=<MmBackward0>)
    

    【讨论】:

      猜你喜欢
      • 2022-01-13
      • 1970-01-01
      • 2019-05-16
      • 2019-09-25
      • 2019-10-09
      • 1970-01-01
      • 2020-03-28
      • 2021-04-19
      • 1970-01-01
      相关资源
      最近更新 更多