본문 바로가기
Error Note

[Pytorch] RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn

by ga.0_0.ga 2023. 1. 29.
728x90
반응형
반응형

- 전체 에러 문구

RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn

- 해결 방법

requires_grad 함수가 False 값을 가진 채 backward 함수를 실행하면 발생하는 오류입니다. backward()함수를 통해 역전파를 실행하기 위해 네트워크의 뒤로 갔는데 gradient를 저장해 둔 공간이 없기 때문에 에러가 발생한다고 할 수 있습니다.

import torch
import torch.nn as nn

loss = nn.CrossEntropyLoss()
input = torch.FloatTensor([[-1.4922, -0.1335,  0.2527,  0.0334,  0.0705],
        [-0.1801, -1.0769,  0.0612, -0.3233,  0.0075],
        [ 0.5383, -0.3063,  0.0163,  0.5453,  0.3191]])
target = torch.LongTensor([2, 3, 1])
output = loss(input, target)

output.requires_grad_(True) ## 추가 
output.backward()

 

두 가지 해결방법이 있습니다.

1. 위 방법처럼 output.requires_grad_(True)를 추가해줍니다.

2. tensor 선언 시 파라미터로 아래처럼 requires_grad=True로 만들어줍니다. default는 False로 설정되어 있기 때문에 바꿔주어야 에러가 나는 것을 방지할 수 있습니다.

# torch.tensor(data, *, dtype=None, device=None, requires_grad=False, pin_memory=False)

input = torch.tensor([[-1.4922, -0.1335,  0.2527,  0.0334,  0.0705],
        [-0.1801, -1.0769,  0.0612, -0.3233,  0.0075],
        [ 0.5383, -0.3063,  0.0163,  0.5453,  0.3191]],requires_grad=True)
target = torch.tensor([2., 3., 1.],requires_grad=True).long()

 

 
728x90
반응형

댓글