|
| 1 | +######################################################################## |
| 2 | +# |
| 3 | +# Functions for downloading the CIFAR-10 data-set from the internet |
| 4 | +# and loading it into memory. |
| 5 | +# |
| 6 | +# Implemented in Python 3.5 |
| 7 | +# |
| 8 | +# Usage: |
| 9 | +# 1) Set the variable data_path with the desired storage path. |
| 10 | +# 2) Call maybe_download_and_extract() to download the data-set |
| 11 | +# if it is not already located in the given data_path. |
| 12 | +# 3) Call load_class_names() to get an array of the class-names. |
| 13 | +# 4) Call load_training_data() and load_test_data() to get |
| 14 | +# the images, class-numbers and one-hot encoded class-labels |
| 15 | +# for the training-set and test-set. |
| 16 | +# 5) Use the returned data in your own program. |
| 17 | +# |
| 18 | +# Format: |
| 19 | +# The images for the training- and test-sets are returned as 4-dim numpy |
| 20 | +# arrays each with the shape: [image_number, height, width, channel] |
| 21 | +# where the individual pixels are floats between 0.0 and 1.0. |
| 22 | +# |
| 23 | +######################################################################## |
| 24 | +# |
| 25 | +# This file is part of the TensorFlow Tutorials available at: |
| 26 | +# |
| 27 | +# https://github.com/Hvass-Labs/TensorFlow-Tutorials |
| 28 | +# |
| 29 | +# Published under the MIT License. See the file LICENSE for details. |
| 30 | +# |
| 31 | +# Copyright 2016 by Magnus Erik Hvass Pedersen |
| 32 | +# |
| 33 | +######################################################################## |
| 34 | + |
| 35 | +import numpy as np |
| 36 | +import pickle |
| 37 | +import os |
| 38 | +import download |
| 39 | + |
| 40 | +######################################################################## |
| 41 | + |
| 42 | +# Directory where you want to download and save the data-set. |
| 43 | +# Set this before you start calling any of the functions below. |
| 44 | +data_path = "data/cifar10/" |
| 45 | + |
| 46 | +# URL for the data-set on the internet. |
| 47 | +data_url = "https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz" |
| 48 | + |
| 49 | +######################################################################## |
| 50 | +# Various constants for the size of the images. |
| 51 | +# Use these constants in your own program. |
| 52 | + |
| 53 | +# Width and height of each image. |
| 54 | +img_size = 32 |
| 55 | + |
| 56 | +# Number of channels in each image, 3 channels: Red, Green, Blue. |
| 57 | +num_channels = 3 |
| 58 | + |
| 59 | +# Length of an image when flattened to a 1-dim array. |
| 60 | +img_size_flat = img_size * img_size * num_channels |
| 61 | + |
| 62 | +# Number of classes. |
| 63 | +num_classes = 10 |
| 64 | + |
| 65 | +######################################################################## |
| 66 | +# Various constants used to allocate arrays of the correct size. |
| 67 | + |
| 68 | +# Number of files for the training-set. |
| 69 | +_num_files_train = 1 |
| 70 | + |
| 71 | +# Number of images for each batch-file in the training-set. |
| 72 | +_images_per_file = 10000 |
| 73 | + |
| 74 | +# Total number of images in the training-set. |
| 75 | +# This is used to pre-allocate arrays for efficiency. |
| 76 | +_num_images_train = _num_files_train * _images_per_file |
| 77 | + |
| 78 | +######################################################################## |
| 79 | +# Private functions for downloading, unpacking and loading data-files. |
| 80 | + |
| 81 | + |
| 82 | +def _get_file_path(filename=""): |
| 83 | + """ |
| 84 | + Return the full path of a data-file for the data-set. |
| 85 | +
|
| 86 | + If filename=="" then return the directory of the files. |
| 87 | + """ |
| 88 | + |
| 89 | + return os.path.join(data_path, filename) |
| 90 | + |
| 91 | + |
| 92 | +def one_hot_encoded(class_numbers, num_classes=None): |
| 93 | + """ |
| 94 | + Generate the One-Hot encoded class-labels from an array of integers. |
| 95 | +
|
| 96 | + For example, if class_number=2 and num_classes=4 then |
| 97 | + the one-hot encoded label is the float array: [0. 0. 1. 0.] |
| 98 | +
|
| 99 | + :param class_numbers: |
| 100 | + Array of integers with class-numbers. |
| 101 | + Assume the integers are from zero to num_classes-1 inclusive. |
| 102 | +
|
| 103 | + :param num_classes: |
| 104 | + Number of classes. If None then use max(cls)-1. |
| 105 | +
|
| 106 | + :return: |
| 107 | + 2-dim array of shape: [len(cls), num_classes] |
| 108 | + """ |
| 109 | + |
| 110 | + # Find the number of classes if None is provided. |
| 111 | + if num_classes is None: |
| 112 | + num_classes = np.max(class_numbers) - 1 |
| 113 | + |
| 114 | + return np.eye(num_classes, dtype=float)[class_numbers] |
| 115 | + |
| 116 | + |
| 117 | +def _unpickle(filename): |
| 118 | + """ |
| 119 | + Unpickle the given file and return the data. |
| 120 | +
|
| 121 | + Note that the appropriate dir-name is prepended the filename. |
| 122 | + """ |
| 123 | + |
| 124 | + # Create full path for the file. |
| 125 | + file_path = _get_file_path(filename) |
| 126 | + |
| 127 | + print("Loading data: " + file_path) |
| 128 | + |
| 129 | + with open(file_path, mode='rb') as file: |
| 130 | + # In Python 3.X it is important to set the encoding, |
| 131 | + # otherwise an exception is raised here. |
| 132 | + data = pickle.load(file) |
| 133 | + |
| 134 | + return data |
| 135 | + |
| 136 | + |
| 137 | +def _convert_images(raw): |
| 138 | + """ |
| 139 | + Convert images from the CIFAR-10 format and |
| 140 | + return a 4-dim array with shape: [image_number, height, width, channel] |
| 141 | + where the pixels are floats between 0.0 and 1.0. |
| 142 | + """ |
| 143 | + |
| 144 | + # Convert the raw images from the data-files to floating-points. |
| 145 | + raw_float = np.array(raw, dtype=float) / 255.0 |
| 146 | + |
| 147 | + # Reshape the array to 4-dimensions. |
| 148 | + images = raw_float.reshape([-1, num_channels, img_size, img_size]) |
| 149 | + |
| 150 | + # Reorder the indices of the array. |
| 151 | + images = images.transpose([0, 2, 3, 1]) |
| 152 | + |
| 153 | + return images |
| 154 | + |
| 155 | + |
| 156 | +def _load_data(filename): |
| 157 | + """ |
| 158 | + Load a pickled data-file from the CIFAR-10 data-set |
| 159 | + and return the converted images (see above) and the class-number |
| 160 | + for each image. |
| 161 | + """ |
| 162 | + |
| 163 | + # Load the pickled data-file. |
| 164 | + data = _unpickle(filename) |
| 165 | + |
| 166 | + # Get the raw images. |
| 167 | + raw_images = data[b'data'] |
| 168 | + |
| 169 | + # Get the class-numbers for each image. Convert to numpy-array. |
| 170 | + cls = np.array(data[b'labels']) |
| 171 | + |
| 172 | + # Convert the images. |
| 173 | + images = _convert_images(raw_images) |
| 174 | + |
| 175 | + return images, cls |
| 176 | + |
| 177 | + |
| 178 | +######################################################################## |
| 179 | +# Public functions that you may call to download the data-set from |
| 180 | +# the internet and load the data into memory. |
| 181 | + |
| 182 | + |
| 183 | +def maybe_download_and_extract(): |
| 184 | + """ |
| 185 | + Download and extract the CIFAR-10 data-set if it doesn't already exist |
| 186 | + in data_path (set this variable first to the desired path). |
| 187 | + """ |
| 188 | + |
| 189 | + download.maybe_download_and_extract(url=data_url, download_dir=data_path) |
| 190 | + |
| 191 | + |
| 192 | +def load_class_names(): |
| 193 | + """ |
| 194 | + Load the names for the classes in the CIFAR-10 data-set. |
| 195 | +
|
| 196 | + Returns a list with the names. Example: names[3] is the name |
| 197 | + associated with class-number 3. |
| 198 | + """ |
| 199 | + |
| 200 | + # Load the class-names from the pickled file. |
| 201 | + raw = _unpickle(filename="batches.meta")[b'label_names'] |
| 202 | + |
| 203 | + # Convert from binary strings. |
| 204 | + names = [x.decode('utf-8') for x in raw] |
| 205 | + |
| 206 | + return names |
| 207 | + |
| 208 | + |
| 209 | +def load_training_data(): |
| 210 | + """ |
| 211 | + Load all the training-data for the CIFAR-10 data-set. |
| 212 | +
|
| 213 | + The data-set is split into 5 data-files which are merged here. |
| 214 | +
|
| 215 | + Returns the images, class-numbers and one-hot encoded class-labels. |
| 216 | + """ |
| 217 | + |
| 218 | + # Pre-allocate the arrays for the images and class-numbers for efficiency. |
| 219 | + images = np.zeros(shape=[_num_images_train, img_size, img_size, num_channels], dtype=float) |
| 220 | + cls = np.zeros(shape=[_num_images_train], dtype=int) |
| 221 | + |
| 222 | + # Begin-index for the current batch. |
| 223 | + begin = 0 |
| 224 | + |
| 225 | + # For each data-file. |
| 226 | + for i in range(_num_files_train): |
| 227 | + # Load the images and class-numbers from the data-file. |
| 228 | + images_batch, cls_batch = _load_data(filename="data_batch_" + str(i + 1)) |
| 229 | + |
| 230 | + # Number of images in this batch. |
| 231 | + num_images = len(images_batch) |
| 232 | + |
| 233 | + # End-index for the current batch. |
| 234 | + end = begin + num_images |
| 235 | + |
| 236 | + # Store the images into the array. |
| 237 | + images[begin:end, :] = images_batch |
| 238 | + |
| 239 | + # Store the class-numbers into the array. |
| 240 | + cls[begin:end] = cls_batch |
| 241 | + |
| 242 | + # The begin-index for the next batch is the current end-index. |
| 243 | + begin = end |
| 244 | + |
| 245 | + return images, cls, one_hot_encoded(class_numbers=cls, num_classes=num_classes) |
| 246 | + |
| 247 | + |
| 248 | +def load_test_data(): |
| 249 | + """ |
| 250 | + Load all the test-data for the CIFAR-10 data-set. |
| 251 | +
|
| 252 | + Returns the images, class-numbers and one-hot encoded class-labels. |
| 253 | + """ |
| 254 | + |
| 255 | + images, cls = _load_data(filename="test_batch") |
| 256 | + |
| 257 | + return images, cls, one_hot_encoded(class_numbers=cls, num_classes=num_classes) |
| 258 | + |
| 259 | +######################################################################## |
0 commit comments