【问题标题】:Updating part of a shared variable in Theano在 Theano 中更新共享变量的一部分
【发布时间】:2016-02-28 12:45:38
【问题描述】:

如何在 Theano 中更新部分共享变量?

例如而不是这样做:

gradient_W = T.grad(cost,W)
updates.append((W, W-learning_rate*gradient_W))
train = th.function(inputs=[index], outputs=[cost], updates=updates,
                            givens={x:self.X[index:index+mini_batch_size,:]})

我只想更新W 的一部分,例如只有第一列:

 updates.append((W[:, 0], W[:, 0]-learning_rate*gradient_W))

但是这样做会产生错误TypeError: ('update target must be a SharedVariable', Subtensor{::, int64}.0):

Traceback (most recent call last):
  File "ae.py", line 330, in <module>
    main()
  File "ae.py", line 305, in main
    ae.train(n_epochs=n_epochs, mini_batch_size=100, learning_rate=0.002, train_data= train_sentence_embeddings, test_data= test_sentence_embeddings)
  File "ae.py", line 87, in train
    givens={x:self.X[index:index+mini_batch_size,:]})
  File "/usr/local/lib/python2.7/dist-packages/theano/compile/function.py", line 266, in function
    profile=profile)
  File "/usr/local/lib/python2.7/dist-packages/theano/compile/pfunc.py", line 489, in pfunc
    no_default_updates=no_default_updates)
  File "/usr/local/lib/python2.7/dist-packages/theano/compile/pfunc.py", line 194, in rebuild_collect_shared
    store_into)
TypeError: ('update target must be a SharedVariable', Subtensor{::, int64}.0)

在 Theano 中这样做的典型方式是什么?

W是一个典型的权重矩阵:

initial_W = np.asarray(rng.uniform(
                 low=-4 * np.sqrt(6. / (self.hidden_size + self.n)),
                 high=4 * np.sqrt(6. / (self.hidden_size + self.n)),
                 size=(self.n, self.hidden_size)), dtype=th.config.floatX)
W = th.shared(value=initial_W, name='W', borrow=True)

【问题讨论】:

    标签: python neural-network theano


    【解决方案1】:

    您可以使用例如theano.tensor.set_subtensor.

    按照您上面提到的更新行,这变成:

    updates.append((W, T.set_subtensor(W[:, 0], W[:, 0]-learning_rate*gradient_W)))
    

    T = theano.tensor.

    另一种可能性,在您的情况下更简洁一点,是T.inc_subtensor,您只指定增量而不是新值:

    updates.append((W, T.inc_subtensor(W[:, 0], -learning_rate*gradient_W)))
    

    【讨论】:

    • 请确保在您的代码中learning_rate * gradient_W 实际上具有正确的形状。如果它是完整的W 的渐变,您也必须对其进行切片。
    • 谢谢,我发现你的答案比我刚刚在常见问题解答中偶然发现的更好(deeplearning.net/software/theano/tutorial/faq_tutorial.html,这个问题实际上是常见问题解答中唯一的问题),如常见问题解答中的@ 987654329@ 必须用子张量表示。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-23
    • 1970-01-01
    • 2013-10-29
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    相关资源
    最近更新 更多