Error

[Pytorch] RuntimeError: Can't call numpy() on Variable that requires grad. Use var.detach().numpy() instead.

HUR129 2022. 2. 26. 23:22
RuntimeError: Can't call numpy() on Variable that requires grad. Use var.detach().numpy() instead.

문제상황 : test때 gpu의 모델 추론값을 .cpu().numpy()을 통해 바꾸어 주려니 생기는 문제.

 

이유 : 위와 같은 상태로는 trainable tensor기 때문에 tensor를 non-trainable 상태로 바꾸어 놓고 numpy로 보내야한다.

 

해결방법 :

vid_emb=vid_emb.cpu().detach().numpy()

설명 : vid_emb 가 모델을 통해 infer된 tensor입니다. numpy 연산을 위해 gpu > cpu로 보낸 후 .detach()를 통해 학습하지않는 텐서 형태로 바꾸어 줍니다. 이후 numpy 연산을 위해 .numpy()를 적용하면 test단계에서 눈으로 값이 보이는 matrix 연산이 가능합니다 (제 모델의 경우).