In [4]:
import torch
import torchvision
import torch.nn as nn
import numpy as np
import torch.utils.data as data
import torchvision.transforms as transforms
import torchvision.datasets as dsets
from torch.autograd import Variable
In [7]:
# Tensorを作成
# Variableで囲んでrequires_grad=Trueにすると自動微分で勾配を求められる
x = Variable(torch.Tensor([1]), requires_grad=True)
w = Variable(torch.Tensor([2]), requires_grad=True)
b = Variable(torch.Tensor([3]), requires_grad=True)
# 計算グラフ
y = w * x + b
In [11]:
y
Out[11]:
In [12]:
y.backward()
In [13]:
print(x.grad) # dy/dx = w = 2
In [14]:
print(w.grad) # dy/dw = x = 1
In [15]:
print(b.grad) # dy/db = 1
In [ ]: