Python 使用Theano计算前向传播
我试着用Theano编码正向传播。我定义了一个类名hiddenLayer,如下所示: 将无张量导入为T 从没有导入共享 将numpy作为np导入 从无导入函数Python 使用Theano计算前向传播,python,theano,Python,Theano,我试着用Theano编码正向传播。我定义了一个类名hiddenLayer,如下所示: 将无张量导入为T 从没有导入共享 将numpy作为np导入 从无导入函数 class hiddenLayer(): """ Hidden Layer class """ def __init__(self, n_in, n_out): rng = np.random self.W = shared(np.asarray(rng.uniform(low=-n
class hiddenLayer():
""" Hidden Layer class
"""
def __init__(self, n_in, n_out):
rng = np.random
self.W = shared(np.asarray(rng.uniform(low=-np.sqrt(6. / (n_in + n_out)),
high=np.sqrt(6. / (n_in + n_out)),
size=(n_in, n_out)),
dtype=T.config.floatX),
name='W')
self.b = shared(np.zeros(n_out, dtype=T.config.floatX), name='b')
self.x = T.dvector('x')
self.a = T.tanh(T.dot(self.x, self.W) + self.b)
self.W_sum = shared(np.zeros([n_in, n_out]), name='W_sum')
self.gw = 0
self.gb = 0
我想建立一个hiddenLayer对象列表,当前的hiddenLayer是下一个hiddenLayer的输入。最后我定义了一个名为forward buy的函数,它会引发错误,代码如下:
def init_network(n_in, n_out, sl, x, y):
l = []
for i in range(sl):
l.append(hiddenLayer(n_in, n_out))
for i in range(sl):
if i == 0:
l[i].x = x
elif i < sl-1:
l[i].x = l[i-1].a
else:
l[i].x = l[i-1].a
y = l[i].a
return x, y, l
x = T.dvector('x')
y = T.dvector('y')
x, y, l = init_network(3, 3, 3, x, y)
forward = function(inputs=[x], outputs=y)
你能告诉我为什么出了问题,怎么解决吗?谢谢问题是您在第二个循环中覆盖了l.x。你不能那样做。在初始化中使用self.x后,基于它的结果将基于self.x的当前实例。所以当你覆盖它时,它不会在新的x上重新创建其他东西 您应该将x作为输入传递到init。如果没有,创建一个。这是第一层。对于另一个,它应该是前一层输出
def __init__(self, n_in, n_out, x=None):
if x is not None:
self.x = x
else:
x = T.dvector('x')
def __init__(self, n_in, n_out, x=None):
if x is not None:
self.x = x
else:
x = T.dvector('x')