2016-12-06 6 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

コードによれば、tvec(ファイルから読み込まれるデータ)は、cnt x 784であり、cntは不明です。貼り付けた線は、cntを解決します。

ファイルポインタがファイルの最後を指しているため、ftell(fid)はファイルの現在の位置を示します。この場合、ファイル内の合計バイト数に対応します。明らかに最初の16バイトは関心のあるデータの一部ではないため、16を減算します。さて、我々はcnt * 784 = ftell(fid) - 16を知っているので、cntを解決するにはちょうど784で割ります。

次に、ファイルポインタを17番目のバイト(データの先頭)に戻して、1:cntをループして、freadの各784バイトの部分を読み込みます。

関連する問題