2016-12-06 2 views
1

다음은 MNIST data files을 읽는 전용 함수입니다.MATLAB/Ocatave 파일 읽기 이해

function [tlab, tvec] = readmnist(datafn, labelfn) 
% function reads mnist data and labels 

fid = fopen(datafn, 'rb'); 
//open datafn in read and big-endian format. 
//returns a file-id 
if fid==-1 
    error('Error opening data file'); 
end; 

fseek(fid, 0, 'eof'); 
// Seek to the 0th byte from the end of the file. 
// In other words. Just go to the end of the file. 
// fid == the file to be accessed. 
// 'eof' == relative position. 
// 0 == bytes to be read. 

cnt = (ftell(fid) - 16)/784; 

fseek(fid, 16, 'bof'); 
//Move to the 16th byte from the beginning of file. 
tvec = zeros(cnt, 784); 
//returns a 2D cntx784 matrix of zeros. 

for i=1:cnt 
    im = fread(fid, 784, 'uchar'); 
    tvec(i,:) = (im(:)/255.0)'; 
end; 
fclose(fid); 
cnt 

fid = fopen(labelfn, 'rb'); 
if fid==-1 
    error('Error opening label file'); 
end; 
fseek(fid, 8, 'bof'); 
[tlab nel] = fread(fid, cnt, 'uchar'); 
if nel ~= cnt 
    disp('Not all elements read.'); 
end; 
fclose(fid); 
nel 

캐치 란 무엇입니까? 다음 줄을 알려주십시오.

cnt = (ftell(fid) - 16)/784; 

여기 무슨 일이 일어나고 있습니까? 784 란 무엇입니까?

답변

3

코드에 따르면 cnt x 784이고, cnt은 알려져 있지 않습니다. 코드에 따르면 tvec (파일에서 데이터를 읽을 때)입니다. 붙여 넣은 선은 cnt으로 해결됩니다.

파일 포인터가 파일 끝을 가리 키기 때문에 ftell(fid)은 파일의 현재 위치를 알려주며이 경우 파일의 총 바이트 수에 해당합니다. 16 바이트는 분명히 관심 데이터의 일부가 아니기 때문에 16을 뺍니다. 이제 우리는 cnt * 784 = ftell(fid) - 16을 알고 있으므로 cnt을 풀기 위해 784으로 나누면됩니다.

다음 줄은 파일 포인터를 다시 17 번째 바이트 (데이터의 시작 부분)로 이동 한 다음 1:cnt을 반복하여 fread으로 각 784 바이트 조각을 읽습니다.