首页 > 解决方案 > 实现张量和矩阵的计算图和自动微分器

问题描述

我正在尝试实现一个非常简单的深度学习框架,例如 PyTorch,以便更好地理解计算图和自动微分。我为受https://github.com/karpathy/micrograd启发的标量值实现了一个自动微分器,然后我尝试实现一个张量自动微分器,您可以在下面的代码中看到它。

import numpy as np
class Tensor:
    def __init__(self,data,_children=()):
        self.data=data
        self.grad=np.zeros_like(self.data)
        self._prev=set(_children)
        self._backward=lambda :0
        
    def __str__(self):
        return f"Tensor of shape {self.data.shape} with grad {self.grad}"

    def dag(self):
        topo=[]
        visited=set()
        def build_topo(v):
            visited.add(v)
            for i in v._prev:
                if(i not in visited):
                    build_topo(i)
                else:
                    pass
            topo.append(v)

        build_topo(self)
        topo.reverse()
        return topo
        
    def backward(self):
        topo=self.dag()
        self.grad=np.ones_like(self.data)
        for v in topo:
            v._backward()

    @staticmethod
    def sum(self,other):
        _tensor=Tensor(self.data+other.data,(self,other))
        def _back():
            self.grad=_tensor.grad
            other.grad=_tensor.grad
        _tensor._backward=_back
        return _tensor

    @staticmethod
    def dot(self,other):
        assert self.data.shape[1]==other.data.shape[0],  \
            f"can't multiply two Tensor with shape {self.data.shape} and {other.data.shape}"
        _tensor=Tensor(np.dot(self.data,other.data),(self,other))
        def _back():
            self.grad=(_tensor.grad*other.data.T)
            other.grad=(_tensor.grad*self.data)
        _tensor._backward=_back
        return _tensor



我的问题是,当我们有一个输入数据矩阵时,我应该如何实现一个自动微分器,每个输入都是矩阵的一个列向量(就像我们在神经网络中为训练所做的那样),因为我想实现一个FPGA上的矩阵乘法器硬件并将我的框架连接到它以在FPGA上进行训练。

标签: tensorflowdeep-learningneural-networkpytorchautomatic-differentiation

解决方案


推荐阅读