38、深度学习-自学之路-自己搭建深度学习框架-3、自动梯度计算改进

复制代码
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]))
相关推荐
itwangyang5209 分钟前
AIDD-人工智能药物设计-AI 制药编码之战:预测癌症反应,选对方法是关键
人工智能
蓝桉~MLGT15 分钟前
Ai-Agent学习历程—— 阶段1——环境的选择、Pydantic基座、Jupyter Notebook的使用
人工智能·学习·jupyter
油泼辣子多加37 分钟前
【信创】算法开发适配
人工智能·深度学习·算法·机器学习
数据皮皮侠42 分钟前
2m气温数据集(1940-2024)
大数据·数据库·人工智能·制造·微信开放平台
lzhdim1 小时前
魅族手机介绍
人工智能·智能手机
Debroon1 小时前
现代医疗中的AI智能体
人工智能
Winner13001 小时前
查看rk3566摄像头设备、能力、支持格式
linux·网络·人工智能
shizhenshide1 小时前
“绕过”与“破解”的成本账:自行研发、购买API与外包打码的性价比全分析
人工智能·验证码·recaptcha·ezcaptcha·recaptcha v2
龙腾亚太1 小时前
大模型在工业物流领域有哪些应用
人工智能·具身智能·智能体·世界模型·智能体培训·具身智能培训
Deepoch1 小时前
智能清洁新纪元:Deepoc开发板如何重塑扫地机器人的“大脑“
人工智能·机器人·清洁机器人·具身模型·deepoc