tensorflow - 实现张量和矩阵的计算图和自动微分器
问题描述
我正在尝试实现一个非常简单的深度学习框架,例如 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上进行训练。
解决方案
推荐阅读
- sql - SQL - 列出我们在 1996 年没有进行销售的所有客户
- python - 分割连字符分隔的单词,中间有空格 | Python
- php - 使用条件语句循环时出现致命错误允许内存耗尽
- angular - 如何创建自定义键 Angular Firebase CRUD 以创建嵌套子级
- javascript - 如何在我的谷歌地图 api 网络中添加多个搜索框?
- reactjs - 在动态 URL 中传递查询参数以在另一个页面上使用
- github - 将整个主分支从一个 GitHub 企业服务器复制到另一个位置的另一个 GitHub 企业服务器
- python - 基于多行值改变行值的有效方法
- mule - Mule - 从 HashMap 生成 JSON 格式的有效负载
采用以下格式 - python - 在解析 XML 时检查 None 值