Skip to content

Instantly share code, notes, and snippets.

@georgebyte
Last active July 31, 2019 13:46
Show Gist options
  • Save georgebyte/5157650 to your computer and use it in GitHub Desktop.
Save georgebyte/5157650 to your computer and use it in GitHub Desktop.
Python: Mnist Reader
def get_data_and_labels(images_filename, labels_filename):
print("Opening files ...")
images_file = open(images_filename, "rb")
labels_file = open(labels_filename, "rb")
try:
print("Reading files ...")
images_file.read(4)
num_of_items = int.from_bytes(images_file.read(4), byteorder="big")
num_of_rows = int.from_bytes(images_file.read(4), byteorder="big")
num_of_colums = int.from_bytes(images_file.read(4), byteorder="big")
labels_file.read(8)
num_of_image_values = num_of_rows * num_of_colums
data = [[None for x in range(num_of_image_values)]
for y in range(num_of_items)]
labels = []
for item in range(num_of_items):
print("Current image number: %7d" % item)
for value in range(num_of_image_values):
data[item][value] = int.from_bytes(images_file.read(1),
byteorder="big")
labels.append(int.from_bytes(labels_file.read(1), byteorder="big"))
return data, labels
finally:
images_file.close()
labels_file.close()
print("Files closed.")
images_filename = "location/of/images/file"
labels_filename = "location/of/labels/file"
data, labels = get_data_and_labels(images_filename, labels_filename)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment