【问题标题】:TensorFlow for binary classification用于二进制分类的 TensorFlow
【发布时间】:2016-05-18 14:28:08
【问题描述】:

我正在尝试使this MNIST example 适应二进制分类。

但是当我的 NLABELSNLABELS=2 更改为 NLABELS=1 时,损失函数总是返回 0(和准确度 1)。

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf

# Import data
mnist = input_data.read_data_sets('data', one_hot=True)
NLABELS = 2

sess = tf.InteractiveSession()

# Create the model
x = tf.placeholder(tf.float32, [None, 784], name='x-input')
W = tf.Variable(tf.zeros([784, NLABELS]), name='weights')
b = tf.Variable(tf.zeros([NLABELS], name='bias'))

y = tf.nn.softmax(tf.matmul(x, W) + b)

# Add summary ops to collect data
_ = tf.histogram_summary('weights', W)
_ = tf.histogram_summary('biases', b)
_ = tf.histogram_summary('y', y)

# Define loss and optimizer
y_ = tf.placeholder(tf.float32, [None, NLABELS], name='y-input')

# More name scopes will clean up the graph representation
with tf.name_scope('cross_entropy'):
    cross_entropy = -tf.reduce_mean(y_ * tf.log(y))
    _ = tf.scalar_summary('cross entropy', cross_entropy)
with tf.name_scope('train'):
    train_step = tf.train.GradientDescentOptimizer(10.).minimize(cross_entropy)

with tf.name_scope('test'):
    correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    _ = tf.scalar_summary('accuracy', accuracy)

# Merge all the summaries and write them out to /tmp/mnist_logs
merged = tf.merge_all_summaries()
writer = tf.train.SummaryWriter('logs', sess.graph_def)
tf.initialize_all_variables().run()

# Train the model, and feed in test data and record summaries every 10 steps

for i in range(1000):
    if i % 10 == 0:  # Record summary data and the accuracy
        labels = mnist.test.labels[:, 0:NLABELS]
        feed = {x: mnist.test.images, y_: labels}

        result = sess.run([merged, accuracy, cross_entropy], feed_dict=feed)
        summary_str = result[0]
        acc = result[1]
        loss = result[2]
        writer.add_summary(summary_str, i)
        print('Accuracy at step %s: %s - loss: %f' % (i, acc, loss)) 
   else:
        batch_xs, batch_ys = mnist.train.next_batch(100)
        batch_ys = batch_ys[:, 0:NLABELS]
        feed = {x: batch_xs, y_: batch_ys}
    sess.run(train_step, feed_dict=feed)

我检查了batch_ys(输入y)和_y 的尺寸,当NLABELS=1 时它们都是1xN 矩阵,所以问题似乎在此之前。也许与矩阵乘法有关?

我实际上在一个实际项目中遇到了同样的问题,所以任何帮助将不胜感激......谢谢!

【问题讨论】:

  • 我正在尝试您的网络,但它似乎无法正常工作,您找到可能的解决方案了吗?
  • 我看到您将所有权重初始化为 0。我认为该模型无法正常工作,因为所有内容都乘以零。我会将其更改为 W=tf.get_variable('weights'[in_dim,out_dim],initializer=tf.truncated_normal_initializer())

标签: python neural-network tensorflow


【解决方案1】:

原始 MNIST 示例使用 one-hot encoding 表示数据中的标签:这意味着如果有 NLABELS = 10 类(如在 MNIST 中),则目标输出为 [1 0 0 0 0 0 0 0 0 0] 用于类 0,[0 1 0 0 0 0 0 0 0 0]对于第 1 类等。tf.nn.softmax() 运算符将由 tf.matmul(x, W) + b 计算的 logits 转换为跨不同输出类的概率分布,然后将其与 y_ 的输入值进行比较。

如果NLABELS = 1,这就像只有一个类,tf.nn.softmax() 运算将计算该类的概率为1.0,导致交叉熵为0.0,因为@对于所有示例,987654338@ 是 0.0

您可以尝试(至少)两种方法进行二元分类:

  1. 最简单的方法是为两个可能的类设置NLABELS = 2,并将您的训练数据编码为[1 0] 用于标签0 和[0 1] 用于标签1。This answer 有一个关于如何做到这一点的建议。

  2. 您可以将标签保留为整数01 并使用tf.nn.sparse_softmax_cross_entropy_with_logits(),如this answer 中所建议的那样。

【讨论】:

  • 哦,我明白了这个问题......但现在我想知道,我应该使用交叉熵来解决二进制分类问题吗?这个手动实现了神经网络的家伙没有使用交叉熵来解决他的二进制分类问题:iamtrask.github.io/2015/07/12/basic-python-network
  • 这当然是可能的。你可以有一个单一的输出单元,通过tf.nn.sigmoid() 得到一个介于0 和1 之间的值,然后使用y - y_ 作为损失函数。
  • TensorFlow 不尝试最小化损失函数吗?它必须是一个标量,对吧?我应该做类似sum(abs(y-y_)) 的事情吗?
  • 您可以尝试使用tf.nn.l2_loss() 操作而不是sum(abs(…))
  • 通常对数损失与单个输出单元结合使用是一个不错的选择。对数损失也称为二元交叉熵,因为它是交叉熵的一种特殊情况,仅适用于两个类(查看exegetic.biz/blog/2015/12/making-sense-logarithmic-loss 以获得更详细的解释)。在 Keras 中,您可以使用 binary_crossentropy。在 TensorFlow 中,您可以使用 log_loss。
【解决方案2】:

我一直在寻找如何在 TensorFlow 中以与在 Keras 中完成的方式类似的方式实现二进制分类的好例子。我没有找到任何东西,但是在仔细研究了代码之后,我想我已经弄清楚了。我在这里修改了问题以实现一个使用 sigmoid_cross_entropy_with_logits 的解决方案,就像 Keras 在幕后所做的那样。

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf

# Import data
mnist = input_data.read_data_sets('data', one_hot=True)
NLABELS = 1

sess = tf.InteractiveSession()

# Create the model
x = tf.placeholder(tf.float32, [None, 784], name='x-input')
W = tf.get_variable('weights', [784, NLABELS],
                    initializer=tf.truncated_normal_initializer()) * 0.1
b = tf.Variable(tf.zeros([NLABELS], name='bias'))
logits = tf.matmul(x, W) + b

# Define loss and optimizer
y_ = tf.placeholder(tf.float32, [None, NLABELS], name='y-input')

# More name scopes will clean up the graph representation
with tf.name_scope('cross_entropy'):

    #manual calculation : under the hood math, don't use this it will have gradient problems
    # entropy = tf.multiply(tf.log(tf.sigmoid(logits)), y_) + tf.multiply((1 - y_), tf.log(1 - tf.sigmoid(logits)))
    # loss = -tf.reduce_mean(entropy, name='loss')

    entropy = tf.nn.sigmoid_cross_entropy_with_logits(labels=y_, logits=logits)
    loss = tf.reduce_mean(entropy, name='loss')

with tf.name_scope('train'):
    # Using Adam instead
    # train_step = tf.train.GradientDescentOptimizer(learning_rate=0.001).minimize(loss)
    train_step = tf.train.AdamOptimizer(learning_rate=0.002).minimize(loss)

with tf.name_scope('test'):
    preds = tf.cast((logits > 0.5), tf.float32)
    correct_prediction = tf.equal(preds, y_)
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

tf.initialize_all_variables().run()

# Train the model, and feed in test data and record summaries every 10 steps

for i in range(2000):
    if i % 100 == 0:  # Record summary data and the accuracy
        labels = mnist.test.labels[:, 0:NLABELS]
        feed = {x: mnist.test.images, y_: labels}
        result = sess.run([loss, accuracy], feed_dict=feed)
        print('Accuracy at step %s: %s - loss: %f' % (i, result[1], result[0]))
    else:
        batch_xs, batch_ys = mnist.train.next_batch(100)
        batch_ys = batch_ys[:, 0:NLABELS]
        feed = {x: batch_xs, y_: batch_ys}
    sess.run(train_step, feed_dict=feed)

培训:

Accuracy at step 0: 0.7373 - loss: 0.758670
Accuracy at step 100: 0.9017 - loss: 0.423321
Accuracy at step 200: 0.9031 - loss: 0.322541
Accuracy at step 300: 0.9085 - loss: 0.255705
Accuracy at step 400: 0.9188 - loss: 0.209892
Accuracy at step 500: 0.9308 - loss: 0.178372
Accuracy at step 600: 0.9453 - loss: 0.155927
Accuracy at step 700: 0.9507 - loss: 0.139031
Accuracy at step 800: 0.9556 - loss: 0.125855
Accuracy at step 900: 0.9607 - loss: 0.115340
Accuracy at step 1000: 0.9633 - loss: 0.106709
Accuracy at step 1100: 0.9667 - loss: 0.099286
Accuracy at step 1200: 0.971 - loss: 0.093048
Accuracy at step 1300: 0.9714 - loss: 0.087915
Accuracy at step 1400: 0.9745 - loss: 0.083300
Accuracy at step 1500: 0.9745 - loss: 0.079019
Accuracy at step 1600: 0.9761 - loss: 0.075164
Accuracy at step 1700: 0.9768 - loss: 0.071803
Accuracy at step 1800: 0.9777 - loss: 0.068825
Accuracy at step 1900: 0.9788 - loss: 0.066270

【讨论】:

    猜你喜欢
    • 2021-04-10
    • 1970-01-01
    • 2017-05-30
    • 2017-07-25
    • 2021-06-03
    • 2018-01-09
    • 2020-02-18
    • 2023-03-12
    • 2017-02-10
    相关资源
    最近更新 更多