2016-10-15 8 views
2

3d Numpy配列を生成するサンプルコードがあります。このデータをh5ファイルを使用してh5pyファイルに保存します。 2次元データセットを4次元に沿って「追加」するにはどうすればよいですか?または、既存の.h5ファイルの4次元(または新しい軸)に沿って別の3Dデータセットを書き込むにはどうすればよいですか?私は見つけることができるドキュメンテーションを読んでおり、例にはこれに対処していないようです。私のコードを以下に示します。h5pyを使用して新しい軸に沿って既存のh5pyファイルにデータを追加

import h5py 
import numpy as np 

dataset1 = np.random.rand(240,240,250); 
dataset2 = np.random.rand(240,240,250); 

with h5py.File('data.h5', 'w') as hf: 
    dset = hf.create_dataset('dataset_1', data=dataset1) 

答えて

2

は、私は少し実験http://docs.h5py.org/en/latest/high/dataset.htmlを使用する:

In [504]: import h5py 
In [505]: f=h5py.File('data.h5','w') 
In [506]: data=np.ones((3,5)) 

を作るdataset普通:

In [509]: dset=f.create_dataset('dset', data=data) 
In [510]: dset.shape 
Out[510]: (3, 5) 
In [511]: dset.maxshape 
Out[511]: (3, 5) 

ヘルプresize用:

In [512]: dset.resize? 
Signature: dset.resize(size, axis=None) 
Docstring: 
Resize the dataset, or the specified axis. 

The dataset must be stored in chunked format; it can be resized up to 
the "maximum shape" (keyword maxshape) specified at creation time. 
The rank of the dataset cannot be changed. 

maxshapeを指定していないので、このデータセットを変更または追加することはできません。

In [513]: dset1=f.create_dataset('dset1', data=data, maxshape=(2,10,10)) 
... 
ValueError: "maxshape" must have same rank as dataset shape 

私は3次元の「空間」を定義することはできませんし、2次元配列を少なくともこのように配置することはできません。

しかし、私はdataに寸法(ランク)を追加することができます。

In [514]: dset1=f.create_dataset('dset1', data=data[None,...], maxshape=(2,10,10)) 
In [515]: dset1 
Out[515]: <HDF5 dataset "dset1": shape (1, 3, 5), type "<f8"> 

今、私はデータセットのサイズを変更することができます - 1次元以上では、定義された最大まで。

In [521]: dset1[1,:,:]=10 
In [523]: dset1[0,:,5:]=2 

In [524]: dset1[:] 
Out[524]: 
array([[[ 1., 1., 1., 1., 1., 2., 2., 2., 2., 2.], 
     [ 1., 1., 1., 1., 1., 2., 2., 2., 2., 2.], 
     [ 1., 1., 1., 1., 1., 2., 2., 2., 2., 2.]], 

     [[ 10., 10., 10., 10., 10., 10., 10., 10., 10., 10.], 
     [ 10., 10., 10., 10., 10., 10., 10., 10., 10., 10.], 
     [ 10., 10., 10., 10., 10., 10., 10., 10., 10., 10.]]]) 

そうです、あなたが提供する、1つのh5のデータセットであなたのdatasetの両方を置くことができます。

In [517]: dset1.resize((2,3,10)) 
In [518]: dset1 
Out[518]: <HDF5 dataset "dset1": shape (2, 3, 10), type "<f8"> 
In [519]: dset1[:] 
Out[519]: 
array([[[ 1., 1., 1., 1., 1., 0., 0., 0., 0., 0.], 
     [ 1., 1., 1., 1., 1., 0., 0., 0., 0., 0.], 
     [ 1., 1., 1., 1., 1., 0., 0., 0., 0., 0.]], 

     [[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], 
     [ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], 
     [ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]]]) 

dataは現在、いくつかのゼロで埋める展開したデータセット

の一角を占めていますあなたが指定するのに十分な大きさのmaxshape (2,240,240,250)または(240,240,250)または(240,240,250,2)など。

または無制限サイズ変更の場合maxshape=(None, 240, 240, 250))

作成後にディメンションを追加できないという主な制約のようです。

もう1つの方法は、保存する前にデータを連結することです。

dataset12 = np.stack((dataset1, dataset2), axis=0) 
関連する問題