Files
MA_Param_Tuning/reID_param_tuning.py
2025-09-13 11:31:21 +02:00

155 lines
5.1 KiB
Python

import json
from pathlib import Path
import numpy as np
import pandas as pd
from sklearn.metrics import f1_score, accuracy_score
from tqdm import tqdm
import utils
def load_pairs(path):
""" Data Loader """
df = pd.read_csv(path)
pairs = []
for _, row in df.iterrows():
pairs.append({
"clip1": np.array(eval(row["clip1"])),
"hist1": np.array(eval(row["hist1"])),
"clip2": np.array(eval(row["clip2"])),
"hist2": np.array(eval(row["hist2"])),
"label": int(row["label"])
})
return pairs
def _range(start=0.0, steps=0.01):
""" Value Range in [0:1] with default stepsize 0.01 """
values = np.arange(start, 1.0 + 1e-9, steps)
return np.round(values, 8)
def _pow_range(steps=0.05):
""" Value Range in [1:1.5] with stepsize 0.05 """
values = np.arange(1.0, 1.5 + 1e-9, steps)
return np.round(values, 8)
def grid_search(train_pairs, alphas=None, thresholds=None, p_values=None, q_values=None):
""" Find best feature weights and threshold on training pairings """
if alphas is None:
alphas = _range(start=0.30, steps=0.02)
if thresholds is None:
thresholds = _range(start=0.70, steps=0.02)
if p_values is None:
p_values = _pow_range(steps=0.02)
if q_values is None:
q_values = _pow_range(steps=0.02)
cosine_similarities, bhattarcharyya_coefficients, labels = calc_features(train_pairs)
best = {"alpha": None, "beta": None, "threshold": None, "p": None, "q": None, "f1": -1.0}
results = []
for alpha in tqdm(alphas):
for p in p_values:
for q in q_values:
beta = 1.0 - alpha
scores = alpha * (cosine_similarities ** p) + beta * (bhattarcharyya_coefficients ** q)
best_f1_combo = -1
best_threshold_combo = None
for threshold in thresholds:
predictions = (scores >= threshold).astype(int)
f1 = f1_score(labels, predictions, zero_division=0)
if f1 > best_f1_combo:
best_f1_combo = float(f1)
best_threshold_combo = float(threshold)
if f1 > best["f1"]:
best.update({
"alpha": float(alpha),
"beta": float(beta),
"threshold": float(threshold),
"p": float(p),
"q": float(q),
"f1": float(f1)
})
results.append({
"alpha": float(alpha),
"beta": float(beta),
"p": float(p),
"q": float(q),
"best_threshold": float(best_threshold_combo),
"best_f1": float(best_f1_combo)
})
return best, results
def evaluate(test_pairs, alpha, beta, threshold, p, q):
""" Calculate Accuracy + f1 Score on test pairings """
cosine_similarities, bhattarcharyya_coefficients, labels = calc_features(test_pairs)
scores = alpha * (cosine_similarities ** p) + beta * (bhattarcharyya_coefficients ** q)
predictions = (scores >= threshold).astype(int)
accuracy = accuracy_score(labels, predictions)
f1 = f1_score(labels, predictions, zero_division=0)
return accuracy, f1
def calc_features(pairs):
""" Re-Identification Features per object Pairing """
cos_sims = np.array([np.maximum(0.0, utils.cosine_similarity(p["clip1"], p["clip2"])) for p in pairs], dtype=float)
bhatts = np.array([utils.bhattarcharyya_coefficient(p["hist1"], p["hist2"]) for p in pairs], dtype=float)
labels = np.array([p["label"] for p in pairs], dtype=int)
return cos_sims, bhatts, labels
if __name__ == "__main__":
scene_ids = [
"17DRP5sb8fy",
"2t7WUuJeko7",
"PX4nDJXEHrG",
"q9vSo1VnCiC",
"Vvot9Ly1tCj",
"zsNo4HB9uLZ"
]
for scene_id in tqdm(scene_ids):
train_pairs = load_pairs(f"splits/{scene_id}/train_pairs.csv")
best = grid_search(train_pairs)
print(f"\nBest training combination: {best}")
test_pairs = load_pairs(f"splits/{scene_id}/test_pairs.csv")
accuracy, f1 = evaluate(test_pairs, best["alpha"], best["beta"], best["threshold"], best["p"], best["q"])
print(f'\nTest accuracy: {accuracy:.2f}, F1 score: {f1:.2f}')
out_dir = Path("optimization_results")
out_dir.mkdir(parents=True, exist_ok=True)
out_path = out_dir / f"pq_training_{scene_id}.json"
with open(out_path, "w", encoding="utf-8") as f:
json.dump(
{
"alpha": round(best["alpha"], 2),
"beta": round(best["beta"], 2),
"threshold": round(best["threshold"], 2),
"p": round(best["p"], 2),
"q": round(best["q"], 2),
"train_f1": round(best["f1"], 2),
"test_accuracy": round(accuracy, 2),
"test_f1": round(f1, 2),
}, f, indent=4)