복붙노트

[PYTHON] 이진 분류 용 TensorFlow

PYTHON

이진 분류 용 TensorFlow

이 바이너리 분류에이 MNIST 예제를 적용하려고한다.

그러나 NLABELS = 2에서 NLABELS = 1으로 NLABELS를 변경하면 손실 함수는 항상 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 행렬이므로 문제가 그 이전 인 것 같습니다. 아마 행렬 곱셈과 관련이 있을까요?

실제로 실제 프로젝트에서 이와 동일한 문제가 발생 했으므로 도움을 받으실 수 있습니다 ... 감사합니다!

해결법

  1. ==============================

    1.원래 MNIST 예제는 데이터의 레이블을 나타 내기 위해 one-hot 인코딩을 사용합니다. 즉, NLABELS = 10 클래스가있는 경우 (MNIST에서와 같이) 대상 출력은 [1 0 0 0 0 0 0 0 0 0] tf.nn.softmax () 연산자는 tf.matmul (x, W) + b에 의해 계산 된 로짓을 확률 분포로 변환하고 클래스 0에 대해서는 [0 1 0 0 0 0 0 0 0] 다른 출력 클래스를 가로 질러 y_에 대한 fed-in 값과 비교된다.

    원래 MNIST 예제는 데이터의 레이블을 나타 내기 위해 one-hot 인코딩을 사용합니다. 즉, NLABELS = 10 클래스가있는 경우 (MNIST에서와 같이) 대상 출력은 [1 0 0 0 0 0 0 0 0 0] tf.nn.softmax () 연산자는 tf.matmul (x, W) + b에 의해 계산 된 로짓을 확률 분포로 변환하고 클래스 0에 대해서는 [0 1 0 0 0 0 0 0 0] 다른 출력 클래스를 가로 질러 y_에 대한 fed-in 값과 비교된다.

    NLABELS = 1 인 경우 이것은 하나의 클래스 만있는 것처럼 작동하며 tf.nn.softmax () op는 해당 클래스에 대해 1.0의 확률을 계산하여 교차 엔트로피가 0.0이되도록합니다. tf.log ( 1.0)은 모든 예제에서 0.0입니다.

    바이너리 분류를 위해 시도 할 수있는 두 가지 방법이있다.

  2. from https://stackoverflow.com/questions/35277898/tensorflow-for-binary-classification by cc-by-sa and MIT license