hdf5格式的matlab读写操作

最近要用caffe处理一个multi-label的回归问题,就是输出是一个向量,不是一个具体的数值,这个时候之前的leveldb格式就不凑效了,因为caffe源代码里面默认label是一个数值,网上搜了下,都说hdf5格式可以解决这个问题

在caffe里面,有一个hdf5的datalayer作为数据输入,从源代码来看,对于label的维数没做限制,剩下的问题就是如何生成hdf5的数据,目前只是找到了github上的一个人共享的用matlab写的hdf5数据的读写操作,在这我把代码粘贴出来

testHDF5.m

%% WRITING TO HDF5
filename='trial.h5';

num_total_samples=10000;
% to simulate data being read from disk / generated etc.
data_disk=rand(5,5,1,num_total_samples);
label_disk=rand(10,num_total_samples); 

chunksz=100;
created_flag=false;
totalct=0;
for batchno=1:num_total_samples/chunksz
  fprintf('batch no. %d\n', batchno);
  last_read=(batchno-1)*chunksz;

  % to simulate maximum data to be held in memory before dumping to hdf5 file
  batchdata=data_disk(:,:,1,last_read+1:last_read+chunksz);
  batchlabs=label_disk(:,last_read+1:last_read+chunksz);

  % store to hdf5
  startloc=struct('dat',[1,1,1,totalct+1], 'lab', [1,totalct+1]);
  curr_dat_sz=store2hdf5(filename, batchdata, batchlabs, ~created_flag, startloc, chunksz);
  created_flag=true;% flag set so that file is created only once
  totalct=curr_dat_sz(end);% updated dataset size (#samples)
end

% display structure of the stored HDF5 file
h5disp(filename);

%% READING FROM HDF5

% Read data and labels for samples #1000 to 1999
data_rd=h5read(filename, '/data', [1 1 1 1000], [5, 5, 1, 1000]);
label_rd=h5read(filename, '/label', [1 1000], [10, 1000]);
fprintf('Testing ...\n');
try
  assert(isequal(data_rd, single(data_disk(:,:,:,1000:1999))), 'Data do not match');
  assert(isequal(label_rd, single(label_disk(:,1000:1999))), 'Labels do not match');

  fprintf('Success!\n');
catch err
  fprintf('Test failed ...\n');
  getReport(err)
end

%delete(filename);

% CREATE list.txt containing filename, to be used as source for HDF5_DATA_LAYER
FILE=fopen('list.txt', 'w');
fprintf(FILE, '%s', filename);
fclose(FILE);
fprintf('HDF5 filename listed in %s \n', 'list.txt');

% NOTE: In net definition prototxt, use list.txt as input to HDF5_DATA as:
% layers {
%   name: "data"
%   type: HDF5_DATA
%   top: "data"
%   top: "labelvec"
%   hdf5_data_param {
%     source: "/path/to/list.txt"
%     batch_size: 64
%   }
% }

store2hdf5.m

<span style="font-family:Microsoft YaHei;font-size:18px;">function [curr_dat_sz, curr_lab_sz] = store2hdf5(filename, data, labels, create, startloc, chunksz)
  % *data* is W*H*C*N matrix of images should be normalized (e.g. to lie between 0 and 1) beforehand
  % *label* is D*N matrix of labels (D labels per sample)
  % *create* [0/1] specifies whether to create file newly or to append to previously created file, useful to store information in batches when a dataset is too big to be held in memory  (default: 1)
  % *startloc* (point at which to start writing data). By default,
  % if create=1 (create mode), startloc.data=[1 1 1 1], and startloc.lab=[1 1];
  % if create=0 (append mode), startloc.data=[1 1 1 K+1], and startloc.lab = [1 K+1]; where K is the current number of samples stored in the HDF
  % chunksz (used only in create mode), specifies number of samples to be stored per chunk (see HDF5 documentation on chunking) for creating HDF5 files with unbounded maximum size - TLDR; higher chunk sizes allow faster read-write operations 

  % verify that format is right
  dat_dims=size(data);
  lab_dims=size(labels);
  num_samples=dat_dims(end);

  assert(lab_dims(end)==num_samples, 'Number of samples should be matched between data and labels');

  if ~exist('create','var')
    create=true;
  end

  if create
    %fprintf('Creating dataset with %d samples\n', num_samples);
    if ~exist('chunksz', 'var')
      chunksz=1000;
    end
    if exist(filename, 'file')
      fprintf('Warning: replacing existing file %s \n', filename);
      delete(filename);
    end
    h5create(filename, '/data', [dat_dims(1:end-1) Inf], 'Datatype', 'single', 'ChunkSize', [dat_dims(1:end-1) chunksz]); % width, height, channels, number
    h5create(filename, '/label', [lab_dims(1:end-1) Inf], 'Datatype', 'single', 'ChunkSize', [lab_dims(1:end-1) chunksz]); % width, height, channels, number
    if ~exist('startloc','var')
      startloc.dat=[ones(1,length(dat_dims)-1), 1];
      startloc.lab=[ones(1,length(lab_dims)-1), 1];
    end
  else  % append mode
    if ~exist('startloc','var')
      info=h5info(filename);
      prev_dat_sz=info.Datasets(1).Dataspace.Size;
      prev_lab_sz=info.Datasets(2).Dataspace.Size;
      assert(prev_dat_sz(1:end-1)==dat_dims(1:end-1), 'Data dimensions must match existing dimensions in dataset');
      assert(prev_lab_sz(1:end-1)==lab_dims(1:end-1), 'Label dimensions must match existing dimensions in dataset');
      startloc.dat=[ones(1,length(dat_dims)-1), prev_dat_sz(end)+1];
      startloc.lab=[ones(1,length(lab_dims)-1), prev_lab_sz(end)+1];
    end
  end

  if ~isempty(data)
    h5write(filename, '/data', single(data), startloc.dat, size(data));
    h5write(filename, '/label', single(labels), startloc.lab, size(labels));
  end

  if nargout
    info=h5info(filename);
    curr_dat_sz=info.Datasets(1).Dataspace.Size;
    curr_lab_sz=info.Datasets(2).Dataspace.Size;
  end
end</span>

时间: 2024-07-29 04:27:30

hdf5格式的matlab读写操作的相关文章

MATLAB串口操作和GUI编程

简单的MATLAB GUI编程和串口控制.Word编辑,如需PDF版本,请留言.说实话这个挺难看的……     概述 本文介绍了程序AD9512_Serial_GUI的编程思路和功能.该程序设计到MATLAB的图像用户界面编程的基本方法和串口的基本操作.程序目的在于通过串口写控制字对AD9512进行配置(AD9512通过SPI写入寄存器,本程序只是整个控制程序中的一部分). 修订历史 以下表格展示了本文档的修订过程 日期 版本号 修订内容 2015/01/15 V0.0 初始版本,试验版[1]

Matlab文件操作

1.  Matlab文件操作主要有三个步骤:首先打开文件,然后对文件进行读写操作,最后要关闭文件. 2.  fid=fopen(文件名,打开方式) 'r' 只读,文件必须存在(缺省的打开方式) 'w' 写文件,若文件已存在则原内容将被覆盖:若文件不存在则新建一个 'a' 在文件末尾添加,文件若不存在则新建一个 'r+' 可读可写,文件必须存在 'w+' 可读可写,若文件已存在则原内容将被覆盖:若文件不存在则新建一个 'a+' 可读可写可添加,文件若不存在则新建一个 3.  fid 为文件句柄,其

文件的新建、定位、截短和读写操作

1.创建一个新文件,创建新文件除了可以使用open函数之外还可以用creat()函数. 创建文件函数 creat(const char * pathname, mode_t mode) 头文件 :#include <fcntl.h> 参数说明:第一个参数pathname同open函数的第一个参数具有同样的意义,区别在于这是需要创建的文件的地址而不是需要打开文件的地址,第二个参数mode是新建文件的访问权限. 返回值:成功返回1,失败返回-1. 函数说明:creat()函数能够创建一个新的文件,

oracle读写文件--利用utl_file包对磁盘文件的读写操作

摘要: 用户提出一个需求,即ORACLE中的一个表存储了照片信息,字段类型为BLOB,要求能导出成文件形式. 本想写个C#程序来做,后来想起ORACLE有很多包,功能很好很强大,于是网上参考了些文章完成了. 主要是用了ORACLE的两个包:UTL_FILE和DBMS_LOB. 实现过程: 第一步:以管理员用户登陆设置可操作目录 --CREATE DIRECTORY privilege is granted only to SYS and SYSTEM by default. create or

使用shell脚本简单模拟对特定文件同时读写操作

使用shell脚本简单模拟对特定文件同时读写操作文件内容的格式:field1    ,       field2    , field3    ,       field4以,为分隔符,但是存在空格. 脚本用法如下: ./check_write_read.sh 10 输出结果: Thu Apr 27 19:59:44 CST 2017:Read operation finished 670 Thu Apr 27 19:59:44 CST 2017:Write operation finished

MATLAB常用操作

1.点乘,点除,点乘方 点乘(对应元素相乘),必须同维或者其中一个是标量,a.*b 点除,a.\b表示矩阵b的每个元素除以a中对应元素或者除以常数a,a./b表示常数a除以矩阵b中每个元素或者矩阵a除以矩阵b对应元素或者常数b 点乘方a.^b,矩阵a中每个元素按b中对应元素乘方或者b是常数 2.矩阵中元素的操作 矩阵a中第r行,a(r,:), 第r列,a(:,r), 依次提取每一列组成一个列向量a(:), 提取子矩阵第i到j行和第k到t列a(i:j,k:t) 可以通过下标引用,但是元素下标从1开

matlab字符串操作总结

matlab字符串操作总结 字符串操作总结 char(S1,S2,…)利用给定的字符串或单元数组创建字符数组double(S)将字符串转化成ASC码形式cellstr(S)利用的给定的字符数组创建字符串单元数组blanks(n)生成一个由n个空格组成的字符串deblank(S)删除尾部的空格eval_r(S) evalc(S)使用MATLAB解释器求字符串表达式的值ischar(S)判断是不是字符串数组iscellstr(C)判断是不是字符串单元数组isletter(S)判断是不是字母isspa

matlab读写图片,读取图像序列,读取AVI视频

介绍使用matlab读写图片,读取图像序列,读取AVI视频的方法: 一. 读写图像 使用matlab读一幅图像,并另存 1 % Filename: ImageReadWrite 2 clc; 3 clear; 4 i = imread('D:\\aa3.bmp');%打开D:\\aa3.bmp图像 5 imshow(i); %显示图像 6 imwrite(i, 'D:\\aa4.jpg');%将图像另存为D:\\aa4.jpg 使用matlab读写还可以进行图片格式转换,将jpg图像转换成256

C#拾遗之读写操作

最近一直在学C#语言,在写一些程序的时候难免遇到C#输入输出的问题,除了葛老师讲的一些东西,我也在看网上的一些关于C#程序设计的视频讲解,在看到C#流程控制结构的这一章节,看到了一个很好的关于C#读写操作的一个例子.这个例子就是典型的for迭代语句编写"小九九表". 第一种输出格式的代码: <span style="font-size:18px;"> for (int i = 1; i <=9; i++) { for (int j = 1; j &