图上的c++反向传播异构的向量

C++ Back-propagation on a Graph; heterogeneous vectors?

本文关键字:传播 异构 向量 c++      更新时间:2023-10-16

过去我已经成功地编写了一些神经网络。我已经编写了一个多层感知器,具有完全连接的层(任何大小和数量),并使用backprop训练它。我做了一个卷积网络,并通过手写/计算数学找到了它的梯度。我现在试着说得更一般一些。本着Theano的精神,我想为任何计算图编写反向传播。

考虑以下Python代码:

from __future__ import division
from pylab import *
class Node(object):
    def __init__(self):
        self.children = []
        self.parents = []
        self.state = []
    def forward_prop(self):
        for child in self.children:
            child.forward_prop()

class Static(Node):
    def __init__(self, *shape):
        super(Static, self).__init__()
        state = zeros(shape)
class MatrixProduct(Node):
    def __init__(self, w, x):
        super(MatrixProduct, self).__init__()
        self.w = w
        self.x = x
        self.state = [0]*len(x.state)
    def forward_prop(self):
        self.state = self.w.state.dot(self.x.state)
        for child in self.children:
            child.forward_prop()
class Doubler(Node):
    def __init__(self):
        super(Doubler, self).__init__()
    def forward_prop(self):
        self.state = [s*2 for s in self.state]
        for child in self.children:
             child.forward_prop()

a = Static()
a.state = array([2,3])
w = Static()
w.state = array([[1,2],[3,4]])
x = MatrixProduct(w, a)
a.children.append(x)
d = Doubler()
d.state.append(3)
x.children.append(d)
a.forward_prop()
print a.state
print d.state

我主要看到如何将其移植到c++。我的问题是我不知道如何有孩子的工作在c++的前向传播。在Python中,这很容易,因为child是一个潜在异构类型的列表,每个类型都有自己的forward_propagate行为。在c++中,我该怎么做?

我觉得答案是继承,但如果它们都是某个基类,那么它调用基类向前传播,而不是子。

我想避免冗余。节点知道要做什么操作将输入转化为输出。但是,它们可以接受不同类型的输入,只要它们的形状相同。在IE中,ElementwiseVectorDoubler节点可以将任何处理向量的节点作为输入并将其作为输出。可以从矩阵乘法中获得输入,等等……但是我不想为输入输出的每种特定类型的1d向量都有单独的ElementwiseVectorDoubler类

回答。谢谢你UnholySheep。我只需要虚函数。http://www.cplusplus.com/doc/tutorial/polymorphism/