Updating part of a shared variable in Theano

How to update part of a shared variable in Theano?

eg. instead of doing:

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,:]})

I would only like to update the part W, for example. only the first column:

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

But an error appears 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)

What is the typical way to do this in Theano?

W - typical weight matrix:

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)
+4
source share
1 answer

You can use for example. theano.tensor.set_subtensor.

Taking the update line that you mentioned above, it will be:

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

where T = theano.tensor.

Another possibility, a bit shorter in your case, is T.inc_subtensorwhere you specify only the gain instead of the new value:

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

Source: https://habr.com/ru/post/1617485/


All Articles