【发布时间】:2017-03-17 03:22:13
【问题描述】:
models/inception/inception/image_processing.py
>我是 tersorflow 的初学者。我正在使用以 TF-Slim 表示的 Inception-V3 的实现,使用不同的数据集从头开始训练。我正在尝试解决 5 个类的问题,并且数据集完全不平衡。第一个类的数据比其他 4 个类的总和多。损失没有下降,正如预期的那样,不幸的是所有图像都被归类为“1”。
我部分了解 tensorflow 的工作原理,但现在面临一个问题,不知道如何解决。我们如何构建按类平衡的批次?我相信,最简单的方法是在数据增强的同时解决类平衡问题。这包括应用过采样,复制不太受欢迎的类别的图像(在扭曲它们之前)以平衡人口最多的类别。但我不想手动执行此操作(这会占用磁盘中的大量额外空间),我更喜欢动态执行。
为简洁起见,假设我们分别有 2000 张图片、500 张图片和 100 张图片用于第 1、2 和 3 类。为了平衡类,我们将重复类 2 中的每个数据(3 个副本)和类 3(19 个副本)。复制(或重复)将在应用图像失真之前完成。
数据采用原生 TFRecord 格式。有人可以帮我解决这个问题吗?
代码:https://github.com/tensorflow/models/blob/master/inception/inception/image_processing.py
更新:
感谢其他两个类似的线程(Online oversampling in Tensorflow input pipeline 和How to duplicate input tensors conditional on a tensor attribute ("oversampling") in a Tensorflow queue?),我有了解决问题的方法。
和@citrusvanilla 一样,我尝试使用tf.case(),但没有成功。 tf.cond() 就够了。就我而言,我需要对图像的每个版本应用一些随机扰动。我不知道这是否是最合适的选择,但我正在使用tf.map_fn() 来解决这个问题。
`# Example for three classes (class 0 is not used)
def oversample_by_cond(images, label):
# Oversampling factors per class
OVERSAMPLE_FACTOR = [1, 1, 4]
# Set up the predicates
pred0 = tf.reshape(tf.equal(label, tf.convert_to_tensor([0])), [])
pred1 = tf.reshape(tf.equal(label, tf.convert_to_tensor([1])), [])
pred2 = tf.reshape(tf.equal(label, tf.convert_to_tensor([2])), [])
# Callables functions
def f0(): return tf.concat([images]*OVERSAMPLE_FACTOR[0], 0), tf.concat([label]*OVERSAMPLE_FACTOR[0], 0)
def f1(): return tf.concat([images]*OVERSAMPLE_FACTOR[1], 0), tf.concat([label]*OVERSAMPLE_FACTOR[1], 0)
def f2(): return tf.concat([images]*OVERSAMPLE_FACTOR[2], 0), tf.concat([label]*OVERSAMPLE_FACTOR[2], 0)
# Exclusive conditionals (one for each class)
[images, label] = tf.cond(pred0, f0, lambda: [images,label])
[images, label] = tf.cond(pred1, f1, lambda: [images,label])
[images, label] = tf.cond(pred2, f2, lambda: [images,label])
return [images, label]
images = tf.expand_dims(image_decoded, 0)
if train:
# Oversample the train set in order to balance the classes
[images, labels] = oversample_by_cond(images, label_index)
# Distort all the concatenated version of the training image
thread_id = itertools.cycle(range(num_preprocess_threads))
images = tf.map_fn(lambda img: image_preprocessing(img, bbox, train,
next(thread_id), summariesFlag=False), images)
images_and_labels = [images, labels]
else:
# validation/test set
image = image_preprocessing(image_decoded, bbox, train, thread_id)
images_and_labels = [tf.expand_dims(image, 0), label_index]`
【问题讨论】:
标签: tensorflow