我正在尝试将torch.nn.Parameters
转换为稀疏张量。 Pytorch文档说Parameters是Tensor's子类。 Tensor支持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()
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
是张量的特定类型,被标记为nn.Module
的参数,因此与普通张量不同。