tensorflow softmax始终返回1

时间:2017-09-23 17:42:14

标签: tensorflow softmax

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

出:

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

我不明白为什么我总是收到1,无论输入如何,无论我是否包含偏见B ......任何想法?会很感激。

3 个答案:

答案 0 :(得分:1)

在我看来,您需要将4x5 array of char a b c d e f g h i j k l m n o p q r s t 4x5 array of int 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 4x5 array of double 0.00 1.00 2.00 3.00 4.00 5.00 6.00 7.00 8.00 9.00 10.00 11.00 12.00 13.00 14.00 15.00 16.00 17.00 18.00 19.00 Statically sized 3x3 array of int 1 2 3 4 5 6 7 8 9 参数dim作为softmax提供,以便计算 列softmax 行softmax (默认为dim = -1);因为每行只有一个元素(w.shape [1] == 1),无论值是什么,0都会给softmax

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

答案 1 :(得分: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,这将永远让你回归。

答案 2 :(得分: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的输出是2D数组。在你的情况下,[4,1]。 但reduce_sum中的tf.nn.softmax()默认应用于最后一个轴。你总是得到1 b / c你每行只有1个元素。 tf.reshapetf.matmul(k,w)+b的大小更改为[4]。