pytorch Variable 및 Tensor 병합 후 requires_grad () 기본 및 수정 방법

Pytorch 업데이트 후 Variable 및 Tensor 통합
torch.Tensor () 는 Variable처럼 Tensor 값을 반환하는 역방향 전파 업데이트를 수행할 수 있습니다.
Variable은 자동으로 tensor를 생성하고 값이 Tensor로 되돌아옵니다. (따라서 앞으로는 Variable을 사용할 필요가 없습니다.)
Tensor 생성 후 기본 requires_grad=Flase
xxx를 통해 가능합니다.requires_grad_() 기본 Flase를 True로 수정

다음 코드와 공식 문서 코드는 다음과 같습니다.


import torch
from torch.autograd import Variable # Variabl 
lis=torch.range(1,6).reshape((-1,3))# 1~6   
# (-1 ) 3 floattensor 

print(lis)
print(lis.requires_grad) # requires_grad Flase

lis.requires_grad_() # .requires_grad_() requires_grad true
print(lis.requires_grad)
결과는 다음과 같습니다.
tensor([[1., 2., 3.],
[4., 5., 6.]])
False
True
Variable을 만듭니다. Variable은 Tensor 데이터를 받아야 합니다. a=Variable(range(6)이라고 직접 쓸 수 없습니다.reshape((-1,3))
그렇지 않으면 Variable data has to be a tensor, but got range

정확히 다음과 같습니다.


import torch
from torch.autograd import Variable
tensor=torch.FloatTensor(range(8)).reshape((-1,4))
my_ten=Variable(tensor)
print(my_ten)
print(my_ten.requires_grad)

my_ten.requires_grad_()
print(my_ten.requires_grad)
결과:
tensor([[0., 1., 2., 3.],
[4., 5., 6., 7.]])
False
True
위에서 알 수 있듯이 Tensor는 Variable을 완전히 대체할 수 있다.

다음은 공식 문서입니다.


#  requires_grad = False Tensor  
x = torch . ones ( 1 ) # create a tensor with requires_grad=False (default)
x . requires_grad
# out: False

#  Tensor, requires_grad = False
y = torch . ones ( 1 ) # another tensor with requires_grad=False
# both inputs have requires_grad=False. so does the output
z = x + y
#  Tensor x,y,requires_grad=False. ,
#  (operation)z=x+y z ,requires_grad=False
z . requires_grad
# out: False

# then autograd won't track this computation. let's verify!
#  autograd, 
z . backward ( ) 
# out: :RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn

# now create a tensor with requires_grad=True
w = torch . ones ( 1 , requires_grad = True ) 
w . requires_grad
# out: True

# add to the previous result that has require_grad=False
#  total Tensor w requires_grad=True, 。
total = w + z
# the total sum now requires grad!
total . requires_grad
# out: True
# autograd can compute the gradients as well
total . backward ( ) 
w . grad
#out: tensor([ 1.])

# and no computation is wasted to compute gradients for x, y and z, which don't require grad
#  z,x,y requires_grad=False, 
z . grad == x . grad == y . grad == None 
# True
existing_tensor . requires_grad_ ( ) 
existing_tensor . requires_grad
# out:True
아니면 직접 Tensor로 만들 때 주어진 requires_grad=True

my_tensor = torch.zeros(3,4,requires_grad = True) 
my_tensor.requires_grad
# out: True

lis=torch.range(1,6,requires_grad=True).reshape((-1,3))
print(lis)
print(lis.requires_grad)
lis.requires_grad_()
print(lis.requires_grad)
결과
tensor([[1., 2., 3.],
[4., 5., 6.]], requires_grad=True)
True
True
보충:volatile 및 requires_grad

Backward 프로세스 중 하위 그림 제외


pytorch의 BP 프로세스는 하나의 함수에 의해 결정됩니다.loss.backward (), backward () 함수에 누구를 요구하는 사다리가 없는 것을 볼 수 있습니다.그러면 우리는 BP의 과정에서pytorch는loss에 영향을 미치는 모든 Variable을 한 차례의 사다리를 구했다고 대담하게 추측할 수 있다.
그러나 때때로 우리는 모든 Variable의 사다리를 구하고 싶지 않다.그러면 백워드 과정에서 서브맵을 배제하는 방법을 고려해야 한다.
BP 프로세스에서 하위 그림은 어떻게 제외됩니까?Variable 매개변수 2개(requires_grad 및volatile)
requires_grad=True 요구 단계
requires_grad=False는 사다리를 요구하지 않습니다
volatile=True 상당requires_grad=False.반대로, 반대로...ok
주의: 만약 a가 requires_grad=True, b는 requires_grad=False.c=a+b는requires_grad=True.같은 이치가volatile에 응용되다

하위 그림을 제거하는 이유


사다리를 모두 계산하고 갱신하지 않으면 되지 않느냐고 물어볼 수도 있다.
이렇게 하면 효율 문제와 관련된다. 많은 쓸모없는 사다리를 계산하는 것은 많은 자원을 낭비하는 것이다(시간, 컴퓨터 메모리)
이상의 개인적인 경험으로 여러분께 참고가 되었으면 좋겠습니다. 또한 많은 응원 부탁드립니다.만약 잘못이 있거나 완전한 부분을 고려하지 않으신다면 아낌없이 가르침을 주시기 바랍니다.

좋은 웹페이지 즐겨찾기