tensorflow:一级分类

标签 tensorflow classification deep-learning

我正在尝试改编教程 Deep MNIST for Experts要仅检测一个类别,假设检测图像是否包含小猫。

这是我的代码的预测部分:

y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv), reduction_indices=[1]))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
sess.run(tf.initialize_all_variables())
for i in range(20000):
  batch = mnist.train.next_batch(50)
  if i%100 == 0:
    train_accuracy = accuracy.eval(feed_dict={
        x:batch[0], y_: batch[1], keep_prob: 1.0})
    print("step %d, training accuracy %g"%(i, train_accuracy))
  train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})

print("test accuracy %g"%accuracy.eval(feed_dict={
    x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))

问题是,对于一个类别,softmax 总是以 1 的置信度返回该类别,即使对于空白图像也是如此。 我尝试修改 softmax 和交叉熵,但无法解决。

我需要知道针对此问题推荐的方法。 我希望预测图像是小猫的概率。

我知道这可以使用使用随机图像训练的第二个标签来解决,但我需要知道是否有更好的解决方案。

非常感谢。

最佳答案

不要将 softmax 和多类 logloss 用于单类成员预测。相反,更常见的设置是使用二元交叉熵的 sigmoid 激活。除非您正在优化正确预测的成本/ yield *,否则只需将阈值设置为 > 0.5 即可归类为“正”类。

在 TensorFlow 中,这只会在几个地方更改您的代码。

我认为以下调整适用于代码的开头:

y_conv = tf.nn.sigmoid(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)

# I've split the individual loss out because the line length was too long
# The +1e-12 is for numerical stability in case of perfect 0.0 or 1.0 predictions
# Note how this loss metric penalises incorrect predictions in both directions,
# unlike the multiclass logloss which only assessed confidence in
# correct class.
loss = -(y_ * tf.log(y_conv + 1e-12) + (1 - y_) * tf.log( 1 - y_conv + 1e-12))
cross_entropy = tf.reduce_mean(tf.reduce_sum(loss, reduction_indices=[1]))

predict_is_kitty = tf.greater(y_conv,0.5)
correct_prediction = tf.equal( tf.to_float(predict_is_kitty), y_ )

* 如果您正在处理一个您关心预测置信度的问题,并且需要评估在哪里设置阈值,通常的指标而不是准确性是 area under ROC curve, often known as AUROC or just AUC .

关于tensorflow:一级分类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39192380/

相关文章:

tensorflow - Keras二元分类: same prediction output class

python-3.x - 形状 (1,) 和 () 在条件运算符上不兼容

java - 矩阵 TFIDF 的降维

tensorflow - 如何利用客户数据建立回归模型

python - 如何将以下顺序模型转换为keras中的函数模型

javascript - 如何在javascript中导入tensorflow?导入文件,由本地 http 服务器提供服务

python-3.x - 如何打印预测图像的置信度

Python - 分类套索 sklearn - 如何预测类

output - 在命令行中导出 Weka 预测

python - 使用 Google Colab 改回 CPU