2017-09-23 83 views
0
import tensorflow as tf 
import numpy as np 


a = np.array([[0,0,1], [1,1,1], [1000,200,300], [-3000,-0.2,0]]) 

k = tf.placeholder(tf.float32, [None,3]) 
w = tf.Variable(tf.random_normal([3,1])) 
b = tf.Variable(tf.ones([1,1])) 

model = tf.nn.softmax(tf.matmul(k,w)+b) 


with tf.Session() as sess: 
    tf.global_variables_initializer().run() 
    print(sess.run(model, {k:a})) 

出來:tensorflow SOFTMAX始終返回1分

[[ 1.] 
[ 1.] 
[ 1.] 
[ 1.]] 

我不明白爲什麼我總是收到1,沒有輸入的事,不管我是否有偏差B ...任何想法?將不勝感激。

回答

1

變化model = tf.nn.softmax(tf.matmul(k,w)+b)model = tf.nn.softmax(tf.reshape(tf.matmul(k,w)+b, [-1]))

tf.matmul(k,w)+b的輸出是一個二維數組。在你的情況下,[4,1]。 但是tf.nn.softmax()中的reduce_sum默認應用於最後一個軸。你總是得到1 b/c,你每行只有1個元素。 tf.reshapetf.matmul(k,w)+b的大小更改爲[4]。

1

在我看來,你需要提供dim參數softmax0所以計算列SOFTMAX的代替行SOFTMAX(默認昏暗= -1);由於每一行只有一個元素(w.shape [1] == 1),無論價值,softmax1

model = tf.nn.softmax(tf.matmul(k,w) + b, dim=0) 

import tensorflow as tf 
import numpy as np 
​ 
​ 
a = np.array([[0,0,1], [1,1,1], [1000,200,300], [-3000,-0.2,0]]) 
​ 
k = tf.placeholder(tf.float32, [None,3]) 
w = tf.Variable(tf.random_normal([3,1])) 
b = tf.Variable(tf.ones([1,1])) 

model = tf.nn.softmax(tf.matmul(k,w) + b, dim=0) 
​ ​ 
with tf.Session() as sess: 
    tf.global_variables_initializer().run() 
    print(sess.run(model, {k:a})) 

[[ 0.00000000e+00] 
[ 0.00000000e+00] 
[ 1.00000000e+00] 
[ 1.61103498e-12]] 
1

拆分代碼爲兩個步驟:

mul_tensor = tf.matmul(k,w)+b 
model = tf.nn.softmax(mul_tensor) 

with tf.Session() as sess: 
    tf.global_variables_initializer().run() 
    #print(sess.run(model, {k:a})) 
    print(sess.run(mul_tensor, {k:a})) 

你會得到答案的

array([[ 0.69425076], 
     [ 1.7690506 ], 
     [ 41.94503021], 
     [ 309.35256958]], dtype=float32) 

因此,您在1 * 1條目上應用softmax將永遠返回1。