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]))
相关推荐
数据知道几秒前
一文掌握Bard机器翻译,以及用python调用的4种方式(现已升级为 Gemini)
python·自然语言处理·bard·机器翻译·gemini
Swaggy T1 小时前
自动驾驶控制算法——MPC控制算法
linux·人工智能·自动驾驶
2202_756749691 小时前
1深度学习Pytorch-pytorch、tensor的创建、属性、设备和类型转换、数据转换、常见操作(获取元素、元素运算、形状改变、相乘、广播)
人工智能·pytorch·深度学习·机器学习
2501_924879368 小时前
口罩识别场景误报率↓79%:陌讯多模态融合算法实战解析
人工智能·深度学习·算法·目标检测·智慧城市
万粉变现经纪人8 小时前
如何解决pip安装报错ModuleNotFoundError: No module named ‘keras’问题
人工智能·python·深度学习·scrapy·pycharm·keras·pip
whaosoft-1438 小时前
51c自动驾驶~合集12
人工智能
Chan168 小时前
【智能协同云图库】第七期:基于AI调用阿里云百炼大模型,实现AI图片编辑功能
java·人工智能·spring boot·后端·spring·ai·ai作画
计算机科研圈8 小时前
字节Seed发布扩散语言模型,推理速度达2146 tokens/s,比同规模自回归快5.4倍
人工智能·语言模型·自然语言处理·数据挖掘·开源·字节
Christo38 小时前
TFS-2022《A Novel Data-Driven Approach to Autonomous Fuzzy Clustering》
人工智能·算法·机器学习·支持向量机·tfs
陈哥聊测试8 小时前
Coze开源了!意味着什么?
人工智能·ai·开源·项目管理·项目管理软件