簡體   English   中英

將權重和偏差轉換為稀疏張量 pytorch

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM