使用Theano计算前向传播

0 投票
1 回答
1131 浏览
提问于 2025-04-18 06:32

我尝试用Theano编写前向传播的代码。我定义了一个叫做hiddenLayer的类,如下所示:

import theano.tensor as T
from theano import shared
import numpy as np
from theano import function

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的函数,但它报错了,代码如下:

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)

错误信息是:

theano.compile.function_module.UnusedInputError: theano.function was asked to create a function computing outputs given certain inputs, but the provided input variable at index 0 is not part of the computational graph needed to compute the outputs: x.
To make this error into a warning, you can pass the parameter on_unused_input='warn' to theano.function. To disable it completely, use on_unused_input='ignore'.

你能告诉我问题出在哪里,以及怎么解决吗?谢谢!

1 个回答

1

问题在于你在第二个循环中覆盖了 l.x。这是不可行的。一旦在 init 中使用了 self.x,基于它的结果就依赖于当前的 self.x 实例。所以当你覆盖它时,其他的东西不会在新的 x 上重新创建。

你应该把 x 作为输入传递给 init。如果是 None,就创建一个。这是针对第一层的。对于其他层,应该使用前一层的输出。

def __init__(self, n_in, n_out, x=None):
   if x is not None:
      self.x = x
   else:
      x = T.dvector('x')

撰写回答