PyTorchを使って、深層学習をしています。
forward計算内でnumpyのnp.tileやnp.reshapeなどを使っているのですが、Tensor型をnumpyのndarray型に変換してしまうと、requires_gradの情報が失われ、学習ができません。
Tensor型のままtileのような処理を実行する方法はありますでしょうか。
もしくは、requires_gradの情報を保持したまま、numpyで計算を行うことはできないのでしょうか?
スタック・オーバーフローはプログラマーとプログラミングに熱心な人のためのQ&Aサイトです。すぐ登録できます。
登録してこのコミュニティに参加するこのような感じでいかがでしょうか。
#!/usr/bin/env python
import torch
# tile
x = torch.tensor([[1, 2], [3, 4]], dtype=torch.float32)
x.requires_grad_()
print(x)
x = x.repeat(2, 3)
print(x)
# reshape
x = torch.tensor([[1, 2], [3, 4], [5, 6]], dtype=torch.float32)
x.requires_grad_()
print(x)
x = x.view(2, -1)
print(x)
出力結果は以下の通りです。
luna:~ % ./testu1.py
tensor([[1., 2.],
[3., 4.]], requires_grad=True)
tensor([[1., 2., 1., 2., 1., 2.],
[3., 4., 3., 4., 3., 4.],
[1., 2., 1., 2., 1., 2.],
[3., 4., 3., 4., 3., 4.]], grad_fn=<RepeatBackward>)
tensor([[1., 2.],
[3., 4.],
[5., 6.]], requires_grad=True)
tensor([[1., 2., 3.],
[4., 5., 6.]], grad_fn=<ViewBackward>)