본문 바로가기

다시 보기 싫은 에러 정리

TypeError: can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.

TypeError: can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.
구현 중에, 위와 같은 에러가 발생하였다.

재현

import torch

a = torch.tensor(1)
a = a.cuda()
a.numpy()

TypeError: can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.

이 에러는 GPU에 올린 Tensor를 바로 numpy로 변환하였을 때 발생한다.
따라서, 다음과 같은 방법으로 해결된다.

import torch

a = torch.tensor(1)
a = a.cuda()
a.cpu().numpy()

cpu method를 사용해 cpu ram에 로드하고, numpy method를 사용해주었다.