Let us assume that I have a tensor in tensorflow with 2 elements.

How do I extract these individual elements and perform calculations on them?

def multiplication(a):
    return a[0]*a[1]

def main():
    answer= multiplication(a)
    #answer should be 6

First recognize that your input array has shape (1,2), so a[0]*a[1] will not work.

Following is the code that is working for me-

def mul(a):
    return a[0][0]*a[0][1]

a = tf.constant([[2,3]])
b = tf.contrib.eager.py_func(func = mul, inp=[a], Tout = tf.int32)
with tf.Session() as sess:

If you want to pass custom functions, check this link- https://www.tensorflow.org/api_docs/python/tf/py_function

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.