File size: 7,478 Bytes
b58079c | 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 | 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 函数,处理包含文件路径的批次数据"""
# batch 是一个列表,每个元素是 (img, crops, label, img_path)
imgs = torch.stack([item[0] for item in batch])
# 处理 crops(列表的列表):crops[scale_idx][sample_idx] 是一个 tensor
# 需要将其转换为:crops[scale_idx] 是一个 tensor,形状为 (batch_size, 3, 224, 224)
num_scales = len(batch[0][1]) # 尺度数(通常是3个:1.0x, 0.65x, 0.45x)
num_crops_per_scale = len(batch[0][1][0]) # 每个尺度的 crop 数量(通常是5)
crops = []
for scale_idx in range(num_scales):
scale_crops = []
for crop_idx in range(num_crops_per_scale):
# 收集 batch 中所有样本在这个尺度和 crop 索引下的 tensor
crop_tensors = [batch[sample_idx][1][scale_idx][crop_idx] for sample_idx in range(len(batch))]
# 堆叠成一个 batch tensor
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) 和对应的阈值"""
# 获取 ROC 曲线上的点
fpr, tpr, thresholds = roc_curve(y_true, y_pred_proba)
fnr = 1 - tpr
# 找到 FPR 和 FNR 差异最小的点,即为 EER
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:
# 解包数据:现在使用 custom_collate,返回 (imgs, crops, labels, img_paths)
imgs, crops, labels, batch_paths = batch_data
# 保存文件路径
img_paths.extend(batch_paths)
img_tens = imgs.to(device)
# crops 现在是正确格式:crops[scale_idx][crop_idx] 是 (batch_size, 3, 224, 224)
# 只需要将每个 tensor 移动到 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) # 二值化用于 acc 计算
# Get AP (使用连续概率值)
ap = average_precision_score(y_true, y_pred_proba)
# Get AUC (使用连续概率值)
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 和 ACC@EER
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, # 改为 False 以保持顺序
collate_fn=custom_collate # 使用自定义 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}")
# 保存结果到 CSV
if opt.output_csv is not None:
print(f"Saving inference results to {opt.output_csv}...")
# 计算 EER 和对应的阈值
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)
# 保存到 CSV
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}")
|