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
相关推荐
跨境联盟5 分钟前
行业思考|精准营养会成为社区健康驿站的核心竞争力吗?龙亘川9 分钟前
长假大客流复盘|数字化助力城市交通与文旅态势智能管控糖炒狗子11 分钟前
NeurIPS 2025 最佳论文逐行拆解:一个 sigmoid 门控,让 Attention Sink 从 46.7% 掉到 4.8%zmsup20 分钟前
AI Agent 架构详解:从 ReAct、规划执行到多智能体协作玩AI的奶茶25 分钟前
从零到跑通:在算家云上部署大模型的完整操作手册(实例创建 / 镜像选择 / 远程连接 / 成本控制)超级架构师26 分钟前
迈向数字文明的秩序基石:全面解析 AICTRI 开源 AI 智能体身份与访问管理规范(AgentIAM)智能制造爱好者27 分钟前
7 类新能源汽车驱动电机梳理:从技术特性到量产落地DcMedia元宇宙28 分钟前
智能体丛林法则1:人类的存活与演进田里的水稻30 分钟前
EI_策略训练--机器人策略训练的神经网络种类一QYR-分析33 分钟前
锂电制造核心装备:全球电芯焊接机市场格局与增长趋势研判