【问题标题】:Convert weight and bias to sparse tensor pytorch将权重和偏差转换为稀疏张量 pytorch
【发布时间】:2020-10-02 22:03:13
【问题描述】:

我正在尝试将torch.nn.Parameters 转换为稀疏张量。 Pytorch 文档说Parameters 是Tensor's 子类。张量支持to_sparse 方法,但如果我将Parameters 转换为稀疏,它会给我:
TypeError: cannot assign 'torch.cuda.sparse.FloatTensor' as parameter 'weight' (torch.nn.Parameter or None expected)
有没有办法绕过这个并使用稀疏张量作为参数?强>
这是产生问题的示例代码:

for name, module in net.named_modules():
    if isinstance(module, torch.nn.Conv2d):
        module.weight = module.weight.data.to_sparse()
        module.bias = module.bias.data.to_sparse()

【问题讨论】:

  • module.weight.data = module.weight.data.to_sparse()from torch.nn.parameter import Parameter \n module.weight = Parameter(module.weight.data.to_sparse())
  • 您好,请回答,以便我标记它
  • 哈哈,没关系,解决问题就行了

标签: python neural-network pytorch conv-neural-network tensor


【解决方案1】:

torch.Tensor.to_sparse() 返回张量的稀疏副本,它不能分配给module.weight,因为这是torch.nn.Parameter 的一个实例。所以,你应该这样做:

module.weight = torch.nn.Parameter(module.weight.data.to_sparse())
module.bias = torch.nn.Parameter(module.bias.data.to_sparse())

请注意,Parameters 是一种特定类型的 Tensor,它被标记为来自 nn.Module 的参数,因此它们不同于普通的 Tensor。

【讨论】:

    猜你喜欢
    • 2018-11-12
    • 2018-06-20
    • 1970-01-01
    • 1970-01-01
    • 2020-08-05
    • 2018-07-27
    • 1970-01-01
    • 1970-01-01
    • 2021-01-05
    相关资源
    最近更新 更多