在hdf5文件中重命名dataset

本文介绍了一个H5PY库中不常被注意到的功能——使用move接口直接重命名或移动dataset,避免了手动创建和删除dataset的繁琐步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


以前考虑这个功能时一直没有找到接口,以为要自己先创建一个同样的dataset,再删除老的dataset。今天五一中看到group的接口中有一个:

move(source, dest)

Move an object or link in the file. If source is a hard link, thiseffectively renames the object. If a soft or external link, thelink itself is moved.

Parameters:
  • source (String) – Name of object or link to move.
  • dest (String) – New location for object or link.

于是用一个文件测试了一下,竟然成功!

import h5py
f = h5py.File('e:\\test.h5')
grp = f['/Trans']
grp.move('20141031', '20150101')
f.close()

注意move接口中的两个参数就是源dataset和目的dataset。


import os import sys import urllib.request import zipfile import h5py import time import shutil # 更新目标文件路径(使用官方最新结构) TARGET_DIR = r"D:\cs231n.github.io-master\assignments\2021\assignment3_colab\assignment3\cs231n\datasets\coco_captioning" TARGET_FILE = os.path.join(TARGET_DIR, "coco2014_captions.h5") def handle_long_paths(path): """处理Windows长路径问题""" if len(path) > 260 and sys.platform == "win32": if not path.startswith(r"\\?\\"): return r"\\?\\" + os.path.abspath(path) return path def fix_path_issues(file_path): """修复路径相关的问题""" file_path = handle_long_paths(file_path) os.makedirs(os.path.dirname(file_path), exist_ok=True) if os.path.exists(file_path): print(f"✅ 文件已存在: {file_path}") return True, file_path print(f"❌ 文件不存在: {file_path}") return False, file_path def download_coco_dataset(file_path): """下载并解压COCO数据集(使用官方源+重试机制)""" # 官方下载链接(使用2017整合版) dataset_urls = [ "http://images.cocodataset.org/annotations/annotations_trainval2017.zip", "https://pjreddie.com/media/files/coco/annotations_trainval2017.zip" ] zip_path = os.path.join(TARGET_DIR, "coco_annotations.zip") extracted_dir = os.path.join(TARGET_DIR, "annotations") # 尝试多个镜像源 for i, url in enumerate(dataset_urls): try: print(f"尝试下载源 {i+1}/{len(dataset_urls)}: {url}") urllib.request.urlretrieve(url, zip_path) print("✅ 下载成功") break except Exception as e: print(f"下载失败: {str(e)}") if i == len(dataset_urls) - 1: return False, file_path # 解压文件 print("解压文件中...") try: with zipfile.ZipFile(zip_path, 'r') as zip_ref: zip_ref.extractall(TARGET_DIR) # 重命名文件结构 captions_file = os.path.join(extracted_dir, "captions_trainval2017.json") if os.path.exists(captions_file): # 课程需要的是HDF5格式,这里进行转换 convert_to_hdf5(captions_file, file_path) os.remove(zip_path) # 清理压缩包 shutil.rmtree(extracted_dir) # 删除临时目录 except Exception as e: print(f"解压失败: {str(e)}") return False, file_path return os.path.exists(file_path), file_path def convert_to_hdf5(json_path, hdf5_path): """将JSON标注转换为课程需要的HDF5格式""" print("转换标注格式为HDF5...") try: import json import numpy as np with open(json_path, 'r') as f: data = json.load(f) # 创建HDF5文件 with h5py.File(hdf5_path, 'w') as hf: # 创建数据集结构 hf.create_dataset("train_captions", data=np.array([ann["caption"] for ann in data["annotations"]])) hf.create_dataset("train_image_idxs", data=np.array([ann["image_id"] for ann in data["annotations"]])) print("✅ 格式转换完成") except Exception as e: print(f"❌ 格式转换失败: {str(e)}") raise def validate_hdf5_file(file_path): """验证HDF5文件完整性""" try: with h5py.File(file_path, 'r') as f: if "train_captions" in f and "train_image_idxs" in f: print("✅ 文件验证成功! 包含:") print(f" - 标注数量: {len(f['train_captions'])}") return True print("❌ 文件结构不符合要求") return False except Exception as e: print(f"❌ 文件验证失败: {str(e)}") return False # 主执行流程 if __name__ == "__main__": exists, current_path = fix_path_issues(TARGET_FILE) if not exists: downloaded, current_path = download_coco_dataset(current_path) if downloaded: print(f"✅ 数据集成功部署: {current_path}") else: print("❌ 数据集部署失败,请手动下载") sys.exit(1) if not validate_hdf5_file(current_path): print("❌ 文件验证失败,数据集可能损坏") sys.exit(1) print("✨ 所有操作成功完成!") ❌ 文件不存在: D:\cs231n.github.io-master\assignments\2021\assignment3_colab\assignment3\cs231n\datasets\coco_captioning\coco2014_captions.h5 尝试下载源 1/2: http://images.cocodataset.org/annotations/annotations_trainval2017.zip ✅ 下载成功 解压文件中... ❌ 数据集部署失败,请手动下载 An exception has occurred, use %tb to see the full traceback. SystemExit: 1 D:\miniconda\lib\site-packages\IPython\core\interactiveshell.py:3587: UserWarning: To exit: use 'exit', 'quit', or Ctrl-D. warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
07-28
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值