| import argparse |
| import torch |
| import numpy as np |
| import pandas as pd |
| from data import AVLip |
| import torch.utils.data |
| from models import build_model |
| from sklearn.metrics import average_precision_score, confusion_matrix, accuracy_score, roc_auc_score, roc_curve |
| import os |
|
|
|
|
| def custom_collate(batch): |
| """自定义 collate 函数,处理包含文件路径的批次数据""" |
| |
| imgs = torch.stack([item[0] for item in batch]) |
| |
| |
| |
| num_scales = len(batch[0][1]) |
| num_crops_per_scale = len(batch[0][1][0]) |
| |
| crops = [] |
| for scale_idx in range(num_scales): |
| scale_crops = [] |
| for crop_idx in range(num_crops_per_scale): |
| |
| crop_tensors = [batch[sample_idx][1][scale_idx][crop_idx] for sample_idx in range(len(batch))] |
| |
| crop_batch = torch.stack(crop_tensors) |
| scale_crops.append(crop_batch) |
| crops.append(scale_crops) |
| |
| labels = torch.tensor([item[2] for item in batch]) |
| img_paths = [item[3] for item in batch] |
| |
| return imgs, crops, labels, img_paths |
|
|
|
|
| def compute_eer(y_true, y_pred_proba): |
| """计算 EER (Equal Error Rate) 和对应的阈值""" |
| |
| fpr, tpr, thresholds = roc_curve(y_true, y_pred_proba) |
| fnr = 1 - tpr |
| |
| |
| eer_threshold = thresholds[np.nanargmin(np.abs(fpr - fnr))] |
| eer = fpr[np.nanargmin(np.abs(fpr - fnr))] |
| |
| return eer, eer_threshold |
|
|
|
|
| def compute_acc_at_eer(y_true, y_pred_proba, eer_threshold): |
| """计算在 EER 阈值下的准确率""" |
| y_pred_binary = (y_pred_proba >= eer_threshold).astype(int) |
| acc = accuracy_score(y_true, y_pred_binary) |
| return acc |
|
|
|
|
| def validate(model, loader, gpu_id): |
| print("validating...") |
| device = torch.device(f"cuda:{gpu_id[0]}" if torch.cuda.is_available() else "cpu") |
| with torch.no_grad(): |
| y_true, y_pred = [], [] |
| img_paths = [] |
| for batch_data in loader: |
| |
| imgs, crops, labels, batch_paths = batch_data |
| |
| |
| img_paths.extend(batch_paths) |
| |
| img_tens = imgs.to(device) |
| |
| |
| crops_tens = [[t.to(device) for t in scale_crops] for scale_crops in crops] |
| features = model.get_features(img_tens).to(device) |
|
|
| y_pred.extend(model(crops_tens, features)[0].sigmoid().flatten().tolist()) |
| y_true.extend(labels.flatten().tolist()) |
| y_true = np.array(y_true) |
| y_pred_proba = np.array(y_pred) |
| y_pred_binary = np.where(y_pred_proba >= 0.5, 1, 0) |
|
|
| |
| ap = average_precision_score(y_true, y_pred_proba) |
| |
| |
| auc = roc_auc_score(y_true, y_pred_proba) |
| |
| |
| cm = confusion_matrix(y_true, y_pred_binary) |
| tp, fn, fp, tn = cm.ravel() |
| fnr = fn / (fn + tp) |
| fpr = fp / (fp + tn) |
| acc = accuracy_score(y_true, y_pred_binary) |
| |
| |
| eer, eer_threshold = compute_eer(y_true, y_pred_proba) |
| acc_at_eer = compute_acc_at_eer(y_true, y_pred_proba, eer_threshold) |
| |
| return acc, ap, auc, fpr, fnr, eer, acc_at_eer, y_true, y_pred, img_paths |
|
|
|
|
| if __name__ == "__main__": |
| parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) |
| parser.add_argument("--real_list_path", type=str, default="./datasets/val/0_real") |
| parser.add_argument("--fake_list_path", type=str, default="./datasets/val/1_fake") |
| parser.add_argument("--max_sample", type=int, default=1000, help="max number of validate samples") |
| parser.add_argument("--batch_size", type=int, default=10) |
| parser.add_argument("--data_label", type=str, default="val") |
| parser.add_argument("--arch", type=str, default="CLIP:ViT-L/14") |
| parser.add_argument("--ckpt", type=str, default="./checkpoints/ckpt.pth") |
| parser.add_argument("--gpu", type=int, default=0) |
| parser.add_argument("--output_csv", type=str, default=None, help="Path to save inference results as CSV") |
|
|
| opt = parser.parse_args() |
|
|
| device = torch.device(f"cuda:{opt.gpu}" if torch.cuda.is_available() else "cpu") |
| print(f"Using cuda {opt.gpu} for inference.") |
|
|
| model = build_model(opt.arch) |
| state_dict = torch.load(opt.ckpt, map_location="cpu") |
| model.load_state_dict(state_dict["model"]) |
| print("Model loaded.") |
| model.eval() |
| model.to(device) |
|
|
| dataset = AVLip(opt) |
| loader = data_loader = torch.utils.data.DataLoader( |
| dataset, batch_size=opt.batch_size, shuffle=False, |
| collate_fn=custom_collate |
| ) |
| acc, ap, auc, fpr, fnr, eer, acc_at_eer, y_true, y_pred, img_paths = validate(model, loader, gpu_id=[opt.gpu]) |
| print(f"acc: {acc} ap: {ap} auc: {auc} fpr: {fpr} fnr: {fnr} eer: {eer} acc@eer: {acc_at_eer}") |
| |
| |
| if opt.output_csv is not None: |
| print(f"Saving inference results to {opt.output_csv}...") |
| |
| |
| eer, eer_threshold = compute_eer(np.array(y_true), np.array(y_pred)) |
| acc_at_eer = compute_acc_at_eer(np.array(y_true), np.array(y_pred), eer_threshold) |
| |
| print(f"EER: {eer}, EER threshold: {eer_threshold}, ACC@EER: {acc_at_eer}") |
| |
| |
| results = [] |
| y_pred_proba = np.array(y_pred) |
| y_pred_binary = np.where(y_pred_proba >= 0.5, 1, 0) |
| y_pred_at_eer = (y_pred_proba >= eer_threshold).astype(int) |
| |
| for i in range(len(y_true)): |
| result_dict = { |
| 'img_path': img_paths[i] if i < len(img_paths) else f'sample_{i}', |
| 'true_label': int(y_true[i]), |
| 'pred_prob': float(y_pred_proba[i]), |
| 'pred_label_05': int(y_pred_binary[i]), |
| 'pred_label_eer': int(y_pred_at_eer[i]) |
| } |
| results.append(result_dict) |
| |
| |
| df = pd.DataFrame(results) |
| df.to_csv(opt.output_csv, index=False) |
| print(f"Results saved to {opt.output_csv}") |
| |
| |
| summary_path = opt.output_csv.replace('.csv', '_summary.csv') |
| summary = { |
| 'metric': ['acc', 'ap', 'auc', 'fpr', 'fnr', 'eer', 'acc_at_eer', 'eer_threshold'], |
| 'value': [acc, ap, auc, fpr, fnr, eer, acc_at_eer, eer_threshold] |
| } |
| df_summary = pd.DataFrame(summary) |
| df_summary.to_csv(summary_path, index=False) |
| print(f"Summary saved to {summary_path}") |
|
|