![](/img/trans.png)
[英]How to convert a PyTorch sparse_coo_tensor into a PyTorch dense tensor?
[英]Convert weight and bias to sparse tensor pytorch
我正在嘗試將torch.nn.Parameters
轉換為稀疏張量。 Pytorch 文檔說參數是張量的子類。 張量支持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
的參數,因此它們與普通張量不同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.