Search code examples
pythontheano

Theano Tensor remove element?


I am currently trying to learn theano.

Is there a way to, for example, delete/add a row/column from an NxN tensor? The subtensor functionality highlighted in the documentation only modifies elements, not remove them.


Solution

  • Sutensor allow to take part of tensor. It is set_subtensor and inc_subtensor that allow to modify part of them.

    Theano support Python and NumPy indexing and advanced indexing. You can do what you want in many ways. Here is a simple one:

    import theano, numpy
    T = theano.tensor.matrix()
    f = theano.function([T], T[[1, 2, 4]])
    f(numpy.arange(25).reshape(5, 5))
    

    So mostly, you can just pass a list with the index of rows that you want to keep. For colums, just use:

    import theano, numpy
    T = theano.tensor.matrix()
    f = theano.function([T], T[:, [1, 2, 4]])
    f(numpy.arange(25).reshape(5, 5))
    

    To add rows, we support the same interface as numpy, so mostly, you can just build a new tensor by concatenating the part you want:

    import theano, numpy
    T = theano.tensor.matrix()
    o = theano.tensor.concatenate([T[2], T[4], [100, 101, 102, 103, 104]])
    f = theano.function([T], o)
    f(numpy.arange(25).reshape(5, 5))