Alcott
Alcott

Reputation: 18585

change a subset of elements' values in theano matrix

I want to create a mask matrix dynamically, for example, in numpy

mask = numpy.zeros((5,5))
row = numpy.arange(5)
col = [0, 2, 3, 0, 1]
mask[row, col] += 1   # that is setting some values to `1`

Here is what I tried in theano,

mask = tensor.zeros((5,5))
row = tensor.ivector('row')
col = tensor.ivector('col')
mask = tensor.set_subtensor(mask[row, col], 1)

the above theano code failed with error message: not supported. Any other ways?

Upvotes: 2

Views: 1656

Answers (1)

eickenberg
eickenberg

Reputation: 14377

This works for me on 0.6.0. I used your code and created a function from it to check the output. Try copying and pasting this:

import theano
from theano import tensor

mask = tensor.zeros((5,5))
row = tensor.ivector('row')
col = tensor.ivector('col')
mask = tensor.set_subtensor(mask[row, col], 1)

f = theano.function([row, col], mask)

print f(np.array([0, 1, 2]).astype(np.int32), np.array([1, 2, 3]).astype(np.int32))

This yields

array([[ 0.,  1.,  0.,  0.,  0.],
       [ 0.,  0.,  1.,  0.,  0.],
       [ 0.,  0.,  0.,  1.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.]])

Upvotes: 4

Related Questions