自动梯度
- 前向传播(Forward Propagation) 是从input,经过一层层的layer,不断计算每一层的z和a, 得到输出y^ 的过程,计算出了y^,就可以根据它和真实值y的差别来计算损失(loss)。
- 反向传播(Backward Propagation) 是根据损失函数L(y^,y)来反方向地计算每一层的z、a、w、b的偏导数(梯度),从而更新参数。
import torch
from torch.autograd import Variable
class Model(object):
def __init__(self):
super(Model, self).__init__()
def forward(self, x):
return x * w
def loss(self, x, y):
y_pred = self.forward(x)
return pow((y_pred - y), 2)
def run(self):
print('predict (before training)', 4, self.forward(4).item())
for epoch in range(10):
for x_val, y_val in zip(x_data, y_data):
l = self.loss(x_val, y_val)
l.backward()
print('\tgrad:', x_val, y_val, w.grad.item())
w.data = w.data - 0.01 * w.grad.data
w.grad.data.zero_()
print('process:', epoch, l.data[0])
print('predict (after training)', 4, self.forward(4).item())
if __name__ == "__main__":
print("Life is short, You need Python!")
x_data = [1.0, 2.0, 3.0]
y_data = [2.0, 4.0, 6.0]
w = Variable(torch.Tensor([1.0]), requires_grad=True)
m = Model()
m.run()