38、深度学习-自学之路-本身搭建深度学习框架-3、自动梯度盘算改进 ...

打印 上一主题 下一主题

主题 969|帖子 969|积分 2907

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. import numpy as np
  2. class Tensor(object):
  3.     def __init__(self, data,
  4.                  autograd=False,
  5.                  creators=None,
  6.                  creation_op=None,
  7.                  id=None):
  8.         self.data = np.array(data)
  9.         self.autograd = autograd
  10.         self.grad = None
  11.         if (id is None):
  12.             self.id = np.random.randint(0, 100000)
  13.         else:
  14.             self.id = id
  15.         self.creators = creators
  16.         self.creation_op = creation_op
  17.         self.children = {}
  18.         if(creators is not None):
  19.             for c in creators:
  20.                 if(self.id not in c.children):
  21.                     c.children[self.id] = 1
  22.                 else:
  23.                     c.children[self.id] += 1
  24.     def all_children_grads_accounted_for(self):
  25.         for id, cnt in self.children.items():
  26.             if (cnt != 0):
  27.                 return False
  28.         return True
  29.     def backward(self, grad=None, grad_origin=None):
  30.         if (self.autograd):
  31.             if (grad is None):
  32.                 grad = FloatTensor(np.ones_like(self.data))
  33.             if (grad_origin is not None):
  34.                 if (self.children[grad_origin.id] == 0):
  35.                     raise Exception("cannot backprop more than once")
  36.                 else:
  37.                     self.children[grad_origin.id] -= 1
  38.             if (self.grad is None):
  39.                 self.grad = grad
  40.             else:
  41.                 self.grad += grad
  42.             # grads must not have grads of their own
  43.             assert grad.autograd == False
  44.             # only continue backpropping if there's something to
  45.             # backprop into and if all gradients (from children)
  46.             # are accounted for override waiting for children if
  47.             # "backprop" was called on this variable directly
  48.             if (self.creators is not None and
  49.                     (self.all_children_grads_accounted_for() or
  50.                      grad_origin is None)):
  51.                 if (self.creation_op == "add"):
  52.                     self.creators[0].backward(self.grad, self)
  53.                     self.creators[1].backward(self.grad, self)
  54.     def __add__(self, other):
  55.         if (self.autograd and other.autograd):
  56.             return Tensor(self.data + other.data,
  57.                           autograd=True,
  58.                           creators=[self, other],
  59.                           creation_op="add")
  60.         return Tensor(self.data + other.data)
  61.     def __repr__(self):
  62.         return str(self.data.__repr__())
  63.     def __str__(self):
  64.         return str(self.data.__str__())
  65. a = Tensor([1, 2, 3, 4, 5], autograd=True)
  66. b = Tensor([2, 2, 2, 2, 2], autograd=True)
  67. c = Tensor([5, 4, 3, 2, 1], autograd=True)
  68. d = a + b
  69. e = b + c
  70. f = d + e
  71. f.backward(Tensor(np.array([1, 1, 1, 1, 1])))
  72. print(b.grad.data == np.array([2, 2, 2, 2, 2]))
复制代码


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

温锦文欧普厨电及净水器总代理

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表