File size: 10,417 Bytes
c6cd40d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 | #!/usr/bin/env python3
"""
生成按退化类型分类的详细表格
输出格式:
Corruption Category novel_ap50_PC_c novel_ap50_rPC(%) base_ap50_PC_c base_ap50_rPC(%) all_ap50_PC_c all_ap50_rPC(%)
gaussian_noise noise 27.32 72.83 38.18 69.50 35.34 70.15
shot_noise noise 27.17 72.43 37.67 68.57 34.92 69.32
...
"""
import os
import json
import argparse
import pickle
try:
import pandas as pd
HAS_PANDAS = True
except ImportError:
HAS_PANDAS = False
print("Warning: pandas not installed, Excel output disabled")
# 15 种 benchmark 退化类型
BENCHMARK_CORRUPTIONS = [
'gaussian_noise', 'shot_noise', 'impulse_noise',
'defocus_blur', 'glass_blur', 'motion_blur', 'zoom_blur',
'snow', 'frost', 'fog', 'brightness',
'contrast', 'elastic_transform', 'pixelate', 'jpeg_compression'
]
# 退化类别
CORRUPTION_CATEGORIES = {
'gaussian_noise': 'noise',
'shot_noise': 'noise',
'impulse_noise': 'noise',
'defocus_blur': 'blur',
'glass_blur': 'blur',
'motion_blur': 'blur',
'zoom_blur': 'blur',
'snow': 'weather',
'frost': 'weather',
'fog': 'weather',
'brightness': 'weather',
'contrast': 'digital',
'elastic_transform': 'digital',
'pixelate': 'digital',
'jpeg_compression': 'digital'
}
# 预定义的 Clean 数据性能 (P_clean)
PREDEFINED_CLEAN_METRICS = {
'clearclip': {
'base_ap50': 44.00,
'novel_ap50': 26.74,
'all_ap50': 39.49,
},
'clipself': {
'base_ap50': 54.94,
'novel_ap50': 37.51,
'all_ap50': 50.38,
}
}
def load_model_results(results_dir, model_name):
"""加载单个模型的结果"""
# 尝试加载 merged_results.pkl (包含详细的 corruption_avg)
pkl_path = os.path.join(results_dir, 'merged_results.pkl')
if os.path.exists(pkl_path):
with open(pkl_path, 'rb') as f:
data = pickle.load(f)
return data
# 尝试加载 JSON 汇总
json_path = os.path.join(results_dir, 'robustness_summary.json')
if os.path.exists(json_path):
with open(json_path, 'r') as f:
return {'robustness_results': json.load(f)}
return None
def get_clean_metrics(model_name):
"""获取模型的 clean metrics"""
model_key = model_name.lower().replace('-', '').replace('_', '')
for key, metrics in PREDEFINED_CLEAN_METRICS.items():
if key in model_key or model_key in key:
return metrics.copy()
return {}
def generate_corruption_table(results_dir, model_name):
"""生成按退化类型的详细表格"""
data = load_model_results(results_dir, model_name)
if data is None:
print(f"ERROR: Could not load results from {results_dir}")
return None
robustness = data.get('robustness_results', data)
corruption_avg = robustness.get('corruption_avg', {})
# 获取 P_clean
p_clean = robustness.get('P', robustness.get('P_clean', {}))
if not p_clean:
p_clean = get_clean_metrics(model_name)
rows = []
for corr in BENCHMARK_CORRUPTIONS:
category = CORRUPTION_CATEGORIES.get(corr, 'unknown')
corr_data = corruption_avg.get(corr, {})
row = {
'Corruption': corr,
'Category': category,
}
for metric in ['novel_ap50', 'base_ap50', 'all_ap50']:
pc_c = corr_data.get(metric)
p_clean_val = p_clean.get(metric)
# PC_c (Performance under Corruption for this corruption type)
row[f'{metric}_PC_c'] = round(pc_c, 2) if pc_c is not None else None
# rPC(%) = PC_c / P_clean * 100
if pc_c is not None and p_clean_val is not None and p_clean_val > 0:
rpc = (pc_c / p_clean_val) * 100
row[f'{metric}_rPC(%)'] = round(rpc, 2)
else:
row[f'{metric}_rPC(%)'] = None
rows.append(row)
return rows, p_clean
def print_corruption_table(rows, model_name, p_clean):
"""打印退化类型表格"""
print(f"\n{'='*120}")
print(f"Corruption-level Performance: {model_name}")
print(f"P_clean: novel_ap50={p_clean.get('novel_ap50')}, base_ap50={p_clean.get('base_ap50')}, all_ap50={p_clean.get('all_ap50')}")
print(f"{'='*120}")
# 表头
header = f"{'Corruption':<20} {'Category':<10}"
for metric in ['novel_ap50', 'base_ap50', 'all_ap50']:
header += f" {metric+'_PC_c':>14} {metric+'_rPC(%)':>14}"
print(header)
print("-" * 120)
# 数据行
for row in rows:
line = f"{row['Corruption']:<20} {row['Category']:<10}"
for metric in ['novel_ap50', 'base_ap50', 'all_ap50']:
pc_c = row.get(f'{metric}_PC_c')
rpc = row.get(f'{metric}_rPC(%)')
pc_c_str = f"{pc_c:.2f}" if pc_c is not None else "N/A"
rpc_str = f"{rpc:.2f}" if rpc is not None else "N/A"
line += f" {pc_c_str:>14} {rpc_str:>14}"
print(line)
print("=" * 120)
def save_corruption_table_excel(all_tables, output_path):
"""保存所有模型的退化类型表格到 Excel"""
if not HAS_PANDAS:
print("ERROR: pandas not installed, cannot save Excel")
return
columns = ['Corruption', 'Category',
'novel_ap50_PC_c', 'novel_ap50_rPC(%)',
'base_ap50_PC_c', 'base_ap50_rPC(%)',
'all_ap50_PC_c', 'all_ap50_rPC(%)']
with pd.ExcelWriter(output_path, engine='openpyxl') as writer:
for model_name, (rows, p_clean) in all_tables.items():
# 创建 DataFrame
df = pd.DataFrame(rows)
df = df[columns]
# 计算 mPC
mpc = {}
for metric in ['novel_ap50', 'base_ap50', 'all_ap50']:
values = [row.get(f'{metric}_PC_c') for row in rows if row.get(f'{metric}_PC_c') is not None]
if values:
mpc[metric] = sum(values) / len(values)
# 计算整体 rPC
rpc = {}
for metric in ['novel_ap50', 'base_ap50', 'all_ap50']:
if mpc.get(metric) and p_clean.get(metric):
rpc[metric] = (mpc[metric] / p_clean[metric]) * 100
# 创建汇总行 (确保每行都有完整的列)
summary_rows = [
# 空行
{col: None for col in columns},
# P_clean 行
{
'Corruption': 'P_clean',
'Category': None,
'novel_ap50_PC_c': p_clean.get('novel_ap50'),
'novel_ap50_rPC(%)': None,
'base_ap50_PC_c': p_clean.get('base_ap50'),
'base_ap50_rPC(%)': None,
'all_ap50_PC_c': p_clean.get('all_ap50'),
'all_ap50_rPC(%)': None,
},
# mPC 行
{
'Corruption': 'mPC',
'Category': None,
'novel_ap50_PC_c': round(mpc.get('novel_ap50', 0), 2),
'novel_ap50_rPC(%)': round(rpc.get('novel_ap50', 0), 2),
'base_ap50_PC_c': round(mpc.get('base_ap50', 0), 2),
'base_ap50_rPC(%)': round(rpc.get('base_ap50', 0), 2),
'all_ap50_PC_c': round(mpc.get('all_ap50', 0), 2),
'all_ap50_rPC(%)': round(rpc.get('all_ap50', 0), 2),
},
]
df_summary = pd.DataFrame(summary_rows, columns=columns)
# 合并到主 DataFrame
df_full = pd.concat([df, df_summary], ignore_index=True)
df_full.to_excel(writer, sheet_name=model_name, index=False)
print(f"Corruption table Excel saved to: {output_path}")
def save_corruption_table_json(all_tables, output_path):
"""保存所有模型的退化类型表格到 JSON"""
result = {}
for model_name, (rows, p_clean) in all_tables.items():
result[model_name] = {
'P_clean': p_clean,
'corruption_details': rows
}
with open(output_path, 'w') as f:
json.dump(result, f, indent=2)
print(f"Corruption table JSON saved to: {output_path}")
def main():
parser = argparse.ArgumentParser(description='Generate corruption-level performance table')
parser.add_argument('--results-dirs', type=str, nargs='+', required=True,
help='Directories containing model results')
parser.add_argument('--model-names', type=str, nargs='+', default=None,
help='Model names (default: infer from directory names)')
parser.add_argument('--output-dir', type=str, default='.',
help='Output directory')
parser.add_argument('--output-prefix', type=str, default='corruption_table',
help='Output file prefix')
args = parser.parse_args()
# 推断模型名称
if args.model_names is None:
args.model_names = [os.path.basename(d.rstrip('/')) for d in args.results_dirs]
if len(args.model_names) != len(args.results_dirs):
print("ERROR: Number of model names must match number of results directories")
return
# 生成所有模型的表格
all_tables = {}
for results_dir, model_name in zip(args.results_dirs, args.model_names):
print(f"Generating table for {model_name} from {results_dir}...")
result = generate_corruption_table(results_dir, model_name)
if result:
rows, p_clean = result
all_tables[model_name] = (rows, p_clean)
print_corruption_table(rows, model_name, p_clean)
if not all_tables:
print("ERROR: No valid results found!")
return
# 保存结果
os.makedirs(args.output_dir, exist_ok=True)
excel_path = os.path.join(args.output_dir, f'{args.output_prefix}.xlsx')
save_corruption_table_excel(all_tables, excel_path)
json_path = os.path.join(args.output_dir, f'{args.output_prefix}.json')
save_corruption_table_json(all_tables, json_path)
if __name__ == '__main__':
main()
|