Search code examples
theano

How to clamp small values to zero in theano


I know the theano clip function, but what I want to do is different: I have a vector and if an entry is small, but not zero, I want to make it zero. Entries greater than the given threshold will remain unchanged. Is there a way to do that in theano?


Solution

  • You can clip the values of a vector below a specific threshold to zero with the following code snippet:

    import theano
    import theano.tensor as T
    
    x = T.ivector('x')
    threshold = 5  # change accordingly
    x_clipped = x * (x > threshold)
    
    f = theano.function(inputs=[x], outputs=x_clipped)
    
    print(f([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))