我正在构建DNN来预测图像中是否存在对象 . 我的网络有两个隐藏层,最后一层看起来像这样:
# Output layer
W_fc2 = weight_variable([2048, 1])
b_fc2 = bias_variable([1])
y = tf.matmul(h_fc1, W_fc2) + b_fc2
然后我有标签的占位符:
y_ = tf.placeholder(tf.float32, [None, 1], 'Output')
我分批进行训练(因此输出图层形状中的第一个参数为无) .
我使用以下损失函数:
cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(
y[:, :1], y_[:, :1], name='xentropy')
loss = tf.reduce_mean(cross_entropy, name='xentropy_mean')
predict_hand = tf.greater(y, 0.5)
correct_prediction = tf.equal(tf.to_float(predict_hand), y_)
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
但在运行时我收到以下错误:
排名不匹配:标签排名(收到2)应该等于logits排名减去1(收到2) .
我想我应该重塑标签层,但不确定它的期望 . 我抬头看了documentation,它说:
logits:秩r和形状[d_0,d_1,...,d_ ,num_classes]和dtype float32或float64的非标定日志概率 . 标签:形状张量[d_0,d_1,...,d_]和dtype int32或int64 . 标签中的每个条目必须是[0,num_classes)中的索引 .
如果我只有一个单独的类,我的标签应该是什么样的(现在它只是0或1)?任何帮助赞赏
4 回答
为何要
在许多教程中,包括here和here,标签的大小为
[None,10]
,并且logits的大小也为[None,10]
.来自
tf.nn.sparse_softmax_cross_entropy_with_logits
的文档*:所以我认为你的标签张量应该是形状
[None]
. 请注意,形状为[None, 1]
或形状为[None]
的给定张量将包含相同数量的元素 .具有具体虚拟值的示例输入:
如果小批量中有3个示例,则第一个示例的
logits
是11和22,并且有2个类:0和1 .问题可能是网络中的激活功能 . 使用tf.nn.softmax_cross_entropy_with_logits而不是sparse_softmax . 这将解决问题 .
In short, here is implements of it
sparse_softmax_cross_entropy_with_logits
softmax_cross_entropy_with_logits_v2和softmax_cross_entropy_with_logits
here is the same implements of softmax_cross_entropy_with_logits_v2