아이공의 AI 공부 도전기

[Pytorch] RuntimeError: view size is not compatible with input tensor's size and stride (at least one dimension spans across two contiguous subspaces). Use .reshape(...) instead.

 

     

 

문제 의식

 

narrow(), expand(), view(), transpose()를 통해 tensor의 모양을 변화시킬 경우 새로운 텐서를 생성하는 것이 아니라 저장된 tensor memory 주소는 그대로 둔채 모양만 바꾼다.

 

이런 경우 tensor의 메모리를 강제로 연속적으로 만들어줄 필요가 있다. 이를 위한 해결 법은 크게 2가지이다.

 

 

해결법 1. torch.Tensor.contiguous 사용하기

 

본 방법과 관련한 설명은 아래 링크에 정리해두었다. 참조하길 바란다.

 

만약 바라보지 않고 해결법을 원한다면 다음과 같은 코드를 기입하길 바란다.

 

# tensor.view(~) 대신 아래 코드 사용
tensor.contiguous().view(~)

 

https://aigong.tistory.com/430

 

[Pytorch] torch.Tensor.contiguous 이유와 사용법

[Pytorch] torch.Tensor.contiguous 이유와 사용법 목차 torch.Tensor.contiguous란 https://pytorch.org/docs/stable/generated/torch.Tensor.contiguous.html torch.Tensor.contiguous — PyTorch 1.11.0 doc..

aigong.tistory.com

 

해결법 2. torch.Tensor.reshape 사용하기

 

# tensor.view(~) 대신 아래 코드 사용
tensor.reshape(~)

 

공유하기

facebook twitter kakaoTalk kakaostory naver band
loading