【问题标题】:PyTorch: How to write a neural network that only returns the weights?PyTorch:如何编写只返回权重的神经网络?
【发布时间】:2019-09-19 03:15:19
【问题描述】:

我正在训练一个学习一些权重的神经网络,并根据这些权重计算转换,从而产生与权重相结合的预测模型。我的网络没有正确学习,因此我正在编写一个不同的网络,它只返回独立于输入x 的权重(在使用 softmax 和转置进行标准化之后)。这样,我想找出问题出在网络上还是出在网络外的变换估计上。但这不起作用。这就是我所拥有的。

class DoNothingNet(torch.nn.Module):
    def __init__(self, n_vertices=6890, n_joints=14):
        super(DoNothingNet, self).__init__()
        self.weights = nn.parameter.Parameter(torch.randn(n_vertices, n_joints))

    def forward(self, x, indices):
        self.weights = F.softmax(self.weights, dim=1)
        return self.weights.transpose(0,1)

但是self.weights = F.softmax(self.weights, dim=1) 行不起作用并产生错误TypeError: cannot assign 'torch.cuda.FloatTensor' as parameter 'weights' (torch.nn.Parameter or None expected)。我该如何解决?代码是否有意义?

【问题讨论】:

    标签: python neural-network pytorch


    【解决方案1】:

    nn.Module 跟踪所有 nn.Parameter 类型的字段以进行训练。在您的代码中,每次前向调用都尝试通过将参数权重分配给 Tensor 类型来更改参数权重,因此会发生错误。

    以下代码在不更改存储权重的情况下输出归一化权重。希望这会有所帮助。

    import torch
    from torch import nn
    from torch.nn import functional as F
    
    class DoNothingNet(torch.nn.Module):
        def __init__(self, n_vertices=6890, n_joints=14):
            super(DoNothingNet, self).__init__()
            self.weights = nn.parameter.Parameter(torch.randn(n_vertices, n_joints))
    
        def forward(self, x, indices):
            output = F.softmax(self.weights, dim=1)
            return output.transpose(0,1)
    
    

    【讨论】:

      猜你喜欢
      • 2018-12-16
      • 2021-06-25
      • 2023-02-14
      • 2019-05-05
      • 1970-01-01
      • 1970-01-01
      • 2020-03-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多