369 lines
13 KiB
Python
369 lines
13 KiB
Python
import json
|
|
import os
|
|
import statistics
|
|
from pathlib import Path
|
|
|
|
import numpy as np
|
|
import pandas as pd
|
|
from matplotlib import pyplot as plt
|
|
from sklearn.metrics import f1_score
|
|
from tqdm import tqdm
|
|
|
|
import utils
|
|
|
|
OVERLAP_THRESHOLD = 0.8
|
|
|
|
def load_data(path):
|
|
objects, runtimes = [], []
|
|
for _, row in pd.read_json(path).iterrows():
|
|
objects.append(row["objects"])
|
|
# runtimes.append(row["run_time"])
|
|
|
|
return objects #, runtimes
|
|
|
|
|
|
def calculate_metrics(recordings, ground_truth):
|
|
"""
|
|
Probably use this one.
|
|
TODO: Better commentary!
|
|
:param recordings:
|
|
:param ground_truth:
|
|
:return:
|
|
"""
|
|
R, G = len(recordings), len(ground_truth)
|
|
|
|
# candidate pairs
|
|
candidate_pairs = []
|
|
for i, rec in enumerate(recordings):
|
|
for j, gt in enumerate(ground_truth):
|
|
if utils.calculate_bounding_box_overlap(rec['bounding_box'], gt['bounding_box'], OVERLAP_THRESHOLD):
|
|
ov = utils.overlap_volume(rec['bounding_box'], gt['bounding_box'])
|
|
candidate_pairs.append((i, j, ov))
|
|
|
|
# greedy one-to-one
|
|
candidate_pairs.sort(key=lambda x: x[2], reverse=True)
|
|
rec_assigned, gt_assigned, assigned_pairs = set(), set(), []
|
|
for r_idx, g_idx, ov in candidate_pairs:
|
|
if (r_idx not in rec_assigned) and (g_idx not in gt_assigned):
|
|
rec_assigned.add(r_idx)
|
|
gt_assigned.add(g_idx)
|
|
assigned_pairs.append((r_idx, g_idx, ov))
|
|
|
|
assigned_correct = [(r, g, ov) for (r, g, ov) in assigned_pairs if calculate_percentage_correct(recordings[r], ground_truth[g])]
|
|
|
|
TP, FP = 0, 0
|
|
for r_idx, g_idx, _ in assigned_pairs:
|
|
if recordings[r_idx]['class_id'] == ground_truth[g_idx]['class_id']:
|
|
TP += 1
|
|
else:
|
|
FP += 1
|
|
FN = G - len(assigned_pairs)
|
|
|
|
y_true, y_pred = [], []
|
|
for g_idx in range(G):
|
|
if g_idx in [g for (_, g, _) in assigned_pairs]:
|
|
if any(recordings[r]['class_id'] == ground_truth[g_idx]['class_id'] for r, g, _ in assigned_pairs if g == g_idx):
|
|
y_true.append(1)
|
|
y_pred.append(1)
|
|
else:
|
|
y_true.append(1)
|
|
y_pred.append(0)
|
|
else:
|
|
y_true.append(1)
|
|
y_pred.append(0)
|
|
|
|
for r_idx in range(R):
|
|
if r_idx not in [r for (r, _, _) in assigned_pairs]:
|
|
y_true.append(0)
|
|
y_pred.append(1)
|
|
|
|
f1 = f1_score(y_true, y_pred, zero_division=0)
|
|
|
|
found = len(set([g for (_, g, _) in assigned_pairs]))
|
|
correct = TP
|
|
found_pct = (found / G) if G > 0 else 0.0
|
|
correct_pct = (correct / found) if found > 0 else 0.0
|
|
|
|
return {
|
|
'f1_score': float(f1),
|
|
'TP': TP, 'FP': FP, 'FN': FN,
|
|
'found': found,
|
|
'found_pct': round(found_pct, 4),
|
|
'correct': correct,
|
|
'correct_pct': round(correct_pct, 4)
|
|
}
|
|
|
|
|
|
def calculate_percentage_correct(recording, ground_truth):
|
|
if recording['class_id'] == ground_truth['class_id']:
|
|
return True
|
|
return False
|
|
|
|
|
|
def plot_barred_results(tp, fp, fn, recording_id, avg=True):
|
|
prefix = recording_id.split("_", 1)[0]
|
|
suffix = recording_id.split("_", 1)[1]
|
|
if suffix.endswith("_objects"):
|
|
suffix = suffix[:-len("_objects")]
|
|
|
|
folder = os.path.join("experiment_results/metrics/bar_plots", suffix)
|
|
os.makedirs(folder, exist_ok=True)
|
|
|
|
filename = f"{prefix}_{'barredResults_avg_' if avg else 'barredResults_best_'}.png"
|
|
|
|
plt.figure(figsize=(4, 4))
|
|
plt.bar(['TP', 'FP', 'FN'], [tp, fp, fn], color=['green', 'red', 'blue'])
|
|
plt.title(f'Matches for {prefix}')
|
|
plt.ylabel('Amount')
|
|
|
|
plt.tight_layout()
|
|
|
|
plt.savefig(os.path.join(folder, filename))
|
|
plt.close()
|
|
|
|
|
|
def plot_percentages(pct_found, pct_correct, recording_id, avg=True):
|
|
prefix = recording_id.split("_", 1)[0]
|
|
suffix = recording_id.split("_", 1)[1]
|
|
if suffix.endswith("_objects"):
|
|
suffix = suffix[:-len("_objects")]
|
|
|
|
folder = os.path.join("experiment_results/metrics/percentages_plots", suffix)
|
|
os.makedirs(folder, exist_ok=True)
|
|
|
|
filename = f"{prefix}_{'percentageResults_avg_' if avg else 'percentageResults_best_'}.png"
|
|
|
|
plt.figure(figsize=(6, 4))
|
|
labels = ['Found %', 'Correct %']
|
|
values = [pct_found * 100, pct_correct * 100]
|
|
plt.bar(labels, values, color=['purple', 'green'])
|
|
plt.title(f'Percentages for {prefix}')
|
|
plt.ylabel('Percentage (%)')
|
|
plt.ylim(0, 100)
|
|
|
|
plt.tight_layout()
|
|
|
|
plt.savefig(os.path.join(folder, filename))
|
|
plt.close()
|
|
|
|
|
|
def plot_confusion_matrix(tp, fp, fn, recording_id, avg=True):
|
|
prefix = recording_id.split("_", 1)[0]
|
|
suffix = recording_id.split("_", 1)[1]
|
|
if suffix.endswith("_objects"):
|
|
suffix = suffix[:-len("_objects")]
|
|
|
|
folder = os.path.join("experiment_results/metrics/confusionMatrix_plots", suffix)
|
|
os.makedirs(folder, exist_ok=True)
|
|
|
|
filename = f"{prefix}_{'confusionMatrixResults_avg_' if avg else 'confusionMatrixResults_best_'}.png"
|
|
|
|
matrix = np.array([[tp, fn], [fp, 0]])
|
|
labels = [['TP', 'FN'], ['FP', 'TN']]
|
|
|
|
fig, ax = plt.subplots(figsize=(5, 4))
|
|
im = ax.imshow(matrix, cmap='Blues')
|
|
|
|
ax.set_xticks([0, 1])
|
|
ax.set_xticklabels(['Positive (Pred)', 'Negative (Pred)'])
|
|
|
|
ax.set_yticks([0, 1])
|
|
ax.set_yticklabels(['Positive (GT)', 'Negative (GT)'])
|
|
|
|
ax.set_title(f'Confusion matrix for {prefix}')
|
|
|
|
for i in range(matrix.shape[0]):
|
|
for j in range(matrix.shape[1]):
|
|
ax.text(j, i, f'{labels[i][j]}\n{matrix[i, j]}', ha='center', va='center', color='black')
|
|
|
|
plt.colorbar(im, ax=ax)
|
|
|
|
plt.tight_layout()
|
|
|
|
plt.savefig(os.path.join(folder, filename))
|
|
plt.close()
|
|
|
|
|
|
def plot_all(_results, recording_id, avg=True):
|
|
plot_barred_results(_results['TP'], _results['FP'], _results['FN'], recording_id, avg)
|
|
plot_percentages(_results['found'], _results['correct_pct'], recording_id, avg)
|
|
plot_confusion_matrix(_results['TP'], _results['FP'], _results['FN'], recording_id, avg)
|
|
|
|
|
|
def save_metrics(_metrics, recording_id, avg=True):
|
|
prefix = recording_id.split("_", 1)[0]
|
|
suffix = recording_id.split("_", 1)[1]
|
|
if suffix.endswith("_objects"):
|
|
suffix = suffix[:-len("_objects")]
|
|
|
|
folder = os.path.join("experiment_results/metrics/results", suffix)
|
|
os.makedirs(folder, exist_ok=True)
|
|
|
|
filename = f"avg_{prefix}_results.json" if avg else f"best_{prefix}_results.json"
|
|
with open(os.path.join(folder, filename), "w") as f:
|
|
json.dump(_metrics, f)
|
|
|
|
|
|
def plot_yolo_timings(values):
|
|
scenario_names = list(values.keys())
|
|
all_values = [values[name] for name in scenario_names]
|
|
|
|
plt.figure(figsize=(max(6, len(scenario_names) * 2), 5))
|
|
box = plt.boxplot(all_values, vert=True, patch_artist=True)
|
|
|
|
for patch in box['boxes']:
|
|
patch.set_facecolor('none')
|
|
patch.set_edgecolor('black')
|
|
patch.set_linewidth(1.5)
|
|
|
|
for i, values in enumerate(all_values):
|
|
min_val = min(values)
|
|
max_val = max(values)
|
|
avg_val = sum(values) / len(values)
|
|
median_val = box['medians'][i].get_ydata()[0]
|
|
|
|
# plt.scatter([i + 1], [min_val], color='red', marker='o')
|
|
# plt.scatter([i + 1], [max_val], color='blue', marker='o')
|
|
# plt.scatter([i + 1], [avg_val], color='green', marker='D')
|
|
|
|
plt.xticks(range(1, len(scenario_names) + 1), scenario_names, rotation=45, ha='right')
|
|
plt.ylabel("Runtime (s)")
|
|
plt.title("YOLO Node Callback Runtimes")
|
|
|
|
# plt.legend(handles=[
|
|
# mpatches.Patch(color='orange', label='Median'),
|
|
# plt.Line2D([], [], marker='o', color='red', linestyle='None', label='Min'),
|
|
# plt.Line2D([], [], marker='o', color='blue', linestyle='None', label='Max'),
|
|
# plt.Line2D([], [], marker='D', color='green', linestyle='None', label='Avg')
|
|
# ], loc='center left', bbox_to_anchor=(1, 0.85)
|
|
# )
|
|
|
|
plt.tight_layout()
|
|
output_path = Path("experiment_results/yolo_node_runtimes.png")
|
|
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
plt.savefig(output_path, bbox_inches='tight')
|
|
plt.close()
|
|
|
|
|
|
def analyze_graph_management_node():
|
|
base_directory_objects = Path("experiment_data/graph_management_node/objects")
|
|
benchmark_on_avg_params = load_data('experiment_data/graph_management_node/benchmark_run_avg_objects.json')
|
|
benchmark_on_best_params = load_data('experiment_data/graph_management_node/benchmark_run_1_objects.json')
|
|
|
|
graph_gen_runtimes = {'longest': 0, 'shortest': float('inf')}
|
|
|
|
all_graph_times = []
|
|
|
|
for subdir, dirs, files in os.walk(base_directory_objects):
|
|
for file in files:
|
|
file_path = Path(subdir) / file
|
|
_data = load_data(file_path)
|
|
# all_graph_times.extend(_run_times)
|
|
# graph_gen_runtimes['longest'] = max(graph_gen_runtimes['longest'], max(_run_times))
|
|
# graph_gen_runtimes['shortest'] = min(graph_gen_runtimes['shortest'], min(_run_times))
|
|
|
|
avg_metrics = calculate_metrics(_data, benchmark_on_avg_params)
|
|
best_metrics = calculate_metrics(_data, benchmark_on_best_params)
|
|
|
|
# plot_all(avg_metrics, file_path.stem, True)
|
|
# plot_all(best_metrics, file_path.stem, False)
|
|
|
|
save_metrics(avg_metrics, file_path.stem, True)
|
|
save_metrics(best_metrics, file_path.stem, False)
|
|
|
|
# plt.figure(figsize=(6, 4))
|
|
# plt.boxplot(all_graph_times, vert=False, patch_artist=False)
|
|
|
|
# plt.xlabel('Run time (s)')
|
|
# plt.yticks([1], [""], rotation=90)
|
|
# plt.title('Graph Generation Node runtimes')
|
|
# plt.tight_layout()
|
|
|
|
# ggn_boxplot_path = Path("experiment_results/graph_gen_runtimes.png")
|
|
# ggn_boxplot_path.parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
# plt.savefig(ggn_boxplot_path)
|
|
# plt.close()
|
|
|
|
with open("experiment_results/node_timings/graph_gen_runtimes.json", "w") as f:
|
|
json.dump(graph_gen_runtimes, f)
|
|
|
|
|
|
def analyze_yolo_node_timings():
|
|
directory = Path('experiment_data/yolo_node')
|
|
maximum_values = {"max_total_time": 0, "min_total_time": float('inf')}
|
|
|
|
all_time_values = {}
|
|
|
|
for subdir, dirs, files in os.walk(directory):
|
|
for file in files:
|
|
with open(os.path.join(subdir, file), "r") as f:
|
|
data = json.load(f)
|
|
results = {
|
|
'total_time': sum(data),
|
|
'mean_time': statistics.mean(data) if data else 0,
|
|
'median_time': statistics.median(data) if data else 0,
|
|
}
|
|
|
|
for v in ['total_time', 'mean_time', 'median_time']:
|
|
if results[v] > maximum_values.get(f'max_{v}', float('-inf')):
|
|
maximum_values[f'max_{v}'] = results[v]
|
|
|
|
if results['total_time'] < maximum_values['min_total_time']:
|
|
maximum_values['min_total_time'] = results['total_time']
|
|
|
|
prefix = file.split("_", 1)[0]
|
|
suffix = file.split("_", 1)[1]
|
|
if suffix.endswith(".json"):
|
|
suffix = suffix[:-len(".json")]
|
|
|
|
all_time_values[suffix] = data
|
|
|
|
folder = os.path.join("experiment_results/node_timings", suffix)
|
|
os.makedirs(folder, exist_ok=True)
|
|
|
|
filename = f"{prefix}_yolo_timing_results.json"
|
|
with open(os.path.join(folder, filename), "w") as f:
|
|
json.dump(results, f)
|
|
|
|
plot_yolo_timings(all_time_values)
|
|
|
|
with open("experiment_results/node_timings/maximum_values.json", "w") as f:
|
|
json.dump(maximum_values, f)
|
|
|
|
|
|
def find_best_results():
|
|
base_dir = "experiment_results/metrics/results"
|
|
|
|
best_f1 = {"value": -1, "folder": None, "file": None}
|
|
best_found = {"value": -1, "folder": None, "file": None}
|
|
best_correct = {"value": -1, "folder": None, "file": None}
|
|
|
|
for subdir, _, files in os.walk(base_dir):
|
|
for file in files:
|
|
if file.endswith(".json"):
|
|
path = os.path.join(subdir, file)
|
|
with open(path, "r") as f:
|
|
data = json.load(f)
|
|
|
|
f1 = data.get("f1_score", -1)
|
|
found = data.get("found_pct", -1)
|
|
correct = data.get("correct_pct", -1)
|
|
|
|
if f1 > best_f1["value"]:
|
|
best_f1 = {"value": f1, "folder": os.path.basename(subdir), "file": file}
|
|
if found > best_found["value"]:
|
|
best_found = {"value": found, "folder": os.path.basename(subdir), "file": file}
|
|
if correct > best_correct["value"]:
|
|
best_correct = {"value": correct, "folder": os.path.basename(subdir), "file": file}
|
|
|
|
print("Best F1 Score:", best_f1)
|
|
print("Best Found %:", best_found)
|
|
print("Best Correct %:", best_correct)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
analyze_graph_management_node()
|
|
#analyze_yolo_node_timings()
|
|
find_best_results()
|