【问题标题】:TensorFlow model gets loss 0TensorFlow 模型损失为 0
【发布时间】:2017-10-02 06:22:59
【问题描述】:
import tensorflow as tf
import numpy as np
def weight(shape):
return tf.Variable(tf.truncated_normal(shape, stddev=0.1))
def bias(shape):
return tf.Variable(tf.constant(0.1, shape=shape))
def output(input,w,b):
return tf.matmul(input,w)+b
x_columns = 33
y_columns = 1
layer1_num = 7
layer2_num = 7
epoch_num = 10
train_num = 1000
batch_size = 100
display_size = 1
x = tf.placeholder(tf.float32,[None,x_columns])
y = tf.placeholder(tf.float32,[None,y_columns])

layer1 = 
tf.nn.relu(output(x,weight([x_columns,layer1_num]),bias([layer1_num])))
layer2=tf.nn.relu
(output(layer1,weight([layer1_num,layer2_num]),bias([layer2_num])))
prediction = output(layer2,weight([layer2_num,y_columns]),bias([y_columns]))

loss=tf.reduce_mean
(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction))
train_step = tf.train.AdamOptimizer().minimize(loss)

sess = tf.InteractiveSession()
sess.run(tf.global_variables_initializer())
for epoch in range(epoch_num):
   avg_loss = 0.
   for i in range(train_num):
      index = np.random.choice(len(x_train),batch_size)
      x_train_batch = x_train[index]
      y_train_batch = y_train[index]
      _,c = sess.run([train_step,loss],feed_dict=
{x:x_train_batch,y:y_train_batch})
      avg_loss += c/train_num
   if epoch % display_size == 0:
      print("Epoch:{0},Loss:{1}".format(epoch+1,avg_loss))
print("Training Finished")

我的模型得到 纪元:2,损失:0.0 纪元:3,损失:0.0 纪元:4,损失:0.0 纪元:5,损失:0.0 纪元:6,损失:0.0 纪元:7,损失:0.0 纪元:8,损失:0.0 纪元:9,损失:0.0 纪元:10,损失:0.0 训练结束

我该如何处理这个问题?

【问题讨论】:

    标签: python tensorflow cross-entropy


    【解决方案1】:

    softmax_cross_entropy_with_logits 期望标签为 one-hot 形式,即形状为 [batch_size, num_classes] 。在这里,你有y_columns = 1,这意味着只有 1 个类,它必须始终是预测的类和“基本事实”(从你的网络的角度来看),所以无论权重是什么,你的输出总是正确的。因此,loss=0

    我猜你确实有不同的类,y_train 包含标签的 ID。那么predictions 的形状应该是[batch_size, num_classes],而不是softmax_cross_entropy_with_logits 你应该使用tf.nn.sparse_softmax_cross_entropy_with_logits

    【讨论】:

    • 非常感谢!您的回答告诉我,我在输入类方面犯了一个错误。我已经能够预测了!
    猜你喜欢
    • 2021-08-23
    • 2020-10-08
    • 2020-08-06
    • 1970-01-01
    • 2021-09-06
    • 2018-11-29
    • 1970-01-01
    • 2017-06-22
    • 2023-03-20
    相关资源
    最近更新 更多