训练神经网络时,得到的损失值为0。

3
我不确定是否应该粘贴整个代码,但是这里是它:
import tensorflow as tf 
import numpy as np  
import requests 
from sklearn.model_selection import train_test_split

BATCH_SIZE = 20


#Get data
birthdata_url = 'http://springer.bme.gatech.edu/Ch17.Logistic/Logisticdat/lowbwt.dat'
birth_file = requests.get(birthdata_url)
birth_data = birth_file.text.split('\r\n')[5:]
birth_data = np.array([[x for x in y.split(' ') if len(x)>=1] for y in birth_data[1:] if len(y)>=1])

#Get x and y vals
y_vals = np.array([x[1] for x in birth_data]).reshape((-1,1))
x_vals = np.array([x[2:10] for x in birth_data])

#Split data
x_train, x_test, y_train, y_test = train_test_split(x_vals,y_vals,test_size=0.3)


#Placeholders
x_data = tf.placeholder(dtype=tf.float32,shape=[None,8])
y_data = tf.placeholder(dtype=tf.float32,shape=[None,1])


#Define our Neural Network

def init_weight(shape):
    return tf.Variable(tf.truncated_normal(shape=shape,stddev=0.1))

def init_bias(shape):
    return tf.Variable(tf.constant(0.1,shape=shape))

def fully_connected(inp_layer,weights,biases):
    return tf.nn.relu(tf.matmul(inp_layer,weights)+biases)

def nn(x):
    w1 = init_weight([8,25])
    b1 = init_bias([25])
    layer1 = fully_connected(x,w1,b1)

    w2 = init_weight([25,10])
    b2 = init_bias([10])
    layer2 = fully_connected(layer1,w2,b2)

    w3 = init_weight([10,3])
    b3 = init_bias([3])
    layer3 = fully_connected(layer2,w3,b3)

    w4 = init_weight([3,1])
    b4 = init_bias([1])
    final_output = fully_connected(layer3,w4,b4)


    return final_output




#Predicted values.
y_ = nn(x_data)


#Loss and training step.
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_data,logits=y_))
train_step = tf.train.AdamOptimizer(0.1).minimize(loss)

#Initalize session and global variables
sess = tf.Session()
sess.run(tf.global_variables_initializer())

#Accuracy
def get_accuracy(logits,labels):
    batch_predicitons = np.argmax(logits,axis=1)
    num_correct = np.sum(np.equal(batch_predicitons,labels))
    return(100*num_correct/batch_predicitons.shape[0])



loss_vec = []
for i in range(500):
    #Get random indexes and create batches. 
    rand_index = np.random.choice(len(x_train),size=BATCH_SIZE)

    #x and y batch.
    rand_x = x_train[rand_index]
    rand_y = y_train[rand_index]

    #Run the training step.
    sess.run(train_step,feed_dict={x_data:rand_x,y_data:rand_y})

    #Get the current loss. 
    temp_loss = sess.run(loss,feed_dict={x_data:x_test,y_data:y_test})
    loss_vec.append(temp_loss)

    if(i+1)%20==0:
        print("Current Step is: {}, Loss: {}"
            .format((i+1),
            temp_loss))

    #print("-----Test Accuracy: {}-----".format(get_accuracy(logits=sess.run(y_,feed_dict={x_data:x_test}),labels=y_test)))

当我运行我的程序时,在训练时总是得到0的损失值。我不确定问题可能出在哪里,但我有一些想法。
1)可能是我创建数据批次的方式有问题吗?看起来很奇怪,但据我所知,通过获取随机索引,如 rand_index = np.random.choice(len(x_train),size=BATCH_SIZE) 应该能够工作。
2)这没有意义,但是是因为数据“小”吗?
3)代码中是否有任何简单的错误?
4)或者我的确丢失了0。(这是最不可能的情况)
如果你能指出我在上面的代码中应该避免做什么,我将非常感激。
谢谢。

1
我暂时看不出有什么问题,但为什么不打印出预测结果来帮助调试呢?至少这样你可以再次检查损失的计算。 - Aaron
@Aaron 我得到了一个形状为(20,1)的零值,很有趣... - Huzo
1
我会尝试调试这个问题的另一个方法是移除一些隐藏层,使神经网络更简单。 - Aaron
同时,你的最后一层不应该使用ReLU激活函数。 - Aaron
@Aaron 我可以问一下原因吗?这是针对relu的特定情况吗? - Huzo
1
因为你已经在输出层使用了softmax作为非线性函数。 - Aaron
1个回答

4
我运行了您的代码,发现以下问题:
  1. 看起来您的输入数据是字符串。您应该将其转换为浮点数。
  2. 最后一层不应使用relu。它应直接进入损失函数而没有非线性。
  3. 您应该使用sigmoid_cross_entropy_with_logits函数而不是softmax函数。Sigmoid用于二元分类,softmax用于多类分类。
  4. 您的学习率可能过高。我建议尝试较低的学习率。

1
感谢指出这些错误,非常有帮助。现在我知道选择熵函数的重要性了。 - Huzo
我已经多次进行了调整,但仍然失败。你能得到合法的结果吗?在每个训练步骤中,我总是得到100%的准确度。 - Huzo
啊,我明白了。现在我看到了我的错误。非常感谢您的努力和帮助!我可以再问一个问题吗?训练完成后,神经网络不应该返回0或1吗?因为它返回从-3到1的值。对此有什么想法吗?再次感谢您! - Huzo
1
您可以从 y_ 中获取输出,如果它小于0,则视为0;如果大于0,则视为1。另外,您也可以计算 probs = tf.sigmoid(y_),这样您就可以得到属于正类的预估概率。 - Aaron

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接