code: #!/usr/bin/python
  # -*- coding: utf-8 -*-
  
  """
  This module contains a method to load mnist data. Based on  David Larson work at:
  http://g.sweyla.com/blog/2012/mnist-numpy/a
  """
  
  import numpy
  import os, struct
  from array import array as pyarray
  
  
  def load_mnist(dataset="training", digits=numpy.arange(10), path="mnist"):
      """
      The Mnist loading methods from David Larson. Can be checked out at: http://g.sweyla.com/blog/2012/mnist-numpy/a
  
      :param dataset: 'training' or 'testing' depending on the files to load.
      :param digits: digits to load
      :param path: path to the mnist directory
      :return: X, y: data and labels
      """
  
      if dataset == "training":
          fname_img = os.path.join(path, 'train-images.idx3-ubyte')
          fname_lbl = os.path.join(path, 'train-labels.idx1-ubyte')
      elif dataset == "testing":
          fname_img = os.path.join(path, 't10k-images.idx3-ubyte')
          fname_lbl = os.path.join(path, 't10k-labels.idx1-ubyte')
      else:
          raise ValueError("dataset must be 'testing' or 'training'")
  
      flbl = open(fname_lbl, 'rb')
      magic_nr, size = struct.unpack(">II", flbl.read(8))
      lbl = pyarray("b", flbl.read())
      flbl.close()
  
      fimg = open(fname_img, 'rb')
      magic_nr, size, rows, cols = struct.unpack(">IIII", fimg.read(16))
      img = pyarray("B", fimg.read())
      fimg.close()
  
      ind = [ k for k in range(size) if lbl[k] in digits ]
      N = len(ind)
  
      images = numpy.zeros((N, rows, cols), dtype=numpy.uint8)
      labels = numpy.zeros((N, 1), dtype=numpy.int8)
      for i in range(len(ind)):
          images[i] = numpy.array(img[ ind[i]*rows*cols : (ind[i]+1)*rows*cols ]).reshape((rows, cols))
          labels[i] = lbl[ind[i]]
  
      return images, labels
  
apis: numpy.arange numpy.array numpy.zeros