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]))
相关推荐
Seven971 分钟前
AI杂谈:别再问AI会不会替代你,先看你是不是驾驶员
人工智能·后端
七夜zippoe11 分钟前
OpenClaw 测试策略实战:AI Agent 自动化测试体系搭建与落地
人工智能·ai·自动化·agent·测试体系·openclaw
满怀冰雪12 分钟前
20-卷积神经网络基础:用 Paddle 构建 CNN
人工智能·深度学习·cnn·paddle
(轻舟已过万重山)16 分钟前
第40章 Spring AI 实战:企业级 AI 应用架构
人工智能·spring·架构
zzm62816 分钟前
WSDM 2018论文精读:基于多关系学习与路径约束的商品替代互补关系挖掘
人工智能·学习
aneasystone本尊18 分钟前
学习 Headroom 的 CCR 可逆压缩
人工智能
大模型任我行20 分钟前
谷歌:扩散模型实现极速文本生成
人工智能·语言模型·自然语言处理·论文笔记
IT_陈寒23 分钟前
Vite热更新失效?我的几个犯傻操作害我debug两小时
前端·人工智能·后端
月光船幽幽23 分钟前
锁死后干预有效性的关键突破
人工智能·python·算法
深念Y27 分钟前
CPA-Auto池方案总结
人工智能·ai·自动化·路由·代理·账号·轮询