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
相关推荐
还是转转13 分钟前
AI Code Review 工具艾莉丝努力练剑13 分钟前
【Git:多人协作】Git多人协作实战:从同分支到多分支工作流拓端研究室3 小时前
专题:2025AI产业全景洞察报告:企业应用、技术突破与市场机遇|附920+份报告PDF、数据、可视化模板汇总下载lumi.4 小时前
Vue + Element Plus 实现AI文档解析与问答功能(含详细注释+核心逻辑解析)m0_650108245 小时前
InstructBLIP:面向通用视觉语言模型的指令微调技术解析金融小师妹6 小时前
基于NLP语义解析的联储政策信号:强化学习框架下的12月降息概率回升动态建模山顶夕景7 小时前
【RL】Does RLVR enable LLMs to self-improve?AKAMAI7 小时前
提升 EdgeWorker 可观测性:使用 DataStream 设置日志功能银空飞羽8 小时前
让Trae CN SOLO自主发挥,看看能做出一个什么样的项目cg50178 小时前
基于 Bert 基本模型进行 Fine-tuned