Tbertin
Tbertin

Reputation: 645

How to count positive values in a tensor?

How to count the number of positive values in a tensor in TENSORFLOW ?

Thanks for your help.

Upvotes: 4

Views: 3103

Answers (1)

benjaminplanche
benjaminplanche

Reputation: 15119

res = tf.count_nonzero(tf.greater_equal(x, 0.))
                       # or using tf.greater() if you want to exclude 0.

Example:

import tensorflow as tf

x = tf.random_uniform((10,), -2, 2)
res = res = tf.count_nonzero(tf.greater_equal(x, 0.))

with tf.Session() as sess:
    x_val, res_val = sess.run([x, res])
    print(x_val)
    # [-1.5928602 - 0.95617723  1.0444398   0.65296173  1.2118826 - 0.69604445 - 1.3821526   1.3174543 - 1.2171302 - 1.5908141]
    print(res_val)
    # 4

Upvotes: 6

Related Questions