Преобразовать набор данных Omniglot Tensorflow в пользовательский массив Numpy: ['label', 'images'] - PullRequest
1 голос
/ 20 апреля 2020

Я читаю книгу "Практическое мета-обучение с Python" и пытаюсь протестировать обучение прототипов с использованием набора данных Omniglot Tensorflow.

Это мой код для загрузки этого набора данных:

import tensorflow_datasets as tfds

omniglot_builder = tfds.builder("omniglot")
omniglot_builder.download_and_prepare()

info = omniglot_builder.info
print(info.features)
print(info.features["label"].num_classes)
print(info.features["label"].names)

omni_train = omniglot_builder.as_dataset(split="train")

В книге они читают изображения со своего жесткого диска. И они делают это, чтобы загрузить все изображения в массив numpy:

root_dir = 'data/'

# We have the splitting details in the /data/omniglot/splits/train.txt file which has the
# language name, character number, rotation information and images in /data/omniglot/data/
# directory.

train_split_path = os.path.join(root_dir, 'splits', 'train.txt')

with open(train_split_path, 'r') as train_split:
    train_classes = [line.rstrip() for line in train_split.readlines()]

#number of classes
no_of_classes = len(train_classes)

# Now we set the number of examples to 20, as we have 20 example per class in our dataset,
# and also we set image width and height to 28 x 28:


#number of examples
num_examples = 20

#image width
img_width = 28

#image height
img_height = 28
channels = 1

# Next, we initialize our training dataset with a shape as a number of classes, number of
# examples, image height and image width:

train_dataset = np.zeros([no_of_classes, num_examples, img_height, img_width], dtype=np.float32)

# Now, we read all the images, convert it to numpy array and store it our train_dataset array
# with their label and values, that is, train_dataset = [label, values]:


for label, name in enumerate(train_classes):
    alphabet, character, rotation = name.split('/')
    rotation = float(rotation[3:])
    img_dir = os.path.join(root_dir, 'data', alphabet, character)
    img_files = sorted(glob.glob(os.path.join(img_dir, '*.png')))


    for index, img_file in enumerate(img_files):
        values = 1. - np.array(Image.open(img_file).rotate(rotation).resize((img_width, img_height)), np.float32, copy=False)
        train_dataset[label, index] = values


train_dataset.shape

Out[14]: (4112, 20, 28, 28)

Моя проблема в том, что я не знаю, как создать массив Numpy, подобный этому: train_dataset = [label, values]

Есть ли в любом случае итерация omni_train для создания массива Numpy, например train_dataset = [label, values]?

1 Ответ

0 голосов
/ 05 мая 2020

Вы можете использовать take(), где take(-1) будет перебирать все обучающие примеры в omni_train, вы можете получить метку и значение с помощью приведенного ниже кода, а затем добавить его для обучения массива данных Numpy.

train_dataset = []

for index, example in enumerate(omni_train.take(-1)):
  image, label = example["image"], example["label"]
  lab = label.numpy()
  val = 1. - np.array(Image.fromarray(image.numpy()[:, :, 0]/255).resize((28,28)))
  train_dataset.append([lab, val])

train_dataset = np.array(train_dataset)
...