【问题标题】:How to exclude a class from MNIST in TensorFlow?如何从 TensorFlow 中的 MNIST 中排除一个类?
【发布时间】:2018-01-05 16:27:50
【问题描述】:

我是 TensorFlow 的新手,我正在学习 MNIST 数据集的初学者教程,我想只用 0-8(不包括类 9)来训练模型,所以代码中的 10,我替换了它到 9,但是在代码的训练部分,如何要求 next_batch() 排除第 9 类?如果我想排除多个类?

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

import argparse
import sys

from tensorflow.examples.tutorials.mnist import input_data

import tensorflow as tf

FLAGS = None

def main(_):
  # Import data
  mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)

  # Create the model
  x = tf.placeholder(tf.float32, [None, 784])
  W = tf.Variable(tf.zeros([784, 9]))  # was 10 instead of 9 
  b = tf.Variable(tf.zeros([9]))      # was 10 instead of 9
  y = tf.matmul(x, W) + b

  # Define loss and optimizer
  y_ = tf.placeholder(tf.float32, [None, 9]) # was 10 instead of 9

  cross_entropy = tf.reduce_mean(
      tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))
  train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

  sess = tf.InteractiveSession()
  tf.global_variables_initializer().run()
  # Train
  for _ in range(1000):
    batch_xs, batch_ys = mnist.train.next_batch(100)    # How to exclude the class 9 ?
    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})

  # Test trained model
  correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
  accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
  print(sess.run(accuracy, feed_dict={x: mnist.test.images,
                                      y_: mnist.test.labels}))

if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.add_argument('--data_dir', type=str, default='/tmp/tensorflow/mnist/input_data',
                      help='Directory for storing input data')
  FLAGS, unparsed = parser.parse_known_args()
  tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)

【问题讨论】:

    标签: python tensorflow machine-learning neural-network mnist


    【解决方案1】:

    您应该从 mnist 数据对象中提取训练数据,删除您想要的类,然后继续。首先获取其中没有类9的数据集:

    Xdata_no9 = np.array([x for (x,y) in zip(mnist.train.images,mnist.train.labels) if y[9]==0])
    ydata_no9 = np.array([y[0:9] for y in mnist.train.labels if y[9]==0])
    

    请注意,y[0:9] 将大小从 10 减小到 9。这样就可以了,但是现在您需要构建自己的代码来提取小批量。这是一个简单的方法:

    n = Xdata_no9.shape[0]
    batch_size = 100
    batch = np.floor(np.random.rand(batch_size)*n).astype(int)
    batch_xs = Xdata_no10[batch,:]
    batch_ys = ydata_no10[batch,:]
    

    请注意,您可以稍微压缩此代码,但我将其编写为具有指导意义。

    注意事项:这样做(从训练集中删除类)是更好的做法:如果您不想对部分数据进行训练,则应将其从数据集中删除在早期,而不是要求每次调用该数据都记住应该忽略数据的哪一部分。在此示例中,这并不重要,因为您只在训练中使用它,但如果您尝试评估整个训练集的性能,这当然会中断(除非您记得再次忽略该类)。

    【讨论】:

      【解决方案2】:

      这行应该在你得到batch_xsbatch_ys 之后立即执行:

      batch_xs, batch_ys = zip(*[(x_, y_[:-1]) for x_, y_ in zip(batch_xs, batch_ys) if np.argmax(y_) not in [9]])
      

      【讨论】:

      • 但输出将继续为 10 个值,而不是所需的 9 个。
      • 啊,不错。需要在那里挤压y_。应该是y_[:-1](两个类为-2,等等)
      • 好的,但是如果我想排除 7 类,y_[:-1] 将删除 9
      • 如果你打算这样走,你应该序号编码,而不是单热。这将简化一切
      猜你喜欢
      • 2019-07-03
      • 2018-10-29
      • 2017-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多