Я пытаюсь выполнить код, приведенный в ссылкеКак загрузить в MNIST цифры и данные метки в MATLAB?
https://github.com/bd622/DiscretHashing
Discrete Hashing является методом снижения размерности, который используется на приближенном ближайший поиске соседа. Я хочу загрузить в реализацию в базе данных MNIST, которая доступна в http://yann.lecun.com/exdb/mnist/. Я извлек файлы из их сжатого формата gz.
ПРОБЛЕМА 1:
Используя решение для чтения базы данных MNIST представлены в Reading MNIST Image Database binary file in MATLAB
Я получаю следующее сообщение об ошибке:
Error using fread
Invalid file identifier. Use fopen to generate a valid file identifier.
Error in Reading (line 7)
A = fread(fid, 1, 'uint32');
Вот код:
clear all;
close all;
%//Open file
fid = fopen('t10k-images-idx3-ubyte', 'r');
A = fread(fid, 1, 'uint32');
magicNumber = swapbytes(uint32(A));
%//For each image, store into an individual cell
imageCellArray = cell(1, totalImages);
for k = 1 : totalImages
%//Read in numRows*numCols pixels at a time
A = fread(fid, numRows*numCols, 'uint8');
%//Reshape so that it becomes a matrix
%//We are actually reading this in column major format
%//so we need to transpose this at the end
imageCellArray{k} = reshape(uint8(A), numCols, numRows)';
end
%//Close the file
fclose(fid);
UPDATE: Задача 1 решена и пересмотренный код
clear all;
close all;
%//Open file
fid = fopen('t10k-images.idx3-ubyte', 'r');
A = fread(fid, 1, 'uint32');
magicNumber = swapbytes(uint32(A));
%//Read in total number of images
%//A = fread(fid, 4, 'uint8');
%//totalImages = sum(bitshift(A', [24 16 8 0]));
%//OR
A = fread(fid, 1, 'uint32');
totalImages = swapbytes(uint32(A));
%//Read in number of rows
%//A = fread(fid, 4, 'uint8');
%//numRows = sum(bitshift(A', [24 16 8 0]));
%//OR
A = fread(fid, 1, 'uint32');
numRows = swapbytes(uint32(A));
%//Read in number of columns
%//A = fread(fid, 4, 'uint8');
%//numCols = sum(bitshift(A', [24 16 8 0]));
%// OR
A = fread(fid, 1, 'uint32');
numCols = swapbytes(uint32(A));
for k = 1 : totalImages
%//Read in numRows*numCols pixels at a time
A = fread(fid, numRows*numCols, 'uint8');
%//Reshape so that it becomes a matrix
%//We are actually reading this in column major format
%//so we need to transpose this at the end
imageCellArray{k} = reshape(uint8(A), numCols, numRows)';
end
%//Close the file
fclose(fid);
ПРОБЛЕМА 2:
Я не могу понять, как применить 4 файлов MNIST в коде. Код содержит переменные
traindata = double(traindata);
testdata = double(testdata);
Как подготовить базу данных MNIST, чтобы я мог применить к реализации?
UPDATE: Я реализовал решение, но я получаю эту ошибку
Error using fread
Invalid file identifier. Use fopen to generate a valid file identifier.
Error in mnist_parse (line 11)
A = fread(fid1, 1, 'uint32');
Эти файлы
demo.m
% это главный файл, который вызывает функцию для чтения в данных MNIST
clear all
clc
[Trainimages, Trainlabels] = mnist_parse('C:\Users\Desktop\MNIST\train-images-idx3-ubyte', 'C:\Users\Desktop\MNIST\train-labels-idx1-ubyte');
[Testimages, Testlabels] = mnist_parse('t10k-images-idx3-ubyte', 't10k-labels-idx1-ubyte');
k=5;
digit = images(:,:,k);
lbl = label(k);
function [images, labels] = mnist_parse(path_to_digits, path_to_labels)
% Open files
fid1 = fopen(path_to_digits, 'r');
% The labels file
fid2 = fopen(path_to_labels, 'r');
% Read in magic numbers for both files
A = fread(fid1, 1, 'uint32');
magicNumber1 = swapbytes(uint32(A)); % Should be 2051
fprintf('Magic Number - Images: %d\n', magicNumber1);
A = fread(fid2, 1, 'uint32');
magicNumber2 = swapbytes(uint32(A)); % Should be 2049
fprintf('Magic Number - Labels: %d\n', magicNumber2);
% Read in total number of images
% Ensure that this number matches with the labels file
A = fread(fid1, 1, 'uint32');
totalImages = swapbytes(uint32(A));
A = fread(fid2, 1, 'uint32');
if totalImages ~= swapbytes(uint32(A))
error('Total number of images read from images and labels files are not the same');
end
fprintf('Total number of images: %d\n', totalImages);
% Read in number of rows
A = fread(fid1, 1, 'uint32');
numRows = swapbytes(uint32(A));
% Read in number of columns
A = fread(fid1, 1, 'uint32');
numCols = swapbytes(uint32(A));
fprintf('Dimensions of each digit: %d x %d\n', numRows, numCols);
% For each image, store into an individual slice
images = zeros(numRows, numCols, totalImages, 'uint8');
for k = 1 : totalImages
% Read in numRows*numCols pixels at a time
A = fread(fid1, numRows*numCols, 'uint8');
% Reshape so that it becomes a matrix
% We are actually reading this in column major format
% so we need to transpose this at the end
images(:,:,k) = reshape(uint8(A), numCols, numRows).';
end
% Read in the labels
labels = fread(fid2, totalImages, 'uint8');
% Close the files
fclose(fid1);
fclose(fid2);
end
Ошибка довольно понятная, вы использовали 'fopen' для недопустимого имени файла. Убедитесь, что 't10k-images-idx3-ubyte'' является * полным * именем файла и находится в вашем текущем пути MATLAB. В противном случае убедитесь, что это полный * полный путь к файлу, который вы хотите открыть. – excaza
@excaza: решена первая проблема и ошибка из-за операции чтения файлов. В названии файла действительно была проблема. Но теперь я понятия не имею, как использовать базу данных, я не понимаю, как использовать эти 4 файла. Я считаю, что переменная traindata будет содержать файл train-images.idx3-ubyte. Тогда какой из них будет testdata, а затем, как я должен использовать файлы базы данных с двумя метками? Пожалуйста, помогите – SKM
@rayryeng: Не могли бы вы сообщить мне, почему я получаю сообщение об ошибке из-за операции чтения файлов, когда я выполнил ваш ответ? Я включил новые обновления в вопрос. Спасибо за ваше время и силы. – SKM