I want to calculate the sum of zero or more tensor elements in Tensorflow.

Asked 1 years ago, Updated 1 years ago, 42 views

t=tf.constant([1,-1,2,-3], [3,4,-3,2], [2,-1,-2,-3], [2,2,3,1])

If there is, I would like to select only the positive value from the elements of t to produce a sum. What should I do?
Simply put, I would like to use tensorflow for the following things.

sum=0
for i in len(t):
  for jinlen(t[0]):
    if t[i][j]>0:
      sum+=t[i][j]
=>sum == 22

Thank you for your cooperation.

python tensorflow

2022-09-30 15:49

2 Answers

# For each element, the maximum value compared to the zero matrix can be used to exclude negative numbers.
z=tf.constant(0,shape=[4,4],dtype=tf.int32)
abs = tf.maximum(t,z)

# take the sum of all the elements
result=tf.reduce_sum(abs)


2022-09-30 15:49

condition=tf.greater(t,0)
sum = tf.reduce_sum(tf.select(condition,t,tf.zeros_like(t)))

Now I know you can do it with

If it's tf.select, I think it works with both old and new versions.
If you are using a relatively new version, it seems possible to do the following as well.

sum=tf.reduce_sum(tf.where(condition,t,tf.zeros_like(t)))

*I use 0.8.0, so I can't use where like this


2022-09-30 15:49

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.