过滤数据集以仅获取来自特定类的图像

jan*_*lle 7 python dataset keras tensorflow

我想为 n-shot 学习准备 omniglot 数据集。因此我需要来自 10 个类别(字母表)的 5 个样本

重现代码

import tensorflow as tf
import tensorflow_datasets as tfds
import numpy as np

builder = tfds.builder("omniglot")
# assert builder.info.splits['train'].num_examples == 60000
builder.download_and_prepare()
# Load data from disk as tf.data.Datasets
datasets = builder.as_dataset()
dataset, test_dataset = datasets['train'], datasets['test']


def resize(example):
    image = example['image']
    image = tf.image.resize(image, [28, 28])
    image = tf.image.rgb_to_grayscale(image, )
    image = image / 255
    one_hot_label = np.zeros((51, 10))
    return image, one_hot_label, example['alphabet']


def stack(image, label, alphabet):
    return (image, label), label[-1]

def filter_func(image, label, alphabet):
    # get just images from alphabet in array, not just 2
    arr = np.array(2,3,4,5)
    result = tf.reshape(tf.equal(alphabet, 2 ), [])
    return result

# correct size
dataset = dataset.map(resize)
# now filter the dataset for the batch
dataset = dataset.filter(filter_func)
# infinite stream of batches (classes*samples + 1)
dataset = dataset.repeat().shuffle(1024).batch(51)
# stack the images together
dataset = dataset.map(stack)
dataset = dataset.shuffle(buffer_size=1000)
dataset = dataset.batch(32)

for i, (image, label) in enumerate(tfds.as_numpy(dataset)):
    print(i, image[0].shape)
Run Code Online (Sandbox Code Playgroud)

现在我想使用 filter 函数过滤数据集中的图像。tf.equal 只是让我按一类过滤,我想要数组中的张量之类的东西。

你看到一种用过滤器功能来做到这一点的方法吗?或者这是错误的方法,还有更简单的方法?

我想创建一批 51 张图像和相应的标签,它们来自相同的 N=10 类。对于每个班级,我需要 K=5 个不同的图像和一个额外的图像(我需要对其进行分类)。每批 N*K+1 (51) 张图像应该来自 10 个新的随机类别。

非常感谢您提前。

Vla*_*lad 8

要仅保留特定标签,请使用此谓词:

dataset = datasets['train']

def predicate(x, allowed_labels=tf.constant([0, 1, 2])):
    label = x['label']
    isallowed = tf.equal(allowed_labels, tf.cast(label, allowed_labels.dtype))
    reduced = tf.reduce_sum(tf.cast(isallowed, tf.float32))
    return tf.greater(reduced, tf.constant(0.))

dataset = dataset.filter(predicate).batch(20)

for i, x in enumerate(tfds.as_numpy(dataset)):
    print(x['label'])
# [1 0 0 1 2 1 1 2 1 0 0 1 2 0 1 0 2 2 0 1]
# [1 0 2 2 0 2 1 2 1 2 2 2 0 2 0 2 1 2 1 1]
# [2 1 2 1 0 1 1 0 1 2 2 0 2 0 1 0 0 0 0 0]
Run Code Online (Sandbox Code Playgroud)

allowed_labels指定要保留的标签。所有不在此张量中的标签都将被过滤掉。