@file name : lesson-04-Computational-Graph.py
@author : tingsongyu
@date : 2018-08-28
@brief : 计算图示例
# lesson-04-computational-graph.py
import torch as tt
w = tt.tensor([1.], requires_grad = True)
x = tt.tensor([2.], requires_grad = True)
a = tt.add(w,x)
b = tt.add(w,1)
y = tt.mul(a,b)
y.backward()
print(w.grad)
tensor([5.])
# 查看叶子结点
print("is_leaf:\n", w.is_leaf, x.is_leaf, a.is_leaf, b.is_leaf, y.is_leaf)
is_leaf:
True True False False False
# 查看梯度
print("gradient:\n", w.grad, x.grad, a.grad, b.grad, y.grad)
gradient:
tensor([5.]) tensor([2.]) None None None
# 查看 grad_fn
print("grad_fn:\n", w.grad_fn, x.grad_fn, a.grad_fn, b.grad_fn, y.grad_fn)
grad_fn:
None None <AddBackward0 object at 0x000000000891BA20> <AddBackward0 object at 0x000000000891BAC8> <MulBackward0 object at 0x000000000891BB00>