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]))
相关推荐
灵途科技2 小时前
灵途科技亮相NEPCON ASIA 2025 以光电感知点亮具身智能未来
人工智能·科技·机器人
文火冰糖的硅基工坊3 小时前
[人工智能-大模型-125]:模型层 - RNN的隐藏层是什么网络,全连接?还是卷积?RNN如何实现状态记忆?
人工智能·rnn·lstm
IT90903 小时前
c#+ visionpro汽车行业,机器视觉通用检测程序源码 产品尺寸检测,机械手引导定位等
人工智能·计算机视觉·视觉检测
Small___ming4 小时前
【人工智能数学基础】多元高斯分布
人工智能·机器学习·概率论
Ro Jace4 小时前
机器学习、深度学习、信号处理领域常用符号速查表
深度学习·机器学习·信号处理
渔舟渡简4 小时前
机器学习-回归分析概述
人工智能·机器学习
王哈哈^_^4 小时前
【数据集】【YOLO】目标检测游泳数据集 4481 张,溺水数据集,YOLO河道、海滩游泳识别算法实战训练教程。
人工智能·算法·yolo·目标检测·计算机视觉·分类·视觉检测
桂花饼4 小时前
Sora 2:从视频生成到世界模拟,OpenAI的“终极游戏”
人工智能·aigc·openai·sora 2
wwlsm_zql4 小时前
荣耀YOYO智能体:自动执行与任务规划,开启智能生活新篇章
人工智能·生活
科学计算技术爱好者4 小时前
未来已来:AI 如何在 3 年内重塑工作、教育与生活
人工智能·ai