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

2023. 1. 29. 21:02·Error Note
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
반응형
저작자표시 (새창열림)

'Error Note' 카테고리의 다른 글

[Pytorch] RuntimeError: CUDA error: device-side assert triggered  (0) 2023.01.29
[Tensorflow] Invalid argument: Subshape must have computed start >= end since stride is negative,,,  (0) 2023.01.29
TypeError: Encoders require their input to be uniformly strings or numbers. Got ['int', 'str']  (0) 2023.01.29
[Pytorch] RuntimeError: Expected object of scalar type Long but got scalar type Float for argument #  (0) 2023.01.29
[Pytorch] RuntimeError: DataLoader worker (pid(s) 19106, 19107, 19109, 19110) exited unexpectedly.  (0) 2023.01.28
'Error Note' 카테고리의 다른 글
  • [Pytorch] RuntimeError: CUDA error: device-side assert triggered
  • [Tensorflow] Invalid argument: Subshape must have computed start >= end since stride is negative,,,
  • TypeError: Encoders require their input to be uniformly strings or numbers. Got ['int', 'str']
  • [Pytorch] RuntimeError: Expected object of scalar type Long but got scalar type Float for argument #
ga.0_0.ga
ga.0_0.ga
    반응형
    250x250
  • ga.0_0.ga
    ##뚝딱뚝딱 딥러닝##
    ga.0_0.ga
  • 전체
    오늘
    어제
    • 분류 전체보기 (181)
      • Paper Review (51)
        • Video Scene Graph Generation (6)
        • Image Scene Graph Generation (18)
        • Graph Model (5)
        • Key Information Extraction (4)
        • Fake Detection (2)
        • Text to Image (1)
        • Diffusion Personalization (4)
        • etc (11)
      • AI Research (49)
        • Deep Learning (30)
        • Artificial Intelligence (15)
        • Data Analysis (4)
      • Pytorch (10)
      • ONNX (5)
      • OpenCV (2)
      • Error Note (34)
      • Linux (2)
      • Docker (3)
      • Etc (7)
      • My Study (16)
        • Algorithm (10)
        • Project (4)
        • Interview (2)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    그래프신경망
    알고리즘
    tensorflow
    정규화
    나이브 베이즈 분류
    활성화 함수
    JNI
    Logistic regression
    Activation Function
    i3d
    TypeError
    contiguous
    permute
    오차 역전파
    pytorch
    torch.nn
    transformer
    dataset
    Inductive bias
    3dinput
    차원의 저주
    linear regression
    fine tuning
    dataloader
    GCN
    HRNet
    pandas
    RuntimeError
    forch.nn.functional
    ONNX
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.0
ga.0_0.ga
[Pytorch] RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn
상단으로

티스토리툴바