Skip to content

Instantly share code, notes, and snippets.

@volf52
Forked from tylerneylon/mnist.py
Created April 8, 2020 22:46
Show Gist options
  • Save volf52/e7af5405cf10fc6337f3eaf6ff185a8a to your computer and use it in GitHub Desktop.
Save volf52/e7af5405cf10fc6337f3eaf6ff185a8a to your computer and use it in GitHub Desktop.
A function to load numpy arrays from the MNIST data files.
""" A function that can read MNIST's idx file format into numpy arrays.
The MNIST data files can be downloaded from here:
http://yann.lecun.com/exdb/mnist/
This relies on the fact that the MNIST dataset consistently uses
unsigned char types with their data segments.
"""
import struct
import numpy as np
def read_idx(filename):
with open(filename, 'rb') as f:
zero, data_type, dims = struct.unpack('>HBB', f.read(4))
shape = tuple(struct.unpack('>I', f.read(4))[0] for d in range(dims))
return np.fromstring(f.read(), dtype=np.uint8).reshape(shape)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment