0
$\begingroup$

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():
    sess=tf.Session
    a=tf.constant([[2,3]])
    answer= multiplication(a)
    print(sess.run(answer))
    #answer should be 6
$\endgroup$
1
$\begingroup$

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:
    sess.run(b)

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

| improve this answer | |
$\endgroup$

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.