Files
MA_Param_Tuning/reID_param_tuning.py
T

117 lines
3.6 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(steps=0.05):
""" Value Range in [0:1] with stepsize 0.05 """
values = np.arange(0.0, 1.0 + 1e-9, steps)
return np.round(values, 8)
def grid_search(train_pairs, alphas=None, thresholds=None):
""" Find best feature weights and threshold on training pairings """
if alphas is None:
alphas = _range()
if thresholds is None:
thresholds = _range()
cosine_similarities, bhattarcharyya_coefficients, labels = calc_features(train_pairs)
best = {"alpha": None, "beta": None, "threshold": None, "f1": -1.0}
for alpha in alphas:
beta = 1 - alpha
scores = alpha * cosine_similarities + beta * bhattarcharyya_coefficients
for thresh in thresholds:
predictions = (scores >= thresh).astype(int)
f1 = f1_score(labels, predictions, zero_division=0)
if f1 > best["f1"]:
best = {"alpha": float(alpha), "beta": float(beta), "threshold": float(thresh), "f1": float(f1)}
return best
def evaluate(test_pairs, alpha, beta, threshold):
""" Calculate Accuracy + f1 Score on test pairings """
cosine_similarities, bhattarcharyya_coefficients, labels = calc_features(test_pairs)
scores = alpha * cosine_similarities + beta * bhattarcharyya_coefficients
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 """
# TODO: COS_SIM immer 0=<1
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"Best 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"])
print(f'Test accuracy: {accuracy:.2f}, F1 score: {f1:.2f}')
out_dir = Path("results")
out_dir.mkdir(parents=True, exist_ok=True)
out_path = out_dir / f"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),
"train_f1": round(best["f1"], 2),
"test_accuracy": round(accuracy, 2),
"test_f1": round(f1, 2),
}, f, indent=4)