2017-07-17 130 views
0

嗨我有一個python函數,我試圖將張量映射到。我基本上需要通過函數運行每個元素。我不知道如何將這兩個參數映射到這個函數。不僅如此,但即使我刪除第二個參數,它給了我一個錯誤:Tensorflow - 使用兩個參數映射python函數

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

這裏是我的全碼:

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() 

我下面這個:https://www.tensorflow.org/api_docs/python/tf/py_func

編輯 我可以用張量流庫做exp函數:

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)) 

回答

2

爲什麼不能使用tf.nn.sigmoid()函數?

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

如果你想要把一個numpy函數曲線圖,你可以使用tf.py_func(代碼將在CPU執行只):

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) 
+0

這是可行的,但我怎樣才能得到它使用衍生物?如何在函數中傳遞兩個參數? – Kevin

+0

Just call,result = sigmoid(a,derivative = True)? –

+0

謝謝,如果我需要做一個需要numpy的操作的話。從我的理解我不能做到這一點? – Kevin