mgs
mgs

Reputation: 191

Updating a variable that has been casted with theano.tensor.cast()

I am trying to update a theano variable in a function, simplified like this:

copy_func = theano.function(
    inputs=[idx],
    updates=[
        (a_variable, T.set_subtensor(a_variable[some_ptr], another_variable[idx]))
    ]
)

My problem is that I get the error

TypeError: ('update target must be a SharedVariable', Elemwise{Cast{int32}}.0)

The way I get this variable is through using the following (mostly copied from deeplearning.net tutorials) (another_variable is initialized similarly):

a_variable = theano.shared(np.asarray(data,
                               dtype=theano.config.floatX),
                 borrow=True)
print type(a_variable)
a_variable = T.cast(a_variable, 'int32')
print type(a_variable)

which prints

<class 'theano.tensor.sharedvar.TensorSharedVariable'>
<class 'theano.tensor.var.TensorVariable'>

that is, the variable is no longer "shared", explaining the error. This makes sense, as I guess the variable is now simply just a casted view of the original shared floats. But how can I update a variable that is casted efficiently?

Upvotes: 1

Views: 1190

Answers (1)

mgs
mgs

Reputation: 191

I solved this myself, and the answer was of course the obvious one.

Instead of overriding the a_variable variable with the casted version, I kept the uncasted version:

a_variable_casted = T.cast(a_variable, 'int32')

Updates are now done on a_variable, while a_variable_casted is used to perform the computations a_variable was used for earlier.

There might obviously be a more elegant way to do this, in which case I'd love to hear it!

Upvotes: 1

Related Questions