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]))
相关推荐
Bode_20023 分钟前
具身智能机构设计的质量控制
人工智能
阿里云大数据AI技术7 分钟前
EMR Serverless StarRocks × Lance:多模态分析与检索的云上实践
人工智能
SelectDB41 分钟前
数据不能出境的数仓选型与迁移落地:四问框架、可复算成本与迁移三段式
人工智能
李青菜1 小时前
一个人 + AI,用 Tauri 2 和 Rust 写了个开源的 Windows 效率工具:提醒 + 笔记 + 启动器
人工智能
泯泷1 小时前
做 AI 产品,路线图该数“实验”,而不是数“功能”
人工智能·llm·产品
百度Geek说1 小时前
AI 内容核查怎么做:智能内容 AI 核查系统实践
人工智能
武子康2 小时前
Qwen-Drive 到底是什么:4B 级 VLM 如何成为驾驶策略底座
人工智能·算法·机器学习
落798.2 小时前
《启元 PrimeSim 如何用生成视频评估机器人策略》
人工智能·机器人·启元·具身应用
老纪的技术唠嗑局2 小时前
token 暴降75%!减少长程 Agent 任务中的重复开销,PowerContext v1.5.0 发布
人工智能
智塑未来2 小时前
明源云AI走播机器人,打造智能直播新体验
人工智能·机器人