File size: 7,925 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 | #!/usr/bin/env python3
"""
比较多个模型的 OV-COCO 鲁棒性结果
生成格式:
ClearCLIP CLIPSelf
P_clean mPC rPC (%) P_clean mPC rPC (%)
novel_ap50 26.74 13.84 51.76 37.51 29.27 78.05
base_ap50 44.00 26.21 59.57 54.94 40.81 74.27
all_ap50 39.49 22.97 58.17 50.38 37.79 75.01
"""
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")
# 预定义的 Clean 数据性能 (P_clean)
PREDEFINED_CLEAN_METRICS = {
'clearclip': {
'base_ap50': 44.00,
'novel_ap50': 26.74,
'all_ap50': 39.49,
'bbox_mAP': 20.30,
'bbox_mAP_50': 39.50,
},
'clipself': {
'base_ap50': 54.94,
'novel_ap50': 37.51,
'all_ap50': 50.38,
'bbox_mAP': 27.70,
'bbox_mAP_50': 50.00,
}
}
def load_model_results(results_dir, model_name):
"""加载单个模型的结果"""
# 尝试加载 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 json.load(f)
# 尝试加载 pkl
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)
robustness = data.get('robustness_results', {})
return {
'model': model_name,
'P_clean': robustness.get('P', {}),
'mPC': robustness.get('mPC', {}),
'rPC': {k: v * 100 for k, v in robustness.get('rPC', {}).items()},
'category_mPC': robustness.get('category_mPC', {})
}
return None
def print_comparison_table(models_data):
"""打印多模型比较表格"""
model_names = list(models_data.keys())
metrics = ['novel_ap50', 'base_ap50', 'all_ap50']
# 计算列宽
col_width = 10
# 打印表头
print("\n" + "=" * 80)
print("OV-COCO Robustness Comparison")
print("=" * 80)
# 打印模型名称行
print(f"{'Metric':<12}", end="")
for model in model_names:
print(f" | {model:^{col_width * 3 + 4}}", end="")
print()
# 打印子表头
print(f"{'':12}", end="")
for _ in model_names:
print(f" | {'P_clean':>{col_width}} {'mPC':>{col_width}} {'rPC(%)':>{col_width}}", end="")
print()
print("-" * (12 + (col_width * 3 + 5) * len(model_names)))
# 打印数据行
for metric in metrics:
print(f"{metric:<12}", end="")
for model in model_names:
data = models_data[model]
p_val = data.get('P_clean', {}).get(metric, None)
mpc_val = data.get('mPC', {}).get(metric, None)
rpc_val = data.get('rPC', {}).get(metric, None)
p_str = f"{p_val:.2f}" if p_val is not None else "N/A"
mpc_str = f"{mpc_val:.2f}" if mpc_val is not None else "N/A"
rpc_str = f"{rpc_val:.2f}" if rpc_val is not None else "N/A"
print(f" | {p_str:>{col_width}} {mpc_str:>{col_width}} {rpc_str:>{col_width}}", end="")
print()
print("=" * 80)
def save_comparison_excel(models_data, output_path):
"""保存多模型比较到 Excel"""
if not HAS_PANDAS:
print("ERROR: pandas not installed, cannot save Excel")
return
model_names = list(models_data.keys())
metrics = ['novel_ap50', 'base_ap50', 'all_ap50', 'bbox_mAP', 'bbox_mAP_50']
with pd.ExcelWriter(output_path, engine='openpyxl') as writer:
# Sheet 1: Core Comparison
rows = []
for metric in metrics[:3]: # 只取核心指标
row = {'Metric': metric}
for model in model_names:
data = models_data[model]
row[f'{model}_P_clean'] = data.get('P_clean', {}).get(metric)
row[f'{model}_mPC'] = data.get('mPC', {}).get(metric)
row[f'{model}_rPC(%)'] = data.get('rPC', {}).get(metric)
rows.append(row)
df_core = pd.DataFrame(rows)
df_core.to_excel(writer, sheet_name='Core Comparison', index=False)
# Sheet 2: Extended Comparison
rows = []
for metric in metrics:
row = {'Metric': metric}
for model in model_names:
data = models_data[model]
row[f'{model}_P_clean'] = data.get('P_clean', {}).get(metric)
row[f'{model}_mPC'] = data.get('mPC', {}).get(metric)
row[f'{model}_rPC(%)'] = data.get('rPC', {}).get(metric)
rows.append(row)
df_ext = pd.DataFrame(rows)
df_ext.to_excel(writer, sheet_name='Extended Comparison', index=False)
# Sheet 3: Category Comparison
categories = ['noise', 'blur', 'weather', 'digital']
for metric in ['base_ap50', 'novel_ap50', 'all_ap50']:
rows = []
for cat in categories:
row = {'Category': cat}
for model in model_names:
data = models_data[model]
val = data.get('category_mPC', {}).get(cat, {}).get(metric)
row[model] = round(val, 2) if val is not None else None
rows.append(row)
df_cat = pd.DataFrame(rows)
df_cat.to_excel(writer, sheet_name=f'Category {metric}', index=False)
print(f"Comparison Excel saved to: {output_path}")
def save_comparison_json(models_data, output_path):
"""保存比较结果到 JSON"""
with open(output_path, 'w') as f:
json.dump(models_data, f, indent=2)
print(f"Comparison JSON saved to: {output_path}")
def main():
parser = argparse.ArgumentParser(description='Compare OV-COCO robustness results across models')
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 for comparison files')
parser.add_argument('--output-prefix', type=str, default='robustness_comparison',
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
# 加载所有模型结果
models_data = {}
for results_dir, model_name in zip(args.results_dirs, args.model_names):
print(f"Loading results for {model_name} from {results_dir}...")
data = load_model_results(results_dir, model_name)
if data:
models_data[model_name] = data
else:
print(f"Warning: Could not load results for {model_name}")
if not models_data:
print("ERROR: No valid results found!")
return
# 打印比较表格
print_comparison_table(models_data)
# 保存结果
os.makedirs(args.output_dir, exist_ok=True)
excel_path = os.path.join(args.output_dir, f'{args.output_prefix}.xlsx')
save_comparison_excel(models_data, excel_path)
json_path = os.path.join(args.output_dir, f'{args.output_prefix}.json')
save_comparison_json(models_data, json_path)
if __name__ == '__main__':
main()
|