0

Hi I have a python function where I am trying to map a tensor to. I essentially need to run every element through the function. I am not sure how to map the two parameters to this function. Not only this but even when I remove the second parameter it gives me an error:

TypeError: bad operand type for unary -: 'list'

Here is my full code:

import tensorflow as tf

def sigmoid(x, derivative = False):
    if derivative == True:
        return (1.0/(1+math.exp(-x))) * (1.0 - (1.0/(1+math.exp(-x))))
    return 1.0/(1+math.exp(-x))

# build computational graph
a = tf.placeholder('float', None)

result = tf.map_fn(sigmoid, [a] , tf.float32)

# initialize variables
init = tf.global_variables_initializer()

# create session and run the graph
with tf.Session() as sess:
    sess.run(init)
    print sess.run(result, feed_dict={a: [2,3,4]})

# close session
sess.close()

I was following this: https://www.tensorflow.org/api_docs/python/tf/py_func

EDIT I can do the exp function using tensorflows library:

def sigmoid(x, derivative = False):
    if derivative == True:
        return (1.0/(1+tf.exp(-x))) * (1.0 - (1.0/(1+tf.exp(-x))))
    return 1.0/(1+tf.exp(-x))

1 Answer 1

2

Why cant you use the tf.nn.sigmoid() function?.

def sigmoid(x, derivative = False):
   if derivative == True:
       return tf.nn.sigmoid(x) * (1.0 - tf.nn.sigmoid(x))
   return tf.nn.sigmoid(x)

If you want to call a numpy function in the graph, you can use tf.py_func (The code will be executed in CPU only):

def sigmoid(x, derivative = False):
if derivative == True:
    return (1.0/(1+np.exp(-x))) * (1.0 - (1.0/(1+np.exp(-x))))
return 1.0/(1+np.exp(-x))

# build computational graph
a = tf.placeholder('float', None)

result = tf.py_func(sigmoid, [a, True] , tf.float32)
Sign up to request clarification or add additional context in comments.

5 Comments

This will work, but how can I get it to use the derivative? As in how can I pass two parameters into the function?
Just call, result = sigmoid(a, derivative = True)?
Thanks, How about if I needed to do an operation that required numpy. From what I understand I would not be able to do this?
I thought that the py_func did this? tensorflow.org/api_docs/python/tf/py_func
@kevin you are right, we can use py_func to call numpy functions. Updated the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.