Files
MA_Param_Tuning/reID_param_tuning.py
T

164 lines
5.7 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.01):
""" Value Range in [0:1] with stepsize 0.01 """
values = np.arange(0.0, 1.0 + 1e-9, steps)
return np.round(values, 8)
def _pow_range(steps=0.01):
""" 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, trained_variables, 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()
# if thresholds is None:
# thresholds = _range()
if p_values is None:
p_values = _pow_range()
if q_values is None:
q_values = _pow_range()
cosine_similarities, bhattarcharyya_coefficients, labels = calc_features(train_pairs)
# Pre-Calculate exponents for runtime optimization
# cos_p_list = [np.power(cosine_similarities, float(p)) for p in p_values]
# bh_q_list = [np.power(bhattarcharyya_coefficients, float(q)) for q in q_values]
best = {"alpha": None, "beta": None, "threshold": None, "p": None, "q": None, "f1": -1.0}
# for i_p, p in enumerate(p_values):
# cos_p = cos_p_list[i_p]
# for i_q, q in enumerate(q_values):
# bh_q = bh_q_list[i_q]
#
# delta = cos_p - bh_q
# for alpha in tqdm(alphas): # TODO: read alpha, beta, thresh from jsons and only try p,q optim!
for p in tqdm(p_values):
for q in tqdm(q_values):
beta = trained_variables["beta"] #1.0 - alpha
scores = trained_variables["alpha"] * (cosine_similarities ** p) + beta * (bhattarcharyya_coefficients ** q)
#for threshold in thresholds:
predictions = (scores >= trained_variables["threshold"]).astype(int)
best_f1 = f1_score(labels, predictions, zero_division=0)
if best_f1 > best["f1"]:
best.update({
"alpha": trained_variables["alpha"],
"beta": trained_variables["beta"],
"threshold": trained_variables["threshold"],
"p": float(p),
"q": float(q),
"f1": best_f1
})
# 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, 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 scene_ids:
train_pairs = load_pairs(f"splits/{scene_id}/train_pairs.csv")
with open(f'results/training_{scene_id}.json', 'r') as f:
data = json.load(f)
trained_variables = dict(list(data.items()))
best = grid_search(train_pairs, trained_variables)
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("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)