IDFF-code / idff /metrics.py
rezapop's picture
IDFF code release v1.0.0 (mirror of GitHub)
0252cb7 verified
Raw History Blame Contribute Delete
1.96 kB
"""Evaluation metrics used by the examples."""
import numpy as np
import torch
def mmd_rbf(x, y, bandwidth=1.0):
"""Biased (V-statistic) squared MMD between samples x and y with a Gaussian RBF kernel."""
x = torch.as_tensor(x, dtype=torch.float64)
y = torch.as_tensor(y, dtype=torch.float64)
def k(a, b):
return torch.exp(-torch.cdist(a, b) ** 2 / (2 * bandwidth ** 2))
return (k(x, x).mean() + k(y, y).mean() - 2 * k(x, y).mean()).item()
def wrap_degrees(d):
"""Map angle differences to (-180, 180]."""
return (np.asarray(d) + 180.0) % 360.0 - 180.0
def trajectory_metrics(generated, true, angles=False):
"""MAE, RMSE and correlation coefficient between generated and true trajectories.
Args:
generated: array (length, num_samples, dim).
true: array (length, dim).
angles: if True, errors use the wrapped angular difference (degrees).
Metrics are computed per (sample, dimension) series and averaged, as in the paper's MD table.
"""
generated = np.asarray(generated)
true = np.asarray(true)
err = generated - true[:, None, :]
if angles:
err = wrap_degrees(err)
mae = np.abs(err).mean(axis=0)
rmse = np.sqrt((err ** 2).mean(axis=0))
cc = np.full(mae.shape, np.nan)
for s in range(generated.shape[1]):
for j in range(generated.shape[2]):
g, r = generated[:, s, j], true[:, j]
if g.std() > 0 and r.std() > 0:
cc[s, j] = np.corrcoef(g, r)[0, 1]
out = {"MAE": float(mae.mean()), "MAE_std": float(mae.mean(1).std()),
"RMSE": float(rmse.mean()), "RMSE_std": float(rmse.mean(1).std()),
"CC": float("nan"), "CC_std": float("nan")}
if np.isfinite(cc).any():
per_sample = np.array([np.nanmean(row) if np.isfinite(row).any() else np.nan for row in cc])
out["CC"] = float(np.nanmean(cc))
out["CC_std"] = float(np.nanstd(per_sample))
return out