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
相关推荐
寻道码路1 分钟前
AI Agent 工程化开发实战(十四):Deep Agents 能力全景——它到底内置了什么m4Rk_5 分钟前
【论文阅读】Agent 记忆机制(149):SQE——查询扩展能省成本,但简单置信度门控并不可靠土星云SaturnCloud9 分钟前
CAM++ 声纹识别实战(中):调度电话“声纹签章”闭环——原始音频不出场、三级闸门与 10 路承载账炸薯条!11 分钟前
AI人工智能基础入门:大语言模型、AI应用与大模型部署方Elastic 中国社区官方博客14 分钟前
Elastic 获得全新的 AWS 数据能力认证MicrosoftReactor15 分钟前
技术速递|Aspire 17 正式发布,已准备好投入生产使用IT枫斗者16 分钟前
MQ 选型对比:RocketMQ、RabbitMQ、Kafka 各自适合什么场景loulanyue_18 分钟前
AI智能体24小时复刻Photoshop:什么该交给Agent、什么必须留给人——读Brandon Thomas演讲实录flyingonpine24 分钟前
本地大模型能看图修 Bug 吗?Strata + Three.js 三维场景生成与多模态视觉反馈实战愤怒火龙果1 小时前
AI 观察|Gemini 是通往 AGI 的路吗:谷歌首席 AI 架构师访谈要点与 2026 年信息汇总