2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

PytorchのConv2Dのweightプロパティを変更しようとしたらエラーが出た話

Posted at

環境

Windows10
Python 3.7.7
torch 1.8.0

状況

torchで畳み込みをするとき重みを直接設定しようとするとRuntimeError: a view of a leaf Variable that requires grad is being used in an in-place operation.というエラーが出る

##エラーが出たコード

import torch
import torch.nn as nn

m = nn.Conv2d(1, 1, 2, stride=1, bias=False)
m.weight[0, 0, 0, 0] = 1
m.weight[0, 0, 0, 1] = 2
m.weight[0, 0, 1, 0] = 3
m.weight[0, 0, 1, 1] = 4

##修正後のコード

import torch
import torch.nn as nn

m = nn.Conv2d(1, 1, 2, stride=1, bias=False)
m.weight.data[0, 0, 0, 0] = 1
m.weight.data[0, 0, 0, 1] = 2
m.weight.data[0, 0, 1, 0] = 3
m.weight.data[0, 0, 1, 1] = 4

weightのdataプロパティにアクセスするようにしてあげれば、エラーがでなくなった。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?