Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting all negative values of a tensor to zero (in tensorflow)

Tags:

tensorflow

Here's my problem. I have a tensor X and I want to set all negative values to zero. In numpy, I would do the following np.maximum(0, X). Is there any way to achieve the same effect in tensorflow? I tried tf.maximum(tf.fill(X.get_shape(), 0.0), X), but this throws ValueError: Cannot convert a partially known TensorShape to a Tensor: (?,).

PS. X is a 1-D tensor of shape (?,).

like image 437
dfridman1 Avatar asked Dec 08 '16 16:12

dfridman1


People also ask

How do I change the value of a tensor?

we can modify a tensor by using the assignment operator. Assigning a new value in the tensor will modify the tensor with the new value.

How do you know if a tensor is all zeros?

You can use tf. math. count_nonzero() to check whether the tensor has all zeros or not.

What are three parameters that define tensors in TensorFlow?

Tensors are the basic data structures in TensorFlow, and they represent the connecting edges in a dataflow graph. A tensor simply identifies a multidimensional array or list. The tensor structure can be identified with three parameters: rank, shape, and type. Rank: Identifies the number of dimensions of the tensor.


2 Answers

As it happens, your problem is exactly the same as computing the rectifier activation function, and TensorFlow has a built-in operator, tf.nn.relu(), that does exactly what you need:

X_with_negatives_set_to_zero = tf.nn.relu(X)
like image 55
mrry Avatar answered Sep 19 '22 16:09

mrry


You can use tf.clip_by_value function as follows:

t = tf.clip_by_value(t, min_val, max_val)

It will clip tensor t in the range [min_val, max_val]. Here you can set min_val to 0 to clip all negative values and set those to 0. More documentation about clip_by_value.

like image 39
Jayati Deshmukh Avatar answered Sep 20 '22 16:09

Jayati Deshmukh