import numpy as np
class Tensor(object):
def __init__(self, data,
autograd=False,
creators=None,
creation_op=None,
id=None):
self.data = np.array(data)
self.autograd = autograd
self.grad = None
if (id is None):
self.id = np.random.randint(0, 100000)
else:
self.id = id
self.creators = creators
self.creation_op = creation_op
self.children = {}
if(creators is not None):
for c in creators:
if(self.id not in c.children):
c.children[self.id] = 1
else:
c.children[self.id] += 1
def all_children_grads_accounted_for(self):
for id, cnt in self.children.items():
if (cnt != 0):
return False
return True
def backward(self, grad=None, grad_origin=None):
if (self.autograd):
if (grad is None):
grad = FloatTensor(np.ones_like(self.data))
if (grad_origin is not None):
if (self.children[grad_origin.id] == 0):
raise Exception("cannot backprop more than once")
else:
self.children[grad_origin.id] -= 1
if (self.grad is None):
self.grad = grad
else:
self.grad += grad
# grads must not have grads of their own
assert grad.autograd == False
# only continue backpropping if there's something to
# backprop into and if all gradients (from children)
# are accounted for override waiting for children if
# "backprop" was called on this variable directly
if (self.creators is not None and
(self.all_children_grads_accounted_for() or
grad_origin is None)):
if (self.creation_op == "add"):
self.creators[0].backward(self.grad, self)
self.creators[1].backward(self.grad, self)
def __add__(self, other):
if (self.autograd and other.autograd):
return Tensor(self.data + other.data,
autograd=True,
creators=[self, other],
creation_op="add")
return Tensor(self.data + other.data)
def __repr__(self):
return str(self.data.__repr__())
def __str__(self):
return str(self.data.__str__())
a = Tensor([1, 2, 3, 4, 5], autograd=True)
b = Tensor([2, 2, 2, 2, 2], autograd=True)
c = Tensor([5, 4, 3, 2, 1], autograd=True)
d = a + b
e = b + c
f = d + e
f.backward(Tensor(np.array([1, 1, 1, 1, 1])))
print(b.grad.data == np.array([2, 2, 2, 2, 2]))
38、深度学习-自学之路-自己搭建深度学习框架-3、自动梯度计算改进
小宇爱2025-02-22 19:02
相关推荐
xcbrand1 分钟前
政府事业机构品牌策划公司哪家可靠逻辑君2 分钟前
认知神经科学研究报告【20260020】2zcode11 分钟前
基于低光照增强与轻量型CNN道路实时识别算法研究(UI界面+数据集+训练代码)萑澈23 分钟前
Xiaomi MiMo Orbit 百亿 Token 计划申请保姆级教程缝艺智研社25 分钟前
誉财 YC - 23 全自动上底裤明橡筋机:裤腰加工的革新力量北京软秦科技有限公司25 分钟前
工厂到货验收的突破:IACheck如何提升AI报告审核效率LaughingZhu27 分钟前
Product Hunt 每日热榜 | 2026-05-03缝艺智研社27 分钟前
誉财 YC - 18 - JG 小型激光模板机:服装缝切工艺的革新先锋m0_4665252932 分钟前
绿盟科技发布2026年一季报,收入微增,亏损收窄,现金流持续为正weixin_4080996733 分钟前
身份证OCR识别中的“隐形防线”:复印件/翻拍检测如何拦截99%的虚假注册?(附多语言代码)