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]))
相关推荐
Liue612312311 小时前
基于YOLOv26的口罩佩戴检测与识别系统实现与优化
人工智能·yolo·目标跟踪
小二·3 小时前
Python Web 开发进阶实战 :AI 原生数字孪生 —— 在 Flask + Three.js 中构建物理世界实时仿真与优化平台
前端·人工智能·python
chinesegf3 小时前
文本嵌入模型的比较(一)
人工智能·算法·机器学习
哥布林学者3 小时前
吴恩达深度学习课程五:自然语言处理 第二周:词嵌入 课后习题与代码实践
深度学习·ai
珠海西格电力3 小时前
零碳园区的能源结构优化需要哪些技术支持?
大数据·人工智能·物联网·架构·能源
Black蜡笔小新3 小时前
视频汇聚平台EasyCVR打造校园消防智能监管新防线
网络·人工智能·音视频
珠海西格电力科技3 小时前
双碳目标下,微电网为何成为能源转型核心载体?
网络·人工智能·物联网·云计算·智慧城市·能源
2501_941837263 小时前
【计算机视觉】基于YOLOv26的交通事故检测与交通状况分析系统详解_1
人工智能·yolo·计算机视觉
HyperAI超神经4 小时前
加州大学构建基于全连接神经网络的片上光谱仪,在芯片级尺寸上实现8纳米的光谱分辨率
人工智能·深度学习·神经网络·机器学习·ai编程
badfl4 小时前
AI漫剧技术方案拆解:NanoBanana+Sora视频生成全流程
人工智能·ai·ai作画