import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torchvision import torchvision.transforms as transforms from utils.carlini_wagner_l2 import carlini_wagner_l2 from tqdm import tqdm import os import json import time from sklearn.calibration import calibration_curve # 设置随机种子以便结果可重现 def set_seed(seed): torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) np.random.seed(seed) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False set_seed(42) # 设置设备 device = torch.device("cuda" if torch.cuda.is_available() else "cpu") print(f"Using device: {device}") # 创建结果目录 TEST_RESULTS_DIR = "test_results" os.makedirs(TEST_RESULTS_DIR, exist_ok=True) # 加载CIFAR-10数据集 def load_cifar10(batch_size=1): transform_test = transforms.Compose([ transforms.ToTensor(), ]) testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform_test) testloader = torch.utils.data.DataLoader(testset, batch_size=batch_size, shuffle=False, num_workers=2) return testloader, testset # 加载ResNet50模型 def load_model(): model = torchvision.models.resnet50(pretrained=True) # 修改最后的全连接层以适应CIFAR-10的10个类别 num_ftrs = model.fc.in_features model.fc = nn.Linear(num_ftrs, 10) # 尝试加载预训练的CIFAR-10权重 try: weight_path = "/share/pretrained_weights/cifar10_resnet50_cross_entropy.model" if os.path.exists(weight_path): state_dict = torch.load(weight_path) model.load_state_dict(state_dict) print(f"Loaded pretrained weights from {weight_path}") else: print(f"Warning: Pretrained weights not found at {weight_path}") print("Using ImageNet pretrained weights with modified final layer") except Exception as e: print(f"Error loading pretrained weights: {e}") model = model.to(device) model.eval() return model # 获取模型特征提取器(返回倒数第二层特征) def get_feature_extractor(model): class FeatureExtractor(nn.Module): def __init__(self, model): super().__init__() self.model = model self.features = None # 注册钩子来获取特征 def hook_fn(module, input, output): self.features = output # 注册到倒数第二层 model.avgpool.register_forward_hook(hook_fn) def forward(self, x): logits = self.model(x) return self.features, logits return FeatureExtractor(model).to(device) # 方法1: 在logits上使用CW攻击计算hardness def compute_hardness_cw_logits(model, inputs, logits, debug=True): """ 通过在logits上使用CW L2攻击来计算样本的硬度 Args: model: 模型 inputs: 输入样本 logits: 样本的logits debug: 是否打印调试信息 Returns: hardness: 样本硬度值 success: 攻击是否成功 """ model.eval() inputs = inputs.to(device) # 获取原始预测 with torch.no_grad(): if logits is None: outputs = model(inputs) else: outputs = logits original_pred = torch.argmax(outputs, 1) probs = F.softmax(outputs, dim=1) confidence = probs.max(dim=1)[0].item() if debug: print(f"Original prediction: {original_pred.item()}, confidence: {confidence:.4f}") # 创建一个简单的logits到输出的模型 class LogitsModel(nn.Module): def __init__(self): super().__init__() def forward(self, x): return x logits_model = LogitsModel().to(device) # 准备函数包装器 def model_fn(x): return logits_model(x) # 将logits转换为可攻击的输入格式 logits_input = outputs.detach().clone() # 应用CW L2攻击到logits try: if debug: print("Running CW attack on logits with parameters:") print(f"- Binary search steps: 5") print(f"- Max iterations: 300") print(f"- Learning rate: 0.01") print(f"- Early stop: True") # 计算logits的最小值和最大值作为clip范围 logits_min = float(logits_input.min()) logits_max = float(logits_input.max()) adv_logits, l2_norms, success_mask = carlini_wagner_l2( model_fn=model_fn, x=logits_input, n_classes=logits_input.shape[1], y=original_pred, targeted=False, lr=0.01, # logits空间可能需要更高的学习率 binary_search_steps=5, max_iterations=300, confidence=0, clip_min=logits_min, clip_max=logits_max, debug=debug, early_stop=True ) # 获取对抗logits的预测 adv_pred = torch.argmax(adv_logits, 1) adv_probs = F.softmax(adv_logits, dim=1) adv_confidence = adv_probs.max(dim=1)[0].item() # 攻击成功与否直接从success_mask获取 attack_success = success_mask.any().item() # 获取L2范数 l2_val = l2_norms[0].item() if l2_norms.numel() > 0 else 0.0 if debug: print(f"Attack result: {'SUCCESS' if attack_success else 'FAILURE'}") print(f"Adversarial prediction: {adv_pred.item()}, confidence: {adv_confidence:.4f}") print(f"L2 perturbation norm in logits space: {l2_val:.4f}") if attack_success: # 根据logits空间的L2值范围来调整映射 # 对于logits空间,范围可能与图像空间不同 # 这里假设logits空间的L2范围为[0,10] logits_l2_max = 10.0 mapped_hardness = 10.0 * min(l2_val, logits_l2_max) / logits_l2_max if debug: print(f"Mapped hardness (CW logits): {mapped_hardness:.4f}") return mapped_hardness, True else: # 攻击失败,表示样本非常稳定 if debug: print("Attack failed in logits space - using high hardness value 9.0") return 9.0, False except Exception as e: if debug: print(f"Error in logits CW attack: {e}") # 使用备用方法(基于logit gap) logits_tensor = torch.tensor(outputs.cpu().numpy(), dtype=torch.float32) original_pred = torch.argmax(logits_tensor).item() # Calculate logit gap sorted_logits, _ = torch.sort(logits_tensor, descending=True) logit_gap = (sorted_logits[0][0] - sorted_logits[0][1]).item() # 如果攻击失败,使用logit gap作为硬度值的指标 logit_gap_score = 5.0 + 5.0 * (logit_gap / (logit_gap + 1.0)) if debug: print(f"Using fallback logit gap hardness due to error: {logit_gap_score:.4f}") return logit_gap_score, False # 方法2: 在logits上添加高斯噪声计算hardness def compute_hardness_gaussian_logits(model, inputs, num_trials=100, noise_std_range=(0.1, 5.0), debug=True): """ 通过在logits上添加高斯噪声来计算样本的硬度 Args: model: 模型 inputs: 输入样本 num_trials: 每个噪声级别的试验次数 noise_std_range: 噪声标准差范围 debug: 是否打印调试信息 Returns: hardness: 样本硬度值 """ model.eval() inputs = inputs.to(device) # 获取原始预测和logits with torch.no_grad(): logits = model(inputs) original_pred = torch.argmax(logits, 1).item() # 噪声标准差列表 noise_stds = np.linspace(noise_std_range[0], noise_std_range[1], 10) # 对每个噪声级别,尝试多次并记录预测改变的频率 pred_changes = [] for noise_std in noise_stds: changes = 0 for _ in range(num_trials): # 添加高斯噪声到logits noise = torch.randn_like(logits) * noise_std noisy_logits = logits + noise noisy_pred = torch.argmax(noisy_logits, 1).item() # 检查预测是否改变 if noisy_pred != original_pred: changes += 1 # 计算该噪声级别下的预测改变比例 change_rate = changes / num_trials pred_changes.append(change_rate) # 如果预测改变率超过50%,停止尝试更大的噪声 if change_rate > 0.5: break # 寻找首次使预测改变率超过20%的噪声级别 threshold_idx = next((i for i, rate in enumerate(pred_changes) if rate >= 0.2), len(noise_stds) - 1) threshold_std = noise_stds[threshold_idx] # 将噪声阈值映射到硬度值 # 噪声越小,样本越容易被扰动,硬度越低 # 我们将噪声范围映射到硬度范围[0,10] max_std = noise_std_range[1] mapped_hardness = 10.0 * min(threshold_std, max_std) / max_std if debug: print(f"Original prediction: {original_pred}") print(f"Threshold noise std: {threshold_std:.4f}") print(f"Mapped hardness (gaussian logits): {mapped_hardness:.4f}") return mapped_hardness, True # 方法3: 在特征上添加高斯噪声计算hardness def compute_hardness_gaussian_features(model, inputs, feature_extractor, num_trials=100, noise_std_range=(0.1, 1.0), debug=True): """ 通过在特征上添加高斯噪声来计算样本的硬度 Args: model: 模型 inputs: 输入样本 feature_extractor: 特征提取器 num_trials: 每个噪声级别的试验次数 noise_std_range: 噪声标准差范围 debug: 是否打印调试信息 Returns: hardness: 样本硬度值 """ model.eval() feature_extractor.eval() inputs = inputs.to(device) # 获取原始特征和预测 with torch.no_grad(): features, logits = feature_extractor(inputs) original_pred = torch.argmax(logits, 1).item() features = features.squeeze() # 噪声标准差列表 noise_stds = np.linspace(noise_std_range[0], noise_std_range[1], 10) # 对每个噪声级别,尝试多次并记录预测改变的频率 pred_changes = [] # 创建一个函数来从特征到logits def features_to_logits(feats): # 这里取决于你的模型结构,需要相应调整 feats = feats.view(feats.size(0), -1) return model.fc(feats) for noise_std in noise_stds: changes = 0 for _ in range(num_trials): # 添加高斯噪声到特征 noise = torch.randn_like(features) * noise_std noisy_features = features + noise # 从特征计算logits noisy_logits = features_to_logits(noisy_features.unsqueeze(0)) noisy_pred = torch.argmax(noisy_logits, 1).item() # 检查预测是否改变 if noisy_pred != original_pred: changes += 1 # 计算该噪声级别下的预测改变比例 change_rate = changes / num_trials pred_changes.append(change_rate) # 如果预测改变率超过50%,停止尝试更大的噪声 if change_rate > 0.5: break # 寻找首次使预测改变率超过20%的噪声级别 threshold_idx = next((i for i, rate in enumerate(pred_changes) if rate >= 0.2), len(noise_stds) - 1) threshold_std = noise_stds[threshold_idx] # 将噪声阈值映射到硬度值 # 噪声越小,样本越容易被扰动,硬度越低 # 我们将噪声范围映射到硬度范围[0,10] max_std = noise_std_range[1] mapped_hardness = 10.0 * min(threshold_std, max_std) / max_std if debug: print(f"Original prediction: {original_pred}") print(f"Threshold noise std: {threshold_std:.4f}") print(f"Mapped hardness (gaussian features): {mapped_hardness:.4f}") return mapped_hardness, True # 方法4: 在特征上使用CW攻击计算hardness def compute_hardness_cw_features(model, inputs, feature_extractor, debug=True): """ 通过在特征空间上使用CW攻击来计算样本的硬度 Args: model: 模型 inputs: 输入样本 feature_extractor: 特征提取器 debug: 是否打印调试信息 Returns: hardness: 样本硬度值 """ model.eval() feature_extractor.eval() inputs = inputs.to(device) # 获取原始特征和预测 with torch.no_grad(): features, logits = feature_extractor(inputs) original_pred = torch.argmax(logits, 1) features = features.squeeze() # 创建一个特征到logits的模型包装器 class FeatureWrapper(nn.Module): def __init__(self, model): super().__init__() self.fc = model.fc def forward(self, x): x = x.view(x.size(0), -1) return self.fc(x) feature_model = FeatureWrapper(model).to(device) # 准备函数包装器 def model_fn(x): return feature_model(x) # 应用CW攻击到特征 try: if debug: print("Running CW attack on features with parameters:") print(f"- Binary search steps: 5") print(f"- Max iterations: 300") print(f"- Learning rate: 0.01") print(f"- Early stop: True") # 重塑特征形状以适应CW攻击函数 feature_input = features.unsqueeze(0) # 可能需要调整这些参数以适应特征空间 adv_features, l2_norms, success_mask = carlini_wagner_l2( model_fn=model_fn, x=feature_input, n_classes=logits.shape[1], y=original_pred, targeted=False, lr=0.01, # 特征空间可能需要更高的学习率 binary_search_steps=5, max_iterations=300, confidence=0, clip_min=float(feature_input.min()), clip_max=float(feature_input.max()), debug=debug, early_stop=True ) # 获取对抗特征的预测 with torch.no_grad(): adv_logits = feature_model(adv_features) adv_pred = torch.argmax(adv_logits, 1) # 攻击成功与否直接从success_mask获取 attack_success = success_mask.any().item() # 获取L2范数 l2_val = l2_norms[0].item() if l2_norms.numel() > 0 else 0.0 if debug: print(f"Attack result: {'SUCCESS' if attack_success else 'FAILURE'}") print(f"Original prediction: {original_pred.item()}") print(f"Adversarial prediction: {adv_pred.item()}") print(f"L2 perturbation norm in feature space: {l2_val:.4f}") if attack_success: # 根据特征空间的L2值范围来调整映射 # 对于特征空间,范围可能与图像空间不同 # 这里假设特征空间的L2范围为[0,2] feature_l2_max = 2.0 mapped_hardness = 10.0 * min(l2_val, feature_l2_max) / feature_l2_max if debug: print(f"Mapped hardness (CW features): {mapped_hardness:.4f}") return mapped_hardness, True else: # 攻击失败,表示样本非常稳定 if debug: print("Attack failed in feature space - using high hardness value 9.0") return 9.0, False except Exception as e: if debug: print(f"Error in feature CW attack: {e}") # 使用备用方法(基于logit gap) logits_tensor = torch.tensor(logits.cpu().numpy(), dtype=torch.float32) original_pred = torch.argmax(logits_tensor).item() # Calculate logit gap sorted_logits, _ = torch.sort(logits_tensor, descending=True) logit_gap = (sorted_logits[0][0] - sorted_logits[0][1]).item() # 如果攻击失败,使用logit gap作为硬度值的指标 logit_gap_score = 5.0 + 5.0 * (logit_gap / (logit_gap + 1.0)) if debug: print(f"Using fallback logit gap hardness due to error: {logit_gap_score:.4f}") return logit_gap_score, False # 计算ECE (Expected Calibration Error) def compute_ece(probs, labels, n_bins=15): """计算ECE (Expected Calibration Error)""" bin_boundaries = np.linspace(0, 1, n_bins + 1) bin_lowers = bin_boundaries[:-1] bin_uppers = bin_boundaries[1:] confidences = np.max(probs, axis=1) predictions = np.argmax(probs, axis=1) accuracies = (predictions == labels) ece = 0.0 for bin_lower, bin_upper in zip(bin_lowers, bin_uppers): in_bin = np.logical_and(confidences > bin_lower, confidences <= bin_upper) prop_in_bin = np.mean(in_bin) if prop_in_bin > 0: accuracy_in_bin = np.mean(accuracies[in_bin]) avg_confidence_in_bin = np.mean(confidences[in_bin]) ece += np.abs(avg_confidence_in_bin - accuracy_in_bin) * prop_in_bin return ece # Temperature Scaling class TemperatureScaling: """标准温度缩放校准方法""" def __init__(self, temp=1.0): self.temp = temp def fit(self, logits, labels): """通过最小化验证集上的NLL找到最优温度""" from scipy.optimize import minimize def objective(temp, logits, labels): scaled_logits = logits / temp probs = F.softmax(torch.tensor(scaled_logits), dim=1).numpy() nll = -np.mean(np.log(probs[np.arange(len(labels)), labels] + 1e-10)) return nll # 简单的参数寻优 res = minimize(lambda t: objective(t, logits, labels), x0=np.array([self.temp]), method='BFGS') self.temp = res.x[0] def calibrate(self, logits): """应用温度缩放到logits""" scaled_logits = logits / self.temp return F.softmax(torch.tensor(scaled_logits), dim=1).numpy() # 比较不同硬度计算方法的校准效果 def compare_hardness_methods(model, testloader, num_samples=50, run_methods=None): """ 比较不同硬度计算方法的校准效果 Args: model: 要评估的模型 testloader: 测试数据加载器 num_samples: 要评估的样本数量 run_methods: 要运行的方法列表,可选值:['cw_logits', 'gaussian_logits', 'gaussian_features', 'cw_features'] 如果为None,则运行所有方法 """ feature_extractor = get_feature_extractor(model) # 所有可用的方法 all_methods = { 'cw_logits': {'hardness_values': [], 'temps': [], 'func': compute_hardness_cw_logits}, 'gaussian_logits': {'hardness_values': [], 'temps': [], 'func': compute_hardness_gaussian_logits}, 'gaussian_features': {'hardness_values': [], 'temps': [], 'func': compute_hardness_gaussian_features}, 'cw_features': {'hardness_values': [], 'temps': [], 'func': compute_hardness_cw_features} } # 确定要运行的方法 if run_methods is None: # 如果未指定,运行所有方法 methods = all_methods method_names = list(all_methods.keys()) else: # 只保留指定的方法 methods = {method: all_methods[method] for method in run_methods if method in all_methods} method_names = run_methods if not methods: print("警告: 未指定有效的方法,将运行所有方法") methods = all_methods method_names = list(all_methods.keys()) else: print(f"将运行以下方法: {', '.join(method_names)}") all_logits = [] all_labels = [] # 收集样本和计算不同方法的硬度 print(f"Calculating hardness using different methods for {num_samples} samples...") for i, (inputs, labels) in enumerate(tqdm(testloader)): if i >= num_samples: break inputs = inputs.to(device) labels = labels.to(device) # 获取logits with torch.no_grad(): logits = model(inputs) all_logits.append(logits.cpu().numpy()) all_labels.append(labels.cpu().numpy()) print(f"\n------ Sample {i+1}/{num_samples} ------") # 运行每种指定的方法 for idx, method_name in enumerate(method_names): method_info = methods[method_name] func = method_info['func'] print(f"\nMethod {idx+1}: {method_name}") # 根据方法类型调用相应的函数 if method_name == 'cw_logits': hardness, _ = func(model, inputs, logits, debug=True) elif method_name == 'gaussian_logits': hardness, _ = func(model, inputs, debug=True) elif method_name in ['gaussian_features', 'cw_features']: hardness, _ = func(model, inputs, feature_extractor, debug=True) methods[method_name]['hardness_values'].append(hardness) print("----------------------------------------\n") # 整理收集的数据 all_logits = np.vstack(all_logits) all_labels = np.hstack(all_labels) # 计算硬度到温度的映射 for method_name, method_data in methods.items(): # 使用简单的线性映射:硬度越高,温度越高 hardness_temps = [0.5 + 1.5 * (h / 10.0) for h in method_data['hardness_values']] methods[method_name]['temps'] = hardness_temps # 评估校准效果 print("\nEvaluating calibration performance...") # 1. 未校准 uncal_probs = F.softmax(torch.tensor(all_logits), dim=1).numpy() uncal_ece = compute_ece(uncal_probs, all_labels) uncal_acc = np.mean(np.argmax(uncal_probs, axis=1) == all_labels) # 2. 标准温度缩放 ts = TemperatureScaling() ts.fit(all_logits, all_labels) ts_probs = ts.calibrate(all_logits) ts_ece = compute_ece(ts_probs, all_labels) ts_acc = np.mean(np.argmax(ts_probs, axis=1) == all_labels) # 3. 各种硬度方法的样本级温度缩放 results = { 'uncal': {'ece': uncal_ece, 'acc': uncal_acc}, 'ts': {'ece': ts_ece, 'acc': ts_acc, 'temp': ts.temp} } for method_name, method_data in methods.items(): hardness_temps = method_data['temps'] shats_probs = [] for i, logits in enumerate(all_logits): temp = hardness_temps[i] if i < len(hardness_temps) else 1.0 scaled_logits = logits / temp probs = F.softmax(torch.tensor(scaled_logits), dim=1).numpy() shats_probs.append(probs) shats_probs = np.vstack(shats_probs) shats_ece = compute_ece(shats_probs, all_labels) shats_acc = np.mean(np.argmax(shats_probs, axis=1) == all_labels) results[method_name] = { 'ece': shats_ece, 'acc': shats_acc, 'hardness_values': method_data['hardness_values'], 'temps': hardness_temps, 'avg_hardness': np.mean(method_data['hardness_values']), 'avg_temp': np.mean(hardness_temps) } # 打印结果 print("\nCalibration Results:") print(f"Number of samples: {len(all_labels)}") print(f"TS optimal temperature: {ts.temp:.4f}") print("\nMethod Avg Hardness Avg Temp Accuracy ECE") print("-" * 60) print(f"Uncal - - {uncal_acc:.4f} {uncal_ece:.4f}") print(f"TS - {ts.temp:.4f} {ts_acc:.4f} {ts_ece:.4f}") for method_name, method_results in results.items(): if method_name not in ['uncal', 'ts']: print(f"{method_name:<10} {method_results['avg_hardness']:.4f} {method_results['avg_temp']:.4f} {method_results['acc']:.4f} {method_results['ece']:.4f}") # 保存结果 save_path = os.path.join(TEST_RESULTS_DIR, "hardness_methods_comparison.json") with open(save_path, 'w') as f: json.dump(results, f, indent=4, default=float) print(f"\nResults saved to {save_path}") # 计算不同硬度方法之间的相关性 print("\nCalculating correlations between hardness methods...") correlations = {} if len(methods) > 1: # 只有当有多个方法时才计算相关性 method_names = list(methods.keys()) for i, method1 in enumerate(method_names): for method2 in method_names[i+1:]: h1 = methods[method1]['hardness_values'] h2 = methods[method2]['hardness_values'] # 确保长度一致 min_len = min(len(h1), len(h2)) if min_len > 0: corr = np.corrcoef(h1[:min_len], h2[:min_len])[0, 1] correlations[f"{method1}_vs_{method2}"] = corr print(f"Correlation between {method1} and {method2}: {corr:.4f}") else: print("只有一种方法被运行,无法计算相关性") # 将相关性也保存到结果中 results['correlations'] = correlations # 更新保存的结果 with open(save_path, 'w') as f: json.dump(results, f, indent=4, default=float) return results if __name__ == "__main__": print("Loading CIFAR-10 dataset...") testloader, _ = load_cifar10(batch_size=1) print("Loading model...") model = load_model() # 指定要运行的方法 (可选值: 'cw_logits', 'gaussian_logits', 'gaussian_features', 'cw_features') # 设置为None将运行所有方法 run_methods = ['gaussian_logits', 'gaussian_features'] # 示例:只运行基于高斯噪声的方法 print("\n--- Comparing different hardness calculation methods ---") start_time = time.time() results = compare_hardness_methods(model, testloader, num_samples=20, run_methods=run_methods) end_time = time.time() print(f"Total execution time: {(end_time - start_time) / 60:.2f} minutes") print(f"Results saved to {TEST_RESULTS_DIR}/hardness_methods_comparison.json")