如何更改 Theano 中共享变量的值?

How to change value of a shared variable in Theano?

我定义如下class:

class test:

    def __init__(self):
        self.X = theano.tensor.dmatrix('x')
        self.W = theano.shared(value=numpy.zeros((5, 2), dtype=theano.config.floatX), name='W', borrow=True)
        self.out = theano.dot(self.X, self.W)

    def eval(self, X):
        _eval = theano.function([self.X], self.out)
        return _eval(X)

之后,我尝试更改 W 矩阵的值并使用新值进行计算。我通过以下方式进行:

m = test()
W = np.transpose(np.array([[1.0, 2.0, 3.0, 4.0, 5.0], [2.0, 2.0, 3.0, 3.0, 3.0]]))
dn.W = theano.shared(value=W, name='W', borrow=True)
dn.eval(X)

我得到的结果对应于 __init__ 中设置的 W 的值(所有元素均为零)。

为什么 class 看不到我在初始化后显式设置的 W 的新值?

您刚刚为 python 变量 dn.W 创建了一个新的共享变量,但是 theano 的内部计算图仍然链接到旧的共享变量。

要更改存储在现有共享变量中的值:

W = np.transpose(np.array([[1.0, 2.0, 3.0, 4.0, 5.0], [2.0, 2.0, 3.0, 3.0, 3.0]]))
dn.W.set_value(W))

注意 如果您想使用函数调用的结果来更新共享变量,更好的方法是使用 theano.functionupdates 参数。如果共享变量存储在 GPU 中,这将消除不必要的内存传输。