10
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.

ValueError: only one element tensors can be converted to Python scalars の対処法

Posted at

はじめに

pytorchをいじっていると稀によくわからないエラーに出くわします.今回は私が遭遇したValueError: only one element tensors can be converted to Python scalars の対処法を紹介します.

原因

torch.Tensorをlistにしてそれをまるごとtorch.tensor()やtorch.as_tensor()につっこむとタイトルにある通りのエラーが吐き出されます.ただし,Tensorのサイズが1より大きいときにしか発生しないです (多分).TensorのlistをまとめてTensorに変換したい場合はtorch.stackを使いましょう.以下,コード例です.

コード例

a = torch.ones([1])
b = torch.tensor([a])
c = torch.as_tensor([a]) # ここまでは大丈夫

a = torch.ones([2, 2])
b = torch.tensor([a]) # 死ぬ
c = torch.tensor([b]) # 死ぬ
d = torch.stack([a], dim=0) # size = (1, 2, 2) のテンソルができる.defaultではdim=0

おわりに

二次元リストの場合はこの方法は使えないです.

10
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
10
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?