open mnist base in matlab in matlab

To open the MNIST dataset in MATLAB, you need to download the files from the MNIST website first. Once downloaded, you can read the data files using the following code:

main.m
function [images, labels] = readMNIST(filenameImages, filenameLabels)

% Open files
fidImages = fopen(filenameImages, 'r', 'b');
fidLabels = fopen(filenameLabels, 'r', 'b');

% Read headers
magicNumberImages = fread(fidImages, 1, 'int32', 0, 'b');
numImages = fread(fidImages, 1, 'int32', 0, 'b');
numRows = fread(fidImages, 1, 'int32', 0, 'b');
numCols = fread(fidImages, 1, 'int32', 0, 'b');

magicNumberLabels = fread(fidLabels, 1, 'int32', 0, 'b');
numLabels = fread(fidLabels, 1, 'int32', 0, 'b');

% Read images and labels
images = fread(fidImages, inf, 'unsigned char');
images = reshape(images, numCols, numRows, numImages);
images = permute(images,[2 1 3]);

labels = fread(fidLabels, inf, 'unsigned char');

% Close files
fclose(fidImages);
fclose(fidLabels);
end
774 chars
27 lines

To use this function, simply call it with the filenames of the data files:

main.m
[images, labels] = readMNIST('train-images.idx3-ubyte', 'train-labels.idx1-ubyte');
84 chars
2 lines

This will return two arrays:

  • images - a 3D array with dimensions [numCols, numRows, numImages] containing the raw image data.
  • labels - a 1D array containing the corresponding labels for each image.

related categories

gistlibby LogSnag