Tensorflow:NAN在整个网络中传播,即使使用稀疏的\u softmax

2024-03-29 02:21:49 发布

您现在位置:Python中文网/ 问答频道 /正文

解决了,我有更多输出神经元的目标。在

我相信有问题-现在我认为是tensorflow的sparse_softmax_cross....函数(-before:my data)。我写了一个简单的程序(3lyr network)来看看到底发生了什么:

    import tensorflow as tf
import h5py
import numpy as np

def ini_weight_var(shape):
     return tf.Variable(tf.truncated_normal(shape, stddev=(2.0/shape[0])**0.5))

def ini_bias_var(shape):
     return tf.Variable(tf.constant(0.0, shape=shape))

input_dim = 1287
input_lyr = tf.placeholder(tf.float32, shape=[None, input_dim ])
targs = tf.placeholder(tf.int64, shape=[None,])
w1 = ini_weight_var([input_dim ,2048])
b1 = ini_bias_var([2048])
a1 = tf.nn.elu(tf.matmul(input_lyr, w1) + b1)

w2 = ini_weight_var([2048, 2023])
b2 = ini_bias_var([2023])
out = tf.matmul(a1, w2) + b2
out_sm = tf.nn.softmax(out)

cost = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(out, targs))
get_acc = tf.reduce_mean(tf.cast(tf.equal( tf.argmax(out_sm, 1), targs) ,"float"))
train_adam = tf.train.AdamOptimizer(1e-10).minimize(cost)

d = h5py.File('data-amfb/amfb_train_subset.hdf5','r')
# shapes: f==(1000,1287); t==(1000,) -- types: f.dtype==np.float32; t.dtype==np.int64
f, t = d['feats'][()], d['targs'][()]

with tf.Session() as sess:
    sess.run(tf.initialize_all_variables())
    for i in range(2):
        logit = sess.run(out, feed_dict={input_lyr: f})
        sm_res = sess.run(out_sm, feed_dict={input_lyr: f})
        print("is 0 in logit: {}".format(bool(np.sum(logit==0)))) # For Da Tong.
        print("Smallest sm outputs: {}".format(np.sort(np.min(sm_res, axis=1))[:20]))           
        print("is logit with Nan: {}".format(bool(np.sum(np.isnan(logit)))))
        print("is sm with Nan: {}".format(bool(np.sum(np.isnan(sm_res)))))
        print "Performing backprop."
        sess.run(train_adam, feed_dict={input_lyr: f, targs: t})

        print("Score: {}".format(sess.run(get_acc, feed_dict={input_lyr: f, targs: t})))
        print("Cost: {}".format(sess.run(cost, feed_dict={input_lyr: f, targs: t})))
        print

这里的输出(softmax值显然不太小):

^{2}$

我检查了np.sum(np.isnan(w1).astype(np.int32))和{},它们都等于0。所以我的数据和权重矩阵中没有nan。数据的平均值为0,标准偏差为1。在

(因为我改变了主意)我认为问题与我的数据有关,因为只有这个特定的数据才会出现问题。如果我使用不同的数据,它可以工作(其他特征类型);没有nan。在

我尝试过float32/64和int32/64的所有合理变体。我尝试过各种学习率和值。我也试过不同的重量指数。在

现在我没主意了。在

编辑:我在训练了一个历元后打印出隐藏层的激活,这导致了NaNs。如果我在一切正常之前把它打印出来。所以tf.nn.sparse_softmax_cross_entropy_with_logits出了问题。在

我的登录很小。不知道这是否意味着什么。Softmax应该使一切正常化。在


Tags: runformatinputvartfnpoutini