File size: 10,182 Bytes
6033337 | 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 | import os
import argparse
import torch
from torch.utils.data import DataLoader
import pandas as pd
import numpy as np
from sklearn.metrics import accuracy_score, roc_auc_score, average_precision_score, precision_recall_curve
import json
from datetime import datetime
from dataset import FeatureDataset
from model import FusionModel
def filter_metadata_for_testing(metadata_path, test_methods=['SadTalk', 'EDTalk', 'Float']):
"""Filter metadata to include only test methods and real data"""
metadata = pd.read_csv(metadata_path)
# Include real data and test methods
filtered_metadata = metadata[
metadata['path'].str.contains('real', case=False) |
metadata['path'].str.contains('|'.join(test_methods))
]
return filtered_metadata
def get_eval_args():
parser = argparse.ArgumentParser(description='Evaluate Diffusion-Only Model')
# Model checkpoint
parser.add_argument('--checkpoint_path', type=str, required=True,
help='Path to the trained model checkpoint (.pt file)')
# Data paths
parser.add_argument('--features_path', type=str, required=True,
help='Path to feature data directory')
parser.add_argument('--metadata', type=str, required=True,
help='Path to test metadata file')
# Model configuration
parser.add_argument('--batch_size', type=int, default=1024,
help='Batch size for evaluation')
parser.add_argument('--tau', type=int, default=15,
help='Temporal window size')
return parser.parse_args()
def calculate_acc_at_eer(labels, scores):
"""Calculate accuracy at Equal Error Rate (EER)"""
from sklearn.metrics import roc_curve
fpr, tpr, thresholds = roc_curve(labels, scores)
fnr = 1 - tpr
# Find threshold where FPR = FNR (EER)
eer_threshold_idx = np.nanargmin(np.abs(fpr - fnr))
eer_threshold = thresholds[eer_threshold_idx]
# Calculate accuracy at EER threshold
binary_predictions = (scores >= eer_threshold).astype(int)
acc_at_eer = accuracy_score(labels, binary_predictions)
return acc_at_eer, eer_threshold
def save_predictions_to_csv(video_names, predictions, labels, output_path):
"""Save individual video predictions to CSV file"""
results_df = pd.DataFrame({
'video_name': video_names,
'prediction_score': predictions,
'predicted_label': (predictions > 0).astype(int),
'true_label': labels,
'correct': ((predictions > 0).astype(int) == labels).astype(int)
})
results_df.to_csv(output_path, index=False)
print(f"Predictions saved to: {output_path}")
def main():
args = get_eval_args()
print("Evaluating Diffusion-Only Model")
print(f"Checkpoint: {args.checkpoint_path}")
print(f"Features: {args.features_path}")
print(f"Metadata: {args.metadata}")
print(f"Batch size: {args.batch_size}")
# Set device
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# Define test methods
test_methods = ['SadTalk', 'EDTalk', 'Float']
print(f"Testing on methods: {test_methods}")
# Load and filter test metadata
test_metadata = filter_metadata_for_testing(args.metadata, test_methods)
print(f"Test dataset size (filtered): {len(test_metadata)}")
# Create test dataset
# Save filtered metadata to temporary file
temp_metadata_path = "/tmp/test_metadata_filtered.csv"
test_metadata.to_csv(temp_metadata_path, index=False)
test_dataset = FeatureDataset(
temp_metadata_path, args.features_path, tau=args.tau
)
# Create data loader
test_loader = DataLoader(
test_dataset, batch_size=args.batch_size, shuffle=False, num_workers=4
)
# Load model
model = FusionModel().to(device)
# Load checkpoint
if os.path.exists(args.checkpoint_path):
checkpoint = torch.load(args.checkpoint_path, map_location=device)
model.load_state_dict(checkpoint['state_dict'])
print(f"Loaded model from {args.checkpoint_path}")
# 兼容新旧两种 ckpt:
# 旧版 train_diffusion_only.py 存了 'best_val_loss'
# 新版 train_diffusion_only.py 存了 'metrics' dict(含 val_loss / val_auc 等)
if 'best_val_loss' in checkpoint:
print(f"Best validation loss: {checkpoint['best_val_loss']:.6f}")
elif 'metrics' in checkpoint:
m = checkpoint['metrics']
print(f"Saved metrics: epoch={checkpoint.get('epoch')} "
f"val_loss={m.get('val_loss', float('nan')):.6f} "
f"val_auc={m.get('val_auc', float('nan')):.4f}")
else:
print(f"Checkpoint not found at {args.checkpoint_path}")
return
# Enable multi-GPU if available (commented out for stability)
# if torch.cuda.device_count() > 1:
# print(f"Using {torch.cuda.device_count()} GPUs for evaluation")
# model = torch.nn.DataParallel(model)
print(f"Using single GPU for evaluation")
model.eval()
# Evaluation
total_loss = 0
total_samples = 0
logsoftmax = torch.nn.LogSoftmax(dim=1)
# For ACC and AUC calculation and per-video results
all_predictions = []
all_labels = []
all_video_names = []
with torch.no_grad():
for batch in test_loader:
visual_frame, audio_window, video_name, video_frames, labels = batch
current_batch_size = visual_frame.size()[0]
visual_frame = visual_frame.to(device)
audio_window = audio_window.to(device)
# Repeat video frame to match audio frames (2*tau+1 times)
visual_central_frame = visual_frame.unsqueeze(1).repeat(1, 2 * args.tau + 1, 1)
outputs = model(visual_central_frame, audio_window)
outputs = outputs.squeeze()
synchronization_scores = logsoftmax(outputs)[:, args.tau]
loss = -torch.sum(synchronization_scores)
total_loss += loss.item()
total_samples += current_batch_size
# Collect predictions, labels, and video names for detailed analysis
predictions = synchronization_scores.detach().cpu().numpy()
all_predictions.extend(predictions)
batch_labels = labels.detach().cpu().numpy()
all_labels.extend(batch_labels)
# Collect video names
all_video_names.extend(video_name)
avg_loss = total_loss / total_samples
print(f"Test Loss: {avg_loss:.6f}")
# Calculate comprehensive evaluation metrics
if len(all_predictions) > 0 and len(all_labels) > 0:
all_predictions = np.array(all_predictions)
all_labels = np.array(all_labels)
# Convert synchronization scores to binary predictions (threshold at 0)
binary_predictions = (all_predictions > 0).astype(int)
# Calculate Accuracy
accuracy = accuracy_score(all_labels, binary_predictions)
print(f"Accuracy (ACC): {accuracy:.4f}")
# Calculate AUC
try:
auc = roc_auc_score(all_labels, all_predictions)
print(f"AUC Score: {auc:.4f}")
except ValueError as e:
print(f"AUC calculation failed: {e}")
auc = 0.0
# Calculate Average Precision (AP)
try:
ap = average_precision_score(all_labels, all_predictions)
print(f"Average Precision (AP): {ap:.4f}")
except ValueError as e:
print(f"AP calculation failed: {e}")
ap = 0.0
# Calculate Accuracy at EER
try:
acc_at_eer, eer_threshold = calculate_acc_at_eer(all_labels, all_predictions)
print(f"Accuracy at EER: {acc_at_eer:.4f} (Threshold: {eer_threshold:.4f})")
except Exception as e:
print(f"ACC@EER calculation failed: {e}")
acc_at_eer = 0.0
eer_threshold = 0.0
# Print class distribution
unique, counts = np.unique(all_labels, return_counts=True)
print(f"Class distribution: {dict(zip(unique, counts))}")
print(f"Real samples: {counts[0] if 0 in unique else 0}, Fake samples: {counts[1] if 1 in unique else 0}")
# Save detailed predictions to CSV
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
checkpoint_name = os.path.basename(args.checkpoint_path).replace('.pt', '')
predictions_csv_path = f"predictions_{checkpoint_name}_{timestamp}.csv"
save_predictions_to_csv(all_video_names, all_predictions, all_labels, predictions_csv_path)
# Save evaluation summary to JSON
eval_summary = {
'checkpoint_path': args.checkpoint_path,
'test_metadata': args.metadata,
'test_samples': int(len(all_predictions)),
'real_samples': int(counts[0] if 0 in unique else 0),
'fake_samples': int(counts[1] if 1 in unique else 0),
'test_loss': float(avg_loss),
'accuracy': float(accuracy),
'auc': float(auc),
'average_precision': float(ap),
'acc_at_eer': float(acc_at_eer),
'eer_threshold': float(eer_threshold),
'predictions_file': predictions_csv_path,
'evaluation_time': datetime.now().isoformat(),
'test_methods': test_methods
}
summary_json_path = f"eval_summary_{checkpoint_name}_{timestamp}.json"
with open(summary_json_path, 'w') as f:
json.dump(eval_summary, f, indent=2)
print(f"Evaluation summary saved to: {summary_json_path}")
print("\n=== Evaluation Summary ===")
print(f"Test Loss: {avg_loss:.6f}")
print(f"ACC: {accuracy:.4f}")
print(f"AUC: {auc:.4f}")
print(f"AP: {ap:.4f}")
print(f"ACC@EER: {acc_at_eer:.4f}")
print(f"Total samples: {len(all_predictions)}")
if __name__ == "__main__":
main() |