fang jack fang jack - 2 months ago 72
Python Question

IndexError: fail to coerce slice entry of type tensorvariable to integer

I run "ipython debugf.py" and it gave me error message as below

IndexError Traceback (most recent call last)
/home/ml/debugf.py in <module>()
8 fff = theano.function(inputs=[index],
9 outputs=cost,
---> 10 givens={x: train_set_x[index: index+1]})

IndexError: failed to coerce slice entry of type TensorVariable to integer"


I search the forum and no luck, is there someone can help ?
thanks!

debugf.py :

import theano.tensor as T
import theano
import numpy
index =T.lscalar()
x=T.dmatrix()
cost=x +index
train_set_x=numpy.arange(100).reshape([20,5])
fff=theano.function(inputs=[index],
outputs=cost,
givens={x:train_set_x[index: index+1]}) #<--- Error here

Answer

Change train_set_x variable to theano.shared variable, and the code is OK. I dont know the reason, but it works! Hope this post can help others. The correct code is as below

import theano.tensor as T    
import theano    
import numpy    
index =T.lscalar()    
x=T.dmatrix()    
cost=x +index    
train_set_x=numpy.arange(100.).reshape([20,5]) #<--- change to float,
                                   #because shared must be floatX type

#change to shared variable
shared_x = theano.shared(train_set_x)

fff=theano.function(inputs=[index],    
     outputs=cost,    
     givens={x:shared_x[index: index+1]})  #<----change to shared_x
Comments