170 lines
7.5 KiB
Python
170 lines
7.5 KiB
Python
import os
|
|
import pickle
|
|
import numpy as np
|
|
from tqdm import tqdm
|
|
|
|
|
|
def check_and_delete_invalid_data_files(dataset_path, sample_folder="", dry_run=True):
|
|
"""
|
|
检查指定数据集的样本文件中 'data' 字段是否包含 NaN 或 Inf 值,
|
|
并根据 dry_run 参数决定是否删除这些文件。
|
|
|
|
Args:
|
|
dataset_path (str): 数据集的主路径 (例如, '../data/wearable_downstream/PPG_HTN')。
|
|
sample_folder (str): 包含样本 .pkl 文件的文件夹名称。
|
|
dry_run (bool): 如果为 True,则只报告哪些文件会被删除,而不实际删除。
|
|
如果为 False,则实际删除文件。
|
|
"""
|
|
root_dir = os.path.join(dataset_path, sample_folder)
|
|
if not os.path.isdir(root_dir):
|
|
print(f"错误: 目录 '{root_dir}' 不存在。")
|
|
return
|
|
|
|
print(f"开始检查数据集: {dataset_path}")
|
|
print(f"样本文件夹: {sample_folder}")
|
|
if dry_run:
|
|
print("模式: Dry Run (仅报告,不删除文件)")
|
|
else:
|
|
print("模式: !!! 文件删除已启用 !!!")
|
|
print("-" * 30)
|
|
|
|
files_to_delete_nan = []
|
|
files_to_delete_inf = []
|
|
files_with_other_issues = []
|
|
all_files_count = 0
|
|
deleted_count = 0
|
|
problematic_files_count = 0
|
|
|
|
file_list = [f for f in os.listdir(root_dir) if f.endswith('.pkl')]
|
|
if not file_list:
|
|
print("未找到 .pkl 文件。")
|
|
return
|
|
|
|
for filename in tqdm(file_list, desc="检查文件中"):
|
|
all_files_count += 1
|
|
filepath = os.path.join(root_dir, filename)
|
|
is_problematic_current_file = False
|
|
try:
|
|
with open(filepath, 'rb') as f:
|
|
sample = pickle.load(f)
|
|
|
|
if 'data' not in sample:
|
|
print(f"警告: 文件 '{filename}' 中缺少 'data' 字段。跳过删除检查。")
|
|
files_with_other_issues.append(filename)
|
|
is_problematic_current_file = True
|
|
continue # 不删除缺少 'data' 字段的文件,除非你明确想这样做
|
|
|
|
data_array = sample['data']
|
|
if not isinstance(data_array, np.ndarray):
|
|
try:
|
|
data_array = np.array(data_array, dtype=float)
|
|
except Exception as e:
|
|
print(
|
|
f"警告: 文件 '{filename}' 中的 'data' 字段无法转换为 NumPy 数组: {e}。跳过删除检查。")
|
|
files_with_other_issues.append(filename)
|
|
is_problematic_current_file = True
|
|
continue
|
|
|
|
has_nan = np.isnan(data_array).any()
|
|
has_inf = np.isinf(data_array).any()
|
|
|
|
action_taken = False
|
|
if has_nan:
|
|
files_to_delete_nan.append(filename)
|
|
is_problematic_current_file = True
|
|
if not dry_run:
|
|
try:
|
|
os.remove(filepath)
|
|
print(f"已删除 (NaN): {filename}")
|
|
deleted_count += 1
|
|
action_taken = True
|
|
except Exception as e_del:
|
|
print(f"删除文件 '{filename}' 失败: {e_del}")
|
|
|
|
if has_inf and not action_taken: # 如果因为NaN已经删了,就不用再判断Inf了
|
|
files_to_delete_inf.append(filename)
|
|
is_problematic_current_file = True
|
|
if not dry_run:
|
|
try:
|
|
os.remove(filepath)
|
|
print(f"已删除 (Inf): {filename}")
|
|
deleted_count += 1
|
|
except Exception as e_del:
|
|
print(f"删除文件 '{filename}' 失败: {e_del}")
|
|
elif has_inf and action_taken and filename not in files_to_delete_inf: # 如果因为NaN删了,但它也包含Inf,记录一下
|
|
files_to_delete_inf.append(filename)
|
|
|
|
except Exception as e:
|
|
print(f"错误: 处理文件 '{filename}' 时发生错误: {e}。跳过删除检查。")
|
|
files_with_other_issues.append(filename)
|
|
is_problematic_current_file = True
|
|
|
|
if is_problematic_current_file:
|
|
problematic_files_count += 1
|
|
|
|
print("\n--- 检查与删除结果 ---")
|
|
print(f"总共检查文件数: {all_files_count}")
|
|
print(f"总计发现有问题的文件数 (计划删除或有其他读取/格式问题): {problematic_files_count}")
|
|
|
|
if files_to_delete_nan:
|
|
print(f"\n以下 {len(files_to_delete_nan)} 个文件的 'data' 字段包含 NaN 值{' (并已删除,如果非 Dry Run)' if not dry_run else ' (计划删除,如果非 Dry Run)'}:")
|
|
for fname in files_to_delete_nan:
|
|
print(f" - {fname}")
|
|
else:
|
|
print("\n未在 'data' 字段中检测到 NaN 值。")
|
|
|
|
if files_to_delete_inf:
|
|
print(f"\n以下 {len(files_to_delete_inf)} 个文件的 'data' 字段包含 Inf 值{' (并已删除,如果非 Dry Run)' if not dry_run else ' (计划删除,如果非 Dry Run)'}:")
|
|
# 避免重复打印已因NaN删除的文件
|
|
unique_inf_files_to_report = [f for f in files_to_delete_inf if f not in files_to_delete_nan or not (
|
|
f in files_to_delete_nan and not dry_run)]
|
|
if unique_inf_files_to_report:
|
|
for fname in unique_inf_files_to_report:
|
|
print(f" - {fname}")
|
|
elif not files_to_delete_nan: # 如果没有NaN文件,但有Inf文件
|
|
for fname in files_to_delete_inf:
|
|
print(f" - {fname}")
|
|
|
|
else:
|
|
print("\n未在 'data' 字段中检测到 Inf 值。")
|
|
|
|
if files_with_other_issues:
|
|
print(f"\n以下 {len(files_with_other_issues)} 个文件存在其他读取/格式问题 (未删除):")
|
|
for fname in files_with_other_issues:
|
|
print(f" - {fname}")
|
|
|
|
if not dry_run:
|
|
print(f"\n实际删除文件总数: {deleted_count}")
|
|
|
|
if not files_to_delete_nan and not files_to_delete_inf and not files_with_other_issues:
|
|
print("\n所有检查通过,未发现 NaN、Inf 或其他问题。")
|
|
elif not files_to_delete_nan and not files_to_delete_inf and files_with_other_issues:
|
|
print("\n未发现 NaN 或 Inf 值,但存在其他文件读取或格式问题。")
|
|
|
|
|
|
if __name__ == '__main__':
|
|
# --- 使用示例 ---
|
|
# 请在这里设置你要检查的数据集路径
|
|
dataset_to_check = "/data/coding/processed_ecg_segments_pkl_flat_no_inf/train"
|
|
|
|
# **重要:**
|
|
# 第一次运行时,建议将 dry_run 设置为 True,以查看哪些文件会被标记为删除。
|
|
# 确认无误后,再将其设置为 False 来实际执行删除操作。
|
|
# **备份你的数据!**
|
|
perform_actual_deletion = True # <--- 修改这里来启用/禁用实际删除
|
|
|
|
if dataset_to_check == "YOUR_DATASET_PATH_HERE": # 只是一个占位符检查
|
|
print("请在脚本中设置 'dataset_to_check' 变量为你要检查的数据集路径。")
|
|
else:
|
|
if perform_actual_deletion:
|
|
confirmation = input(
|
|
f"你确定要删除数据集 '{dataset_to_check}' 中包含无效数据的文件吗?这是一个不可逆操作!(输入 'yes' 以确认): ")
|
|
if confirmation.lower() == 'yes':
|
|
check_and_delete_invalid_data_files(
|
|
dataset_to_check, dry_run=False)
|
|
else:
|
|
print("操作已取消。未删除任何文件。")
|
|
else:
|
|
print("正在以 Dry Run 模式运行,不会删除任何文件。")
|
|
check_and_delete_invalid_data_files(dataset_to_check, dry_run=True)
|