1.h5文件格式
https://blog.csdn.net/buchidanhuang/article/details/89716252
HDF(Hierarchical Data Format),設計用於存儲和組織大量數據的文件格式。
h5文件中有兩個核心的概念:組“group”和數據集“dataset”。組可以理解為文件夾,數據集理解為文件,文件夾中可以遞歸地包含文件夾、文件等。
- dataset :簡單來講類似數組組織形式的數據集合,像 numpy 數組一樣工作,一個dataset即一個numpy.ndarray。具體的dataset可以是圖像、表格,甚至是pdf文件和excel。
- group:包含了其它 dataset(數組) 和 其它 group ,像字典一樣工作。
2.讀取h5文件
# Reading h5 file import h5py with h5py.File('cat_dog.h5',"r") as f: for key in f.keys(): #print(f[key], key, f[key].name, f[key].value)
# 因為這里有group對象它是沒有value屬性的,故會異常。另外字符串讀出來是字節流,需要解碼成字符串。 print(f[key], key, f[key].name)
""" 結果: <HDF5 group "/dogs" (1 members)> dogs /dogs <HDF5 dataset "list_classes": shape (2,), type "|S7"> list_classes /list_classes <HDF5 dataset "train_set_x": shape (209, 64, 64, 3), type "|u1"> train_set_x /train_set_x <HDF5 dataset "train_set_y": shape (209,), type "<i8"> train_set_y /train_set_y
代碼解析:
- 文件對象f它表示h5文件的根目錄(root group),
- group是按字典的方式工作的,通過f.keys()來找到根目錄下的所有dataset和group的key,然后通過key來訪問各個dataset或group對象。
結果解析:
1.我們可以發現這個h5文件下有1個叫dogs的文件夾(group)和3個文件(dataset)它們分別叫list_classes,train_set_x,train_set_y它們的shape都可知。
dogs group下有一個成員但我們不知道它是group還是dataset。
2.我們可以發現key和name的區別:
- key是關鍵字
- name絕對路徑:比如下文中訪問name得到:/dogs/husky,它表示根目錄下有dogs這個掛載點,dogs下又掛載了husky。
在打開的f中繼續:
dogs_group = f["dogs"] for key in dogs_group.keys(): print(dogs_group[key], dogs_group[key].name)
結果: <HDF5 dataset "husky": shape (64, 64, 3), type "<f8"> /dogs/husky 可見dogs文件夾下有個key為husky的文件dataset
打印Group的name和Dataset的value:
from h5py import Dataset, Group, File with File('cat_dog.h5','r') as f: for k in f.keys(): if isinstance(f[k], Dataset): print(f[k].value) else: print(f[k].name)
3.寫h5文件
# Writing h5 import h5py import numpy as np # mode可以是"w",為防止打開一個已存在的h5文件而清除其數據,故使用"a"模式 with h5py.File("animals.h5", 'a') as f: f.create_dataset('animals_included',data=np.array(["dogs".encode(),"cats".encode()])) # 根目錄下創建一個總覽介紹動物種類的dataset,字符串應當字節化 dogs_group = f.create_group("dogs") # 在根目錄下創建gruop文件夾:dogs f.create_dataset('cats',data = np.array(np.random.randn(5,64,64,3))) # 根目錄下有一個含5張貓圖片的dataset文件 dogs_group.create_dataset("husky",data=np.random.randn(64,64,3)) # 在dogs文件夾下分別創建兩個dataset,一張哈士奇圖片和一張柴犬的圖片 dogs_group.create_dataset("shiba",data=np.random.randn(64,64,3))
2.從hd5轉換為csv格式
https://gist.github.com/kokitsuyuzaki/5b6cebcaf37100c8794bdb89c7135fd5