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
相关推荐
ZGi.ai2 分钟前
用Agent编排实现合同审查自动化:完整实现过程星马梦缘27 分钟前
强化学习实战7——用决策树打赢星际争霸IICoderJia程序员甲28 分钟前
GitHub 热榜项目 - 日榜(2026-04-11)ChatInfo28 分钟前
Etsy 把 1000 个 MySQL 分片迁进 Vitess:425TB 数据背后的真正问题不是性能,而是运维规模lifallen32 分钟前
Flink Agents:Python 执行链路与跨语言 Actor (PyFlink Agent)小二·32 分钟前
2026年4月技术热点深度解析:AI智能体攻防、量子安全与云原生新纪元江瀚视野33 分钟前
京东健康综合门诊望京开业,京东医疗路在何方?飞凌嵌入式36 分钟前
如何用JishuShell在RK3588核心板上快速部署OpenClaw?IT_陈寒37 分钟前
Vue的响应式更新把我坑惨了,原来是这个问题Tom·Ge37 分钟前
告别“猜谜式编程”!详解规范驱动开发(SDD)在企业AI开发中的最佳实践