Pytorch 'TypeError: can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.' & AttributeError: 'list' object has no attribute 'cpu'

2022. 9. 27. 14:10Pytorch

파이토치 쓰던 와중

 

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

 

라는 에러를 만나 x.numpy() 를 x.cpu().numpy()로 수정해준다.

(이는 GPU에 할당되어 있는 tensor를 바로 배열로 바꾸지말고 cpu로 내린다음, cpu에서 변환 작업을 하라는 에러문구이다.)

 

그러면 또 

 

AttributeError: 'list' object has no attribute 'cpu'

 

라는 에러가 발생한다. 

 

아니  cpu로 내리래서 내렸더니 얘는 .cpu() 가 안된다고? 화가 가득난다

그래서 x의 type을 찍어본 결과 list 안에 원소가 tensor인 격이다. 

 

따라서

x = torch.stack(x)

x = x.cpu().numpy()

위 코드를 실행시켜준다.

 

이는 리스트를 1차원으로 풀어주면 리스트 괄호가 벗겨져 텐서가 되고, 이는 cpu() attribute를 가지고 있기 때문에 실행시킬 수 있다.

 

끝!