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
相关推荐
前端小豆几秒前
玩转 OpenClaw:打造你的私有 AI 助手网关BugShare12 分钟前
写一个你自己的Agent Skills机器之心33 分钟前
英伟达护城河被AI攻破,字节清华CUDA Agent,让人人能搓CUDA内核后端小肥肠2 小时前
公众号躺更神器!OpenClaw+Claude Skill 实现自动读对标 + 写文 + 配图 + 存入草稿箱爱可生开源社区2 小时前
SCALE | 重构 AI 时代数据库能力的全新评估标准Jahzo2 小时前
openclaw本地化部署体验与踩坑记录--飞书机器人配置Narrastory2 小时前
明日香 - Pytorch 快速入门保姆级教程(一)数据智能老司机2 小时前
用于进攻性网络安全的智能体 AI——在 n8n 中构建你的第一个 AI 工作流数据智能老司机2 小时前
用于进攻性网络安全的智能体 AI——智能体 AI 入门Narrastory2 小时前
明日香 - Pytorch 快速入门保姆级教程(二)