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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import random
|
| 2 |
+
import math
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
from torch.distributions import Normal, Beta, Exponential, StudentT
|
| 7 |
+
from scipy.stats import beta as scipy_beta
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
# ───────────────────────── helper: icdf() calculation on torch ──────────────────────────
|
| 12 |
+
def _neg_log1p(u):
|
| 13 |
+
"""
|
| 14 |
+
Compute -log(1 - u) in a numerically stable way for u close to 0.
|
| 15 |
+
|
| 16 |
+
Args:
|
| 17 |
+
u: Tensor with values in [0, 1).
|
| 18 |
+
|
| 19 |
+
Returns:
|
| 20 |
+
Tensor of -log(1 - u), clamped to be non-negative.
|
| 21 |
+
"""
|
| 22 |
+
return (-torch.log1p(-u)).clamp_min(0.0)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def exp_icdf(u, rate):
|
| 26 |
+
"""
|
| 27 |
+
Inverse CDF (quantile function) of the Exponential distribution.
|
| 28 |
+
|
| 29 |
+
Args:
|
| 30 |
+
u : Tensor of shape (...,) with values in (0, 1).
|
| 31 |
+
rate : Scale parameter λ > 0, broadcastable with u.
|
| 32 |
+
|
| 33 |
+
Returns:
|
| 34 |
+
Tensor of the same shape as u containing the quantiles.
|
| 35 |
+
"""
|
| 36 |
+
return _neg_log1p(u) / rate
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def beta_icdf(p, a, b, n_grid: int = 1000):
|
| 40 |
+
"""
|
| 41 |
+
Approximate inverse CDF (quantile function) of the Beta distribution via
|
| 42 |
+
numerical CDF inversion on a uniform grid followed by linear interpolation.
|
| 43 |
+
|
| 44 |
+
Args:
|
| 45 |
+
p : Tensor of probabilities in (0, 1), shape (N,) or (N, D).
|
| 46 |
+
a : Alpha (concentration1) parameter(s), broadcastable to (1, D).
|
| 47 |
+
b : Beta (concentration0) parameter(s), broadcastable to (1, D).
|
| 48 |
+
n_grid : Number of grid points used to approximate the CDF (default 1000).
|
| 49 |
+
|
| 50 |
+
Returns:
|
| 51 |
+
Tensor of quantiles with shape (N, D), clamped to [0, 1].
|
| 52 |
+
"""
|
| 53 |
+
p = torch.as_tensor(p, dtype=torch.float32)
|
| 54 |
+
a = torch.as_tensor(a, dtype=torch.float32)
|
| 55 |
+
b = torch.as_tensor(b, dtype=torch.float32)
|
| 56 |
+
if a.size() == torch.Size([]):
|
| 57 |
+
a = a.expand(1)
|
| 58 |
+
if b.size() == torch.Size([]):
|
| 59 |
+
b = b.expand(1)
|
| 60 |
+
x = torch.linspace(0.0, 1.0, n_grid + 1, dtype=torch.float32, device=p.device)
|
| 61 |
+
mid = (x[:-1] + x[1:]) / 2.0
|
| 62 |
+
mid = mid.view(-1, 1) # shape [n_grid, 1]
|
| 63 |
+
dx = 1.0 / n_grid
|
| 64 |
+
|
| 65 |
+
log_norm = torch.lgamma(a) + torch.lgamma(b) - torch.lgamma(a + b)
|
| 66 |
+
pdf_mid = torch.exp((a - 1) * torch.log(mid) +
|
| 67 |
+
(b - 1) * torch.log1p(-mid) -
|
| 68 |
+
log_norm) # [n_grid, D]
|
| 69 |
+
cdf = torch.cumsum(pdf_mid, dim=0) * dx # [n_grid, D]
|
| 70 |
+
cdf = torch.cat([torch.zeros(1, cdf.shape[1], device=p.device), cdf], dim=0) # [n_grid+1, D]
|
| 71 |
+
# Expand p to match shape [N, D]
|
| 72 |
+
if p.ndim == 1:
|
| 73 |
+
p = p.unsqueeze(1)
|
| 74 |
+
if a.ndim == 1:
|
| 75 |
+
a = a.unsqueeze(0)
|
| 76 |
+
b = b.unsqueeze(0)
|
| 77 |
+
if p.shape[1] != a.shape[1]:
|
| 78 |
+
p = p.expand(-1, a.shape[1])
|
| 79 |
+
# Searchsorted per-dimension
|
| 80 |
+
N, D = p.shape
|
| 81 |
+
idx = torch.empty((N, D), dtype=torch.long, device=p.device)
|
| 82 |
+
for d in range(D):
|
| 83 |
+
idx[:, d] = torch.searchsorted(cdf[:, d], p[:, d], right=False).clamp(1, n_grid)
|
| 84 |
+
# Gather x and y for interpolation
|
| 85 |
+
x0 = x[idx - 1]
|
| 86 |
+
x1 = x[idx]
|
| 87 |
+
y0 = torch.empty_like(p)
|
| 88 |
+
y1 = torch.empty_like(p)
|
| 89 |
+
for d in range(D):
|
| 90 |
+
y0[:, d] = cdf[idx[:, d] - 1, d]
|
| 91 |
+
y1[:, d] = cdf[idx[:, d], d]
|
| 92 |
+
|
| 93 |
+
t = (p - y0) / (y1 - y0 + 1e-12)
|
| 94 |
+
return torch.clamp(x0 + t * (x1 - x0), 0., 1.)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def student_t_icdf(u, df):
|
| 98 |
+
"""
|
| 99 |
+
Approximate inverse CDF (quantile function) of the Student-t distribution.
|
| 100 |
+
|
| 101 |
+
Uses the relationship between the Student-t and Beta distributions:
|
| 102 |
+
p-value of |t| under t(df) equals the regularised incomplete beta function
|
| 103 |
+
evaluated at df/(df + t^2).
|
| 104 |
+
|
| 105 |
+
Args:
|
| 106 |
+
u : Tensor of probabilities in (0, 1).
|
| 107 |
+
df : Degrees-of-freedom parameter, broadcastable with u.
|
| 108 |
+
|
| 109 |
+
Returns:
|
| 110 |
+
Tensor of quantiles with the same shape as u.
|
| 111 |
+
"""
|
| 112 |
+
u = torch.as_tensor(u, dtype=torch.float32)
|
| 113 |
+
df = torch.as_tensor(df, dtype=torch.float32)
|
| 114 |
+
|
| 115 |
+
p = 2.0 * torch.minimum(u, 1 - u)
|
| 116 |
+
p = p.to(df.device)
|
| 117 |
+
x = beta_icdf(p, 0.5 * df, torch.tensor(0.5,device = p.device))
|
| 118 |
+
t = torch.sqrt(df * (1.0 / x - 1.0))
|
| 119 |
+
return torch.where(u > 0.5, t, -t)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def normal_cdf(x):
|
| 123 |
+
"""
|
| 124 |
+
CDF of the standard normal distribution evaluated element-wise.
|
| 125 |
+
|
| 126 |
+
Args:
|
| 127 |
+
x: Tensor of real-valued inputs.
|
| 128 |
+
|
| 129 |
+
Returns:
|
| 130 |
+
Tensor of probabilities in (0, 1) with the same shape as x.
|
| 131 |
+
"""
|
| 132 |
+
return 0.5*(1+torch.special.erf(x/math.sqrt(2)))
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def normal_ppf(u):
|
| 136 |
+
"""
|
| 137 |
+
Percent-point function (inverse CDF) of the standard normal distribution.
|
| 138 |
+
|
| 139 |
+
Args:
|
| 140 |
+
u: Tensor of probabilities in (0, 1).
|
| 141 |
+
|
| 142 |
+
Returns:
|
| 143 |
+
Tensor of quantiles with the same shape as u.
|
| 144 |
+
"""
|
| 145 |
+
return Normal(0,1).icdf(u)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
# ─────────────── low-level helpers ───────────────
|
| 149 |
+
def rand_corr_batch(batch, d, identity=False, device='cuda'):
|
| 150 |
+
"""
|
| 151 |
+
Generate a batch of random (or identity) correlation matrices.
|
| 152 |
+
|
| 153 |
+
A valid positive-definite correlation matrix is produced by forming
|
| 154 |
+
A @ A^T and normalising so that every diagonal entry equals 1.
|
| 155 |
+
|
| 156 |
+
Args:
|
| 157 |
+
batch : Number of correlation matrices to generate.
|
| 158 |
+
d : Dimension of each matrix.
|
| 159 |
+
identity : If True, return identity matrices instead of random ones.
|
| 160 |
+
device : Torch device string (default 'cuda').
|
| 161 |
+
|
| 162 |
+
Returns:
|
| 163 |
+
Tensor of shape (B, d, d) containing correlation matrices on the
|
| 164 |
+
specified device with dtype torch.float32.
|
| 165 |
+
"""
|
| 166 |
+
if identity:
|
| 167 |
+
eye = torch.eye(d, device=device, dtype=torch.float32)
|
| 168 |
+
return eye.expand(batch, -1, -1).clone()
|
| 169 |
+
|
| 170 |
+
A = torch.rand(batch, d, d, device=device, dtype=torch.float32)
|
| 171 |
+
psd = A @ A.transpose(-1, -2)
|
| 172 |
+
diag= torch.diagonal(psd, dim1=-2, dim2=-1)
|
| 173 |
+
norm= torch.sqrt(torch.clamp(diag, 1e-12))
|
| 174 |
+
C = psd / (norm.unsqueeze(-1)*norm.unsqueeze(-2))
|
| 175 |
+
C.diagonal(dim1=-2, dim2=-1).fill_(1.)
|
| 176 |
+
C += torch.eye(d, device=device, dtype=torch.float32).unsqueeze(0)*1e-6
|
| 177 |
+
return C
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def mvn_sample(chol, device):
|
| 181 |
+
"""
|
| 182 |
+
Draw one sample per batch from a zero-mean multivariate normal distribution
|
| 183 |
+
parameterised by its Cholesky factor.
|
| 184 |
+
|
| 185 |
+
Args:
|
| 186 |
+
chol : Lower-triangular Cholesky factor of shape (B, d, d) or (d, d).
|
| 187 |
+
A 2-D input is broadcast to batch size 1.
|
| 188 |
+
device : Torch device on which to allocate the standard normal noise.
|
| 189 |
+
|
| 190 |
+
Returns:
|
| 191 |
+
Tensor of shape (B, d) containing the multivariate normal samples.
|
| 192 |
+
"""
|
| 193 |
+
# chol: (B,d,d) or (d,d)
|
| 194 |
+
if chol.dim() == 2: chol = chol.unsqueeze(0)
|
| 195 |
+
B,d = chol.shape[:2]
|
| 196 |
+
z = torch.randn(B, d, 1, device=device, dtype=torch.float32)
|
| 197 |
+
return (chol @ z).squeeze(-1) # (B,d)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
# ─────────────── mixture helpers ───────────────
|
| 201 |
+
class GaussianMix:
|
| 202 |
+
"""
|
| 203 |
+
A univariate Gaussian mixture model that supports CDF and quantile queries.
|
| 204 |
+
|
| 205 |
+
Components are specified as (weight, mean, std) tuples; weights are
|
| 206 |
+
automatically normalised to sum to 1.
|
| 207 |
+
"""
|
| 208 |
+
|
| 209 |
+
def __init__(self, comps, device='cpu'):
|
| 210 |
+
"""
|
| 211 |
+
Initialise the Gaussian mixture.
|
| 212 |
+
|
| 213 |
+
Args:
|
| 214 |
+
comps : Iterable of (weight, mean, std) tuples defining each component.
|
| 215 |
+
device : Torch device on which to store parameter tensors (default 'cpu').
|
| 216 |
+
"""
|
| 217 |
+
w, mu, sigma = zip(*comps)
|
| 218 |
+
self.device = device
|
| 219 |
+
self.w = torch.tensor(w, device=device, dtype=torch.float32)
|
| 220 |
+
self.mu = torch.tensor(mu, device=device, dtype=torch.float32)
|
| 221 |
+
self.sigma = torch.tensor(sigma, device=device, dtype=torch.float32)
|
| 222 |
+
self.w /= self.w.sum()
|
| 223 |
+
|
| 224 |
+
def cdf(self, x):
|
| 225 |
+
"""
|
| 226 |
+
Evaluate the mixture CDF at x.
|
| 227 |
+
|
| 228 |
+
Args:
|
| 229 |
+
x: Scalar or tensor of query points.
|
| 230 |
+
|
| 231 |
+
Returns:
|
| 232 |
+
Tensor of CDF values in [0, 1] with the same shape as x.
|
| 233 |
+
"""
|
| 234 |
+
x = torch.as_tensor(x, dtype=torch.float32, device=self.device)
|
| 235 |
+
z = (x.unsqueeze(-1) - self.mu) / (self.sigma * math.sqrt(2))
|
| 236 |
+
return (self.w * (0.5 * (1 + torch.erf(z)))).sum(-1)
|
| 237 |
+
|
| 238 |
+
def ppf_bounds(self):
|
| 239 |
+
"""
|
| 240 |
+
Return conservative lower and upper bounds for the support of the mixture.
|
| 241 |
+
|
| 242 |
+
Returns:
|
| 243 |
+
Tuple (lo, hi) of floats representing the ±5-sigma range across all
|
| 244 |
+
mixture components.
|
| 245 |
+
"""
|
| 246 |
+
lo = (self.mu - 5 * self.sigma).min().item()
|
| 247 |
+
hi = (self.mu + 5 * self.sigma).max().item()
|
| 248 |
+
return lo, hi
|
| 249 |
+
|
| 250 |
+
def ppf(self, u, tol=1e-5, max_iter=100):
|
| 251 |
+
"""
|
| 252 |
+
Quantile function of the mixture via bisection search.
|
| 253 |
+
|
| 254 |
+
Args:
|
| 255 |
+
u : Tensor of probabilities in (0, 1), shape (...).
|
| 256 |
+
tol : Convergence tolerance on the bracket width (default 1e-5).
|
| 257 |
+
max_iter : Maximum number of bisection iterations (default 100).
|
| 258 |
+
|
| 259 |
+
Returns:
|
| 260 |
+
Tensor of quantiles with the same shape as u.
|
| 261 |
+
"""
|
| 262 |
+
u = torch.as_tensor(u, device=self.device, dtype=torch.float32)
|
| 263 |
+
low, high = self.ppf_bounds()
|
| 264 |
+
low = torch.full_like(u, low)
|
| 265 |
+
high = torch.full_like(u, high)
|
| 266 |
+
|
| 267 |
+
for _ in range(max_iter):
|
| 268 |
+
mid = 0.5 * (low + high)
|
| 269 |
+
cdf_mid = self.cdf(mid)
|
| 270 |
+
low = torch.where(cdf_mid < u, mid, low)
|
| 271 |
+
high = torch.where(cdf_mid >= u, mid, high)
|
| 272 |
+
if torch.max(high - low) < tol:
|
| 273 |
+
break
|
| 274 |
+
return 0.5 * (low + high)
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
class BetaMix:
|
| 278 |
+
"""
|
| 279 |
+
A univariate Beta mixture model with per-component location-scale transforms.
|
| 280 |
+
|
| 281 |
+
Each component is specified as (weight, alpha, beta, loc, scale) so that the
|
| 282 |
+
effective random variable is loc + scale * Beta(alpha, beta).
|
| 283 |
+
"""
|
| 284 |
+
|
| 285 |
+
def __init__(self, comps, device='cuda'):
|
| 286 |
+
"""
|
| 287 |
+
Initialise the Beta mixture.
|
| 288 |
+
|
| 289 |
+
Args:
|
| 290 |
+
comps : Iterable of (weight, alpha, beta, loc, scale) tuples.
|
| 291 |
+
device : Torch device on which to store parameter tensors (default 'cuda').
|
| 292 |
+
"""
|
| 293 |
+
self.comps = comps
|
| 294 |
+
self.w = torch.tensor([c[0] for c in comps], device=device, dtype=torch.float32)
|
| 295 |
+
self.a = torch.tensor([c[1] for c in comps], device=device, dtype=torch.float32)
|
| 296 |
+
self.b = torch.tensor([c[2] for c in comps], device=device, dtype=torch.float32)
|
| 297 |
+
self.loc = torch.tensor([c[3] for c in comps], device=device, dtype=torch.float32)
|
| 298 |
+
self.sc = torch.tensor([c[4] for c in comps], device=device, dtype=torch.float32)
|
| 299 |
+
self.w /= self.w.sum()
|
| 300 |
+
self.device = device
|
| 301 |
+
|
| 302 |
+
def cdf(self, x: torch.Tensor):
|
| 303 |
+
"""
|
| 304 |
+
Evaluate the mixture CDF at x using SciPy's Beta CDF (CPU fallback).
|
| 305 |
+
|
| 306 |
+
Args:
|
| 307 |
+
x: Tensor of query points.
|
| 308 |
+
|
| 309 |
+
Returns:
|
| 310 |
+
Tensor of CDF values in [0, 1] with the same shape as x,
|
| 311 |
+
returned on the device specified at construction time.
|
| 312 |
+
"""
|
| 313 |
+
# Fallback to CPU-based computation
|
| 314 |
+
x_cpu = x.detach().cpu().numpy()
|
| 315 |
+
cdf_vals = np.zeros_like(x_cpu)
|
| 316 |
+
for w, a, b, loc, scale in zip(self.w, self.a, self.b, self.loc, self.sc):
|
| 317 |
+
dist = scipy_beta(a=a.item(), b=b.item(), loc=loc.item(), scale=scale.item())
|
| 318 |
+
cdf_vals += w.item() * dist.cdf(x_cpu)
|
| 319 |
+
return torch.tensor(cdf_vals, device=self.device, dtype=torch.float32)
|
| 320 |
+
|
| 321 |
+
def ppf_bounds(self):
|
| 322 |
+
"""
|
| 323 |
+
Return conservative lower and upper bounds for the support of the mixture.
|
| 324 |
+
|
| 325 |
+
Returns:
|
| 326 |
+
Tuple (lo, hi) of floats corresponding to the minimum loc and the
|
| 327 |
+
maximum loc + scale across all components.
|
| 328 |
+
"""
|
| 329 |
+
lo = (self.loc).min().item()
|
| 330 |
+
hi = (self.loc + self.sc).max().item()
|
| 331 |
+
return lo, hi
|
| 332 |
+
|
| 333 |
+
# ─────────────── marginal catalogue ───────────────
|
| 334 |
+
def rand_def(device='cuda', PPF_GRID=1_000):
|
| 335 |
+
"""
|
| 336 |
+
Randomly sample a marginal distribution specification.
|
| 337 |
+
|
| 338 |
+
Picks uniformly from: Normal, Beta, Exponential, StudentT, Gaussian mixture,
|
| 339 |
+
and Beta mixture. For parametric torch distributions the spec contains the
|
| 340 |
+
distribution object directly; for mixture models an interpolation grid is
|
| 341 |
+
precomputed and stored instead.
|
| 342 |
+
|
| 343 |
+
Args:
|
| 344 |
+
device : Torch device on which to allocate tensors (default 'cuda').
|
| 345 |
+
PPF_GRID : Number of grid points for the quantile interpolation table
|
| 346 |
+
used by mixture distributions (default 1000).
|
| 347 |
+
|
| 348 |
+
Returns:
|
| 349 |
+
dict with key 'kind':
|
| 350 |
+
- 'torch' → also has key 'dist' (a torch.distributions instance).
|
| 351 |
+
- 'interp' → also has keys 'u', 'x', 'lo', 'hi' for grid interpolation.
|
| 352 |
+
"""
|
| 353 |
+
|
| 354 |
+
cat = random.choice(["normal","beta","beta_mix","expo","gauss_mix","beta_mix","student"])
|
| 355 |
+
if cat=="normal":
|
| 356 |
+
return dict(kind="torch", dist=Normal(torch.tensor(random.uniform(-1,1)),
|
| 357 |
+
torch.tensor(random.uniform(1.5,2))))
|
| 358 |
+
if cat=="beta":
|
| 359 |
+
return dict(kind="torch", dist=Beta(torch.tensor(random.uniform(1,5)),
|
| 360 |
+
torch.tensor(random.uniform(1,5))))
|
| 361 |
+
if cat=="expo":
|
| 362 |
+
return dict(kind="torch", dist=Exponential(torch.tensor(random.uniform(1,2))))
|
| 363 |
+
if cat=="student":
|
| 364 |
+
return dict(kind="torch", dist=StudentT(torch.tensor(random.randint(3,10))))
|
| 365 |
+
if cat=="gauss_mix":
|
| 366 |
+
comps = [(random.uniform(0.3,0.7),
|
| 367 |
+
random.uniform(-3,3),
|
| 368 |
+
random.uniform(0.5,1.5)) for _ in range(random.randint(1,3))]
|
| 369 |
+
mix = GaussianMix(comps)
|
| 370 |
+
else:
|
| 371 |
+
comps = [(random.uniform(0.3,0.7),
|
| 372 |
+
random.uniform(1,5),
|
| 373 |
+
random.uniform(1,5),
|
| 374 |
+
-5.0, 10.0) for _ in range(random.randint(1,3))]
|
| 375 |
+
mix = BetaMix(comps,device=device)
|
| 376 |
+
# build interpolation grids
|
| 377 |
+
u_grid = torch.linspace(0.001,0.999,PPF_GRID, device=device, dtype=torch.float32)
|
| 378 |
+
lo,hi = mix.ppf_bounds()
|
| 379 |
+
x_grid = torch.linspace(lo,hi,PPF_GRID, device=device, dtype=torch.float32)
|
| 380 |
+
#cdf_vals = mix.cdf(x_grid)
|
| 381 |
+
return dict(kind="interp", u=u_grid, x=x_grid, lo=lo, hi=hi)
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
class CopulaGenerator:
|
| 385 |
+
"""
|
| 386 |
+
Generates labelled anomaly-detection datasets via a Gaussian copula.
|
| 387 |
+
|
| 388 |
+
The joint distribution is built by:
|
| 389 |
+
1. Sampling from a multivariate normal with a random correlation structure.
|
| 390 |
+
2. Mapping each marginal through its CDF to obtain uniform scores.
|
| 391 |
+
3. Applying per-dimension quantile functions drawn from ``rand_def`` to
|
| 392 |
+
produce the final heterogeneous features.
|
| 393 |
+
|
| 394 |
+
Inliers follow the base copula; outliers are injected by either perturbing
|
| 395 |
+
the uniform scores toward the tails or by replacing a random sub-block of the
|
| 396 |
+
Cholesky factor with an independent structure.
|
| 397 |
+
"""
|
| 398 |
+
|
| 399 |
+
def __init__(self, num_dims, device="cuda", ppf_grid=2_000):
|
| 400 |
+
"""
|
| 401 |
+
Initialise the copula generator.
|
| 402 |
+
|
| 403 |
+
Args:
|
| 404 |
+
num_dims : Number of feature dimensions (d).
|
| 405 |
+
device : Torch device (default 'cuda').
|
| 406 |
+
ppf_grid : Grid resolution for quantile interpolation tables
|
| 407 |
+
used by mixture marginals (default 2000).
|
| 408 |
+
"""
|
| 409 |
+
self.num_dims = num_dims
|
| 410 |
+
self.device = device
|
| 411 |
+
self.dtype = torch.float32
|
| 412 |
+
self.ppf_grid = ppf_grid
|
| 413 |
+
self.chol_base = torch.linalg.cholesky(
|
| 414 |
+
rand_corr_batch(1, num_dims, device=device)[0]
|
| 415 |
+
)
|
| 416 |
+
self.specs = [rand_def(device=device, PPF_GRID=ppf_grid) for _ in range(num_dims)]
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
def sample_inliers(self, num_inliers):
|
| 420 |
+
"""
|
| 421 |
+
Sample inlier observations from the base copula.
|
| 422 |
+
|
| 423 |
+
Draws from the zero-mean multivariate normal defined by the stored
|
| 424 |
+
Cholesky factor. The raw Gaussian samples are returned without
|
| 425 |
+
marginal transformation so that ``_transform`` can be applied later.
|
| 426 |
+
|
| 427 |
+
Args:
|
| 428 |
+
num_inliers : Number of inlier samples to generate.
|
| 429 |
+
|
| 430 |
+
Returns:
|
| 431 |
+
Tensor of shape (num_inliers, num_dims) containing the raw
|
| 432 |
+
Gaussian-copula samples.
|
| 433 |
+
"""
|
| 434 |
+
z = torch.randn(num_inliers, self.num_dims, device=self.device, dtype=self.dtype)
|
| 435 |
+
samples = (z @ self.chol_base.T)
|
| 436 |
+
return samples
|
| 437 |
+
|
| 438 |
+
def sample_outliers(self,
|
| 439 |
+
num_outliers,
|
| 440 |
+
method="probabilistic",
|
| 441 |
+
strength=0.2):
|
| 442 |
+
"""
|
| 443 |
+
Generate outlier observations in Gaussian-copula space.
|
| 444 |
+
|
| 445 |
+
Two injection strategies are supported:
|
| 446 |
+
|
| 447 |
+
``'probabilistic'``
|
| 448 |
+
Samples from the base copula, converts to uniform marginals, then
|
| 449 |
+
forces a random subset of dimensions toward 0 or 1 to create
|
| 450 |
+
extreme-value anomalies.
|
| 451 |
+
|
| 452 |
+
``'dependence'``
|
| 453 |
+
Replaces a contiguous block of the Cholesky factor with a randomly
|
| 454 |
+
rotated version, breaking the local correlation structure.
|
| 455 |
+
|
| 456 |
+
Args:
|
| 457 |
+
num_outliers : Number of outlier samples to generate.
|
| 458 |
+
method : Injection strategy – ``'probabilistic'`` or
|
| 459 |
+
``'dependence'`` (default ``'probabilistic'``).
|
| 460 |
+
strength : Controls how extreme the perturbation is. For
|
| 461 |
+
``'probabilistic'`` this is the tail-fraction pushed;
|
| 462 |
+
for ``'dependence'`` it is the mixing weight of
|
| 463 |
+
the random sub-block (default 0.2).
|
| 464 |
+
|
| 465 |
+
Returns:
|
| 466 |
+
Tensor of shape (num_outliers, num_dims) in Gaussian-copula space
|
| 467 |
+
(before marginal transformation).
|
| 468 |
+
|
| 469 |
+
Raises:
|
| 470 |
+
ValueError: If ``method`` is not one of the supported strategies.
|
| 471 |
+
"""
|
| 472 |
+
if method == "probabilistic":
|
| 473 |
+
# 1. Sample from base MVN
|
| 474 |
+
z = torch.randn(num_outliers, self.num_dims, device=self.device, dtype=self.dtype)
|
| 475 |
+
samples = (z @ self.chol_base.T)
|
| 476 |
+
|
| 477 |
+
# 2. Transform to uniform
|
| 478 |
+
U = normal_cdf(samples)
|
| 479 |
+
min_k = max(1, math.ceil(0.02 * self.num_dims))
|
| 480 |
+
max_k = max(min_k, math.floor(0.2 * self.num_dims))
|
| 481 |
+
|
| 482 |
+
# Ensure min_k < max_k + 1 to avoid invalid range
|
| 483 |
+
if min_k >= max_k + 1:
|
| 484 |
+
max_k = min_k # fallback: both min_k and max_k equal, will result in k_row = min_k
|
| 485 |
+
|
| 486 |
+
k_row = torch.randint(min_k, max_k + 1, (num_outliers,), device=self.device)
|
| 487 |
+
#k_row = torch.randint(5, 6, (num_outliers,), device=self.device)
|
| 488 |
+
perm = torch.rand(num_outliers, self.num_dims, device=self.device).argsort(dim=1)
|
| 489 |
+
sel_mask = torch.arange(self.num_dims, device=self.device).expand(num_outliers, -1) < k_row.unsqueeze(1)
|
| 490 |
+
mask = torch.zeros_like(U, dtype=torch.bool).scatter(1, perm, sel_mask)
|
| 491 |
+
|
| 492 |
+
push0 = torch.rand_like(U) < 0.5
|
| 493 |
+
z_mask, o_mask = mask & push0, mask & ~push0
|
| 494 |
+
noise = torch.empty_like(U)
|
| 495 |
+
noise[z_mask] = strength * torch.rand(z_mask.sum(), device=self.device) * 0.5
|
| 496 |
+
noise[o_mask] = 1.0 - strength * torch.rand(o_mask.sum(), device=self.device) * 0.5
|
| 497 |
+
U[mask] = noise[mask]
|
| 498 |
+
|
| 499 |
+
samples = Normal(0, 1).icdf(U)
|
| 500 |
+
return samples
|
| 501 |
+
|
| 502 |
+
elif method == "dependence":
|
| 503 |
+
d, device = self.num_dims, self.device
|
| 504 |
+
base_L = self.chol_base
|
| 505 |
+
# 1) Random block lengths k and start indices i0 –– now 1 … d inclusive
|
| 506 |
+
lowerbound = int(1+ d//3)
|
| 507 |
+
upperbound = min(int(1+ 2 * d//3),d+1)
|
| 508 |
+
if lowerbound == upperbound:
|
| 509 |
+
upperbound += 1
|
| 510 |
+
k = torch.randint(lowerbound, upperbound, (num_outliers,), device=device) # (B,) #int(1+ d//2)
|
| 511 |
+
k_max = int(k.max())
|
| 512 |
+
|
| 513 |
+
# Vectorised start positions: i0[b] ∈ {0 … d-k[b]}
|
| 514 |
+
# torch.randint can’t take a per-element “high”, so we synthesise i0 using rand():
|
| 515 |
+
max_start = d - k # (B,)
|
| 516 |
+
i0 = (torch.rand(num_outliers, device=device) * (max_start + 1)
|
| 517 |
+
).floor().long() # (B,)
|
| 518 |
+
|
| 519 |
+
i1 = i0 + k # (B,) exclusive end index
|
| 520 |
+
L_rand_full = torch.linalg.cholesky(
|
| 521 |
+
rand_corr_batch(num_outliers, k_max, identity=True, device=device) # (B,k_max,k_max)
|
| 522 |
+
)
|
| 523 |
+
rows = torch.arange(k_max, device=device).view(1, k_max, 1) # (1,k_max,1)
|
| 524 |
+
cols = torch.arange(k_max, device=device).view(1, 1, k_max) # (1,1,k_max)
|
| 525 |
+
keep = (rows < k.view(-1, 1, 1)) & (cols < k.view(-1, 1, 1)) # (B,k_max,k_max)
|
| 526 |
+
|
| 527 |
+
L_rand_pad = torch.zeros(num_outliers, d, d, device=device) # (B,d,d)
|
| 528 |
+
L_rand_pad[:, :k_max, :k_max][keep] = L_rand_full[keep]
|
| 529 |
+
L_mix = base_L.expand(num_outliers, -1, -1).clone()
|
| 530 |
+
|
| 531 |
+
row = torch.arange(d, device=device).view(1, d) # (1,d)
|
| 532 |
+
mask_rows = (row >= i0.view(-1, 1)) & (row < i1.view(-1, 1)) # (B,d)
|
| 533 |
+
col = torch.arange(d, device=device).view(1, 1, d) # (1,1,d)
|
| 534 |
+
mask = mask_rows.unsqueeze(-1) & (col < row.unsqueeze(-1) + 1)
|
| 535 |
+
|
| 536 |
+
L_mix = torch.where(mask,
|
| 537 |
+
(1- strength) * L_mix + strength *L_rand_pad,
|
| 538 |
+
L_mix)
|
| 539 |
+
L_mix.diagonal(dim1=-2, dim2=-1).clamp_(min=1e-6)
|
| 540 |
+
return mvn_sample(L_mix, device=device)
|
| 541 |
+
else:
|
| 542 |
+
raise ValueError(f"Unsupported outlier injection method: {method}")
|
| 543 |
+
|
| 544 |
+
def _transform(self, samples):
|
| 545 |
+
"""
|
| 546 |
+
Map Gaussian-copula samples to the target marginal distributions.
|
| 547 |
+
|
| 548 |
+
Converts each column of ``samples`` through the standard-normal CDF to
|
| 549 |
+
obtain uniform scores, then applies the per-dimension quantile function
|
| 550 |
+
stored in ``self.specs``.
|
| 551 |
+
|
| 552 |
+
Distribution-specific dispatch:
|
| 553 |
+
- ``Normal``, ``Beta``, ``Exponential``, ``StudentT`` → vectorised GPU
|
| 554 |
+
operations (batched across all columns of the same type).
|
| 555 |
+
- Mixture (``kind='interp'``) → fast linear interpolation on the
|
| 556 |
+
precomputed PPF grid.
|
| 557 |
+
|
| 558 |
+
Args:
|
| 559 |
+
samples : Tensor of shape (N, D) in Gaussian-copula space.
|
| 560 |
+
|
| 561 |
+
Returns:
|
| 562 |
+
Tensor of shape (N, D) with each column drawn from its target
|
| 563 |
+
marginal distribution.
|
| 564 |
+
"""
|
| 565 |
+
U = normal_cdf(samples)
|
| 566 |
+
eps = 1e-6
|
| 567 |
+
U = torch.clamp(U, eps, 1-eps) #make sure U does not approch infty
|
| 568 |
+
N, D = U.shape
|
| 569 |
+
X = torch.empty_like(U)
|
| 570 |
+
# Group columns by distribution type
|
| 571 |
+
interp_cols, normal_cols, beta_cols, exp_cols, student_cols = [], [], [], [], []
|
| 572 |
+
for d, spec in enumerate(self.specs):
|
| 573 |
+
if spec["kind"] == "interp":
|
| 574 |
+
interp_cols.append(d)
|
| 575 |
+
elif spec["kind"] == "torch":
|
| 576 |
+
dist = spec["dist"]
|
| 577 |
+
if isinstance(dist, Normal):
|
| 578 |
+
normal_cols.append(d)
|
| 579 |
+
elif isinstance(dist, Beta):
|
| 580 |
+
beta_cols.append(d)
|
| 581 |
+
elif isinstance(dist, Exponential):
|
| 582 |
+
exp_cols.append(d)
|
| 583 |
+
elif isinstance(dist, StudentT):
|
| 584 |
+
student_cols.append(d)
|
| 585 |
+
# ---------- Interp mixture sampling ----------
|
| 586 |
+
for d in interp_cols:
|
| 587 |
+
u = U[:, d]
|
| 588 |
+
spec = self.specs[d]
|
| 589 |
+
grid_min = spec["u"][0]
|
| 590 |
+
grid_max = spec["u"][-1]
|
| 591 |
+
n_bins = len(spec["u"]) - 1
|
| 592 |
+
bin_width = (grid_max - grid_min) / n_bins
|
| 593 |
+
# Clamp u to grid range
|
| 594 |
+
u_clamped = torch.clamp(u, grid_min, grid_max - 1e-6)
|
| 595 |
+
# Fast approximate bin index (assumes linear CDF grid)
|
| 596 |
+
idx = ((u_clamped - grid_min) / bin_width).long().clamp(0, n_bins - 1)
|
| 597 |
+
idx = torch.clamp(idx, 1, len(spec["u"]) - 1)
|
| 598 |
+
u_lo, u_hi = spec["u"][idx - 1], spec["u"][idx]
|
| 599 |
+
x_lo, x_hi = spec["x"][idx - 1], spec["x"][idx]
|
| 600 |
+
X[:, d] = x_lo + (u - u_lo) * (x_hi - x_lo) / (u_hi - u_lo)
|
| 601 |
+
# ---------- Normal ----------
|
| 602 |
+
if normal_cols:
|
| 603 |
+
loc = torch.tensor([self.specs[d]["dist"].loc for d in normal_cols],
|
| 604 |
+
device=self.device).view(1, -1)
|
| 605 |
+
scale = torch.tensor([self.specs[d]["dist"].scale for d in normal_cols],
|
| 606 |
+
device=self.device).view(1, -1)
|
| 607 |
+
dist = Normal(loc, scale)
|
| 608 |
+
X[:, normal_cols] = dist.icdf(U[:, normal_cols])
|
| 609 |
+
# ---------- Beta ----------
|
| 610 |
+
if beta_cols:
|
| 611 |
+
a = torch.tensor([self.specs[d]["dist"].concentration1 for d in beta_cols],
|
| 612 |
+
device=self.device).view(1, -1)
|
| 613 |
+
b = torch.tensor([self.specs[d]["dist"].concentration0 for d in beta_cols],
|
| 614 |
+
device=self.device).view(1, -1)
|
| 615 |
+
X[:, beta_cols] = beta_icdf(U[:, beta_cols], a, b)
|
| 616 |
+
# ---------- Exponential ----------
|
| 617 |
+
if exp_cols:
|
| 618 |
+
rate = torch.tensor([self.specs[d]["dist"].rate for d in exp_cols],
|
| 619 |
+
device=self.device).view(1, -1)
|
| 620 |
+
X[:, exp_cols] = exp_icdf(U[:, exp_cols], rate)
|
| 621 |
+
# ---------- StudentT ----------
|
| 622 |
+
if student_cols:
|
| 623 |
+
df = torch.tensor([self.specs[d]["dist"].df for d in student_cols],
|
| 624 |
+
device=self.device).view(1, -1)
|
| 625 |
+
X[:, student_cols] = student_t_icdf(U[:, student_cols], df)
|
| 626 |
+
return X
|
| 627 |
+
|
| 628 |
+
|
| 629 |
+
|
| 630 |
+
@torch.no_grad()
|
| 631 |
+
def draw_batched_data(self,
|
| 632 |
+
num_inliers,
|
| 633 |
+
num_local_anomalies):
|
| 634 |
+
"""
|
| 635 |
+
Generate a labelled dataset of inliers and outliers.
|
| 636 |
+
|
| 637 |
+
Randomly selects an outlier-injection method and strength, draws both
|
| 638 |
+
populations, concatenates them, applies the marginal transformation, and
|
| 639 |
+
then splits the result back into inlier and outlier tensors.
|
| 640 |
+
|
| 641 |
+
Args:
|
| 642 |
+
num_inliers : Number of normal (inlier) observations.
|
| 643 |
+
num_local_anomalies: Number of anomalous (outlier) observations.
|
| 644 |
+
|
| 645 |
+
Returns:
|
| 646 |
+
Tuple ``(X_inliers, X_outliers)`` where each element is a Tensor of
|
| 647 |
+
shape (n, num_dims) already transformed to the target marginals.
|
| 648 |
+
"""
|
| 649 |
+
METHOD = random.choice(['dependence']) #["disturb_covariance"])#,"probabilistic"]) # or add "probabilistic"
|
| 650 |
+
STRENGTH = random.uniform(0.2,0.4) if METHOD == 'probabilistic' else random.uniform(0.97,0.99)
|
| 651 |
+
inliers = self.sample_inliers(num_inliers)
|
| 652 |
+
|
| 653 |
+
outliers = self.sample_outliers(num_local_anomalies, method=METHOD, strength=STRENGTH)
|
| 654 |
+
combined = torch.cat([inliers, outliers], dim=0)
|
| 655 |
+
|
| 656 |
+
X_combined = self._transform(combined)
|
| 657 |
+
X_inliers = X_combined[:num_inliers]
|
| 658 |
+
X_outliers = X_combined[num_inliers:]
|
| 659 |
+
|
| 660 |
+
return X_inliers, X_outliers
|
| 661 |
+
|
| 662 |
+
|
| 663 |
+
def make_Copula(device,
|
| 664 |
+
max_feature_dim=100,
|
| 665 |
+
min_feature_dim=2,
|
| 666 |
+
dim=None):
|
| 667 |
+
"""
|
| 668 |
+
Convenience factory for ``CopulaGenerator`` with a randomised feature dimension.
|
| 669 |
+
|
| 670 |
+
Args:
|
| 671 |
+
device : Torch device string (e.g. ``'cuda'``, ``'cpu'``).
|
| 672 |
+
max_feature_dim : Upper bound (exclusive) for the random feature count
|
| 673 |
+
when ``dim`` is not provided (default 100).
|
| 674 |
+
min_feature_dim : Lower bound (inclusive) for the random feature count
|
| 675 |
+
when ``dim`` is not provided (default 2).
|
| 676 |
+
dim : If given, use this exact feature dimension instead of
|
| 677 |
+
sampling randomly.
|
| 678 |
+
|
| 679 |
+
Returns:
|
| 680 |
+
A freshly initialised ``CopulaGenerator`` instance.
|
| 681 |
+
"""
|
| 682 |
+
if dim is not None:
|
| 683 |
+
num_features = dim
|
| 684 |
+
else:
|
| 685 |
+
num_features = np.random.randint(min_feature_dim, max_feature_dim)
|
| 686 |
+
return CopulaGenerator(num_dims=num_features, device=device)
|
synbench/generator.py
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from copula import CopulaGenerator
|
| 2 |
+
from gmm import make_NdMclusterGMM
|
| 3 |
+
from scm import make_structuralSCM
|
| 4 |
+
|
| 5 |
+
import math
|
| 6 |
+
import os
|
| 7 |
+
import random
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import torch
|
| 11 |
+
from sklearn.metrics import roc_auc_score
|
| 12 |
+
from sklearn.neighbors import LocalOutlierFactor
|
| 13 |
+
from tqdm import tqdm
|
| 14 |
+
|
| 15 |
+
#========== Helper functions =========================#
|
| 16 |
+
def set_seed(seed: int = 0):
|
| 17 |
+
# Python built-in RNG
|
| 18 |
+
random.seed(seed)
|
| 19 |
+
# NumPy RNG
|
| 20 |
+
np.random.seed(seed)
|
| 21 |
+
# PyTorch CPU RNG
|
| 22 |
+
torch.manual_seed(seed)
|
| 23 |
+
# PyTorch CUDA RNG (all GPUs)
|
| 24 |
+
if torch.cuda.is_available():
|
| 25 |
+
torch.cuda.manual_seed(seed)
|
| 26 |
+
torch.cuda.manual_seed_all(seed)
|
| 27 |
+
torch.backends.cudnn.deterministic = True
|
| 28 |
+
torch.backends.cudnn.benchmark = False
|
| 29 |
+
|
| 30 |
+
def evaluate_with_lof(X, y, num_outliers):
|
| 31 |
+
contamination = num_outliers / len(y)
|
| 32 |
+
lof = LocalOutlierFactor(n_neighbors=20, contamination=contamination)
|
| 33 |
+
_ = lof.fit_predict(X)
|
| 34 |
+
scores = -lof.negative_outlier_factor_
|
| 35 |
+
return roc_auc_score(y, scores)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def run_generation(
|
| 39 |
+
model_builder,
|
| 40 |
+
save_path_builder,
|
| 41 |
+
accept_auc,
|
| 42 |
+
base_seed,
|
| 43 |
+
dimension_range,
|
| 44 |
+
samples_per_dim_range=32,
|
| 45 |
+
device='cuda:0',
|
| 46 |
+
):
|
| 47 |
+
for j, dimension in tqdm(enumerate(dimension_range)):
|
| 48 |
+
count = 0
|
| 49 |
+
i = 0
|
| 50 |
+
begin_idx = j * samples_per_dim_range
|
| 51 |
+
|
| 52 |
+
while count < samples_per_dim_range:
|
| 53 |
+
set_seed(base_seed + i)
|
| 54 |
+
dim = np.random.randint(low=dimension[0], high=dimension[1])
|
| 55 |
+
|
| 56 |
+
num_inliers = np.random.randint(1_000, 5_000)
|
| 57 |
+
outliers_ratio = np.random.uniform(0.05, 0.15)
|
| 58 |
+
num_outliers = int(outliers_ratio * num_inliers)
|
| 59 |
+
|
| 60 |
+
model = model_builder(dim=dim, device=device)
|
| 61 |
+
X_in, X_out = model.draw_batched_data(num_inliers, num_outliers)
|
| 62 |
+
|
| 63 |
+
X = torch.cat([X_in, X_out]).cpu().numpy()
|
| 64 |
+
y = np.concatenate([np.zeros(num_inliers), np.ones(num_outliers)])
|
| 65 |
+
|
| 66 |
+
auc = evaluate_with_lof(X, y, num_outliers)
|
| 67 |
+
if accept_auc(auc):
|
| 68 |
+
saved = begin_idx + count
|
| 69 |
+
output_path = save_path_builder(saved)
|
| 70 |
+
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
| 71 |
+
np.savez(output_path, X=X, y=y)
|
| 72 |
+
count += 1
|
| 73 |
+
i += 1
|
| 74 |
+
|
| 75 |
+
print(
|
| 76 |
+
f"For dimension [{dimension[0]}, {dimension[1]}), accepted ratio:",
|
| 77 |
+
(count / i),
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def build_gmm_model(dim, device):
|
| 82 |
+
num_cluster = np.random.randint(low=2, high=6)
|
| 83 |
+
max_mean = np.random.randint(low=2, high=6)
|
| 84 |
+
max_var = np.random.randint(low=2, high=6)
|
| 85 |
+
return make_NdMclusterGMM(
|
| 86 |
+
dim=dim,
|
| 87 |
+
num_cluster=num_cluster,
|
| 88 |
+
weights=torch.tensor([1 / num_cluster] * num_cluster, device=device),
|
| 89 |
+
max_mean=max_mean,
|
| 90 |
+
max_var=max_var,
|
| 91 |
+
inflate_full=False,
|
| 92 |
+
sub_dims=None,
|
| 93 |
+
percentile=0.9,
|
| 94 |
+
delta=0.05,
|
| 95 |
+
device=device,
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def build_copula_model(dim, device):
|
| 100 |
+
return CopulaGenerator(num_dims=dim, device=device)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def build_scm_model(dim, device):
|
| 104 |
+
max_num_layer = 5
|
| 105 |
+
min_num_layer = max(int(np.sqrt(dim)) - 3, 2)
|
| 106 |
+
min_hidden_size = max(int(math.floor(dim / min_num_layer)) + 2, 2)
|
| 107 |
+
max_hidden_size = min(min_hidden_size + 7, 40)
|
| 108 |
+
return make_structuralSCM(
|
| 109 |
+
max_feature_dim=dim,
|
| 110 |
+
min_num_layer=min_num_layer,
|
| 111 |
+
max_num_layer=max_num_layer,
|
| 112 |
+
min_hidden_size=min_hidden_size,
|
| 113 |
+
max_hidden_size=max_hidden_size,
|
| 114 |
+
alpha=1.5,
|
| 115 |
+
beta=4.0,
|
| 116 |
+
device=device,
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
if __name__ == '__main__':
|
| 121 |
+
dimension_range = [(2, 21), (21, 41), (41, 61), (61, 81), (81, 101)]
|
| 122 |
+
|
| 123 |
+
print('generate GMM based')
|
| 124 |
+
run_generation(
|
| 125 |
+
model_builder=build_gmm_model,
|
| 126 |
+
save_path_builder=lambda saved: f"gaussian/gaussian_{saved}.npz",
|
| 127 |
+
accept_auc=lambda auc: auc < 0.95,
|
| 128 |
+
base_seed=52324,
|
| 129 |
+
dimension_range=dimension_range,
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
print('generate copula based')
|
| 133 |
+
run_generation(
|
| 134 |
+
model_builder=build_copula_model,
|
| 135 |
+
save_path_builder=lambda saved: f"copula_disturb/copuladisturb_{saved}.npz",
|
| 136 |
+
accept_auc=lambda auc: 0.5 < auc < 0.95,
|
| 137 |
+
base_seed=52324,
|
| 138 |
+
dimension_range=dimension_range,
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
print('generate scm based')
|
| 142 |
+
run_generation(
|
| 143 |
+
model_builder=build_scm_model,
|
| 144 |
+
save_path_builder=lambda saved: f"scm_contextual/scmcontextual_{saved}.npz",
|
| 145 |
+
accept_auc=lambda auc: 0.5 < auc < 0.95,
|
| 146 |
+
base_seed=52324,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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import torch
|
| 3 |
+
from torch.distributions.multivariate_normal import MultivariateNormal
|
| 4 |
+
from scipy.stats import chi2
|
| 5 |
+
import time
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class GaussianMixtureModel:
|
| 9 |
+
def __init__(self,
|
| 10 |
+
means: torch.Tensor,
|
| 11 |
+
covariances: torch.Tensor,
|
| 12 |
+
weights: torch.Tensor,
|
| 13 |
+
percentile=0.80,
|
| 14 |
+
delta=0.05,
|
| 15 |
+
inflate_scale=5.0,
|
| 16 |
+
inflate_full=False,
|
| 17 |
+
sub_dims=None,
|
| 18 |
+
device='cpu'):
|
| 19 |
+
"""
|
| 20 |
+
Initialize a Gaussian Mixture Model and a corresponding inflated GMM.
|
| 21 |
+
|
| 22 |
+
The normal GMM is used to draw inlier samples. The inflated GMM is
|
| 23 |
+
created by enlarging the covariance values on a selected subset of
|
| 24 |
+
dimensions, which makes it easier to sample local anomalies.
|
| 25 |
+
|
| 26 |
+
Args:
|
| 27 |
+
means: Tensor of shape ``(num_cluster, d)`` containing one mean
|
| 28 |
+
vector per Gaussian component.
|
| 29 |
+
covariances: Tensor of shape ``(num_cluster, d, d)`` containing one
|
| 30 |
+
covariance matrix per Gaussian component.
|
| 31 |
+
weights: Tensor of shape ``(num_cluster,)`` containing mixture
|
| 32 |
+
probabilities. These are used by ``torch.multinomial`` when
|
| 33 |
+
choosing which component to sample from.
|
| 34 |
+
percentile: Base chi-square percentile used to define inlier and
|
| 35 |
+
anomaly thresholds in the selected subspace.
|
| 36 |
+
delta: Margin around ``percentile``. Inliers are below
|
| 37 |
+
``percentile - delta``; local anomalies are above
|
| 38 |
+
``percentile + delta``.
|
| 39 |
+
inflate_scale: Multiplicative factor applied to selected covariance
|
| 40 |
+
entries when constructing the inflated GMM.
|
| 41 |
+
inflate_full: If True, inflate all dimensions. If False, randomly
|
| 42 |
+
choose a non-empty subset of dimensions to inflate.
|
| 43 |
+
sub_dims: Optional user-provided dimensions to inflate and use for
|
| 44 |
+
Mahalanobis-distance filtering.
|
| 45 |
+
device: Device on which tensors are stored.
|
| 46 |
+
"""
|
| 47 |
+
self.device = device
|
| 48 |
+
self.means = means
|
| 49 |
+
self.covariances = covariances
|
| 50 |
+
self.weights = weights
|
| 51 |
+
|
| 52 |
+
self.num_cluster = len(means)
|
| 53 |
+
d = self.means[0].shape[0]
|
| 54 |
+
self.d = d
|
| 55 |
+
n = d if inflate_full else np.random.randint(1, d + 1) # Generate random integer between 1 and d, inclusive
|
| 56 |
+
if inflate_full and sub_dims is not None:
|
| 57 |
+
print('we are inflating all the dimensions, however, sub_dims is provided')
|
| 58 |
+
raise Exception
|
| 59 |
+
self.sub_dims = torch.sort(torch.randperm(d)[:n]).values.to(self.device) if sub_dims is None else sub_dims.to(
|
| 60 |
+
self.device)
|
| 61 |
+
|
| 62 |
+
self.threshold_plus_delta = chi2.ppf(percentile + delta, df=len(self.sub_dims))
|
| 63 |
+
self.threshold_minus_delta = chi2.ppf(percentile - delta, df=len(self.sub_dims))
|
| 64 |
+
|
| 65 |
+
self.inflated_covariances = []
|
| 66 |
+
self.inv_sub_covariances = []
|
| 67 |
+
|
| 68 |
+
for cov in self.covariances:
|
| 69 |
+
cov_copy = cov.clone()
|
| 70 |
+
sub_cov = cov_copy[self.sub_dims, :][:, self.sub_dims] # the sub_cov defines a new (smaller) Gaussian
|
| 71 |
+
# n x n ---> sub_dims x n ---> sub_dims x sub_dims
|
| 72 |
+
self.inv_sub_covariances.append(torch.linalg.inv(sub_cov))
|
| 73 |
+
cov_copy[self.sub_dims[:, None], self.sub_dims] *= inflate_scale
|
| 74 |
+
self.inflated_covariances.append(cov_copy)
|
| 75 |
+
|
| 76 |
+
self.inflated_covariances = torch.stack(self.inflated_covariances)
|
| 77 |
+
self.inv_sub_covariances = torch.stack(self.inv_sub_covariances)
|
| 78 |
+
|
| 79 |
+
self.GMM4sample = [MultivariateNormal(self.means[cluster_id], self.covariances[cluster_id])
|
| 80 |
+
for cluster_id in range(len(self.weights))]
|
| 81 |
+
|
| 82 |
+
self.GMM4inf = [MultivariateNormal(self.means[cluster_id], self.inflated_covariances[cluster_id])
|
| 83 |
+
for cluster_id in range(len(self.weights))]
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def draw_samples(self, num_samples):
|
| 87 |
+
"""
|
| 88 |
+
Draws samples from the d-dimensional Gaussian Mixture Model.
|
| 89 |
+
Args:
|
| 90 |
+
num_samples (int): Number of samples to draw.
|
| 91 |
+
Returns:
|
| 92 |
+
torch.Tensor: samples drawn from the GMM.
|
| 93 |
+
"""
|
| 94 |
+
samples = torch.zeros(num_samples, self.d, device=self.device)
|
| 95 |
+
component_choices = torch.multinomial(self.weights, num_samples, replacement=True)
|
| 96 |
+
for cluster_id in range(self.num_cluster):
|
| 97 |
+
mask = (component_choices == cluster_id)
|
| 98 |
+
num_cluster_samples = mask.sum().item()
|
| 99 |
+
if num_cluster_samples > 0:
|
| 100 |
+
sample = self.GMM4sample[cluster_id].sample((num_cluster_samples,))
|
| 101 |
+
samples[mask] = sample
|
| 102 |
+
return samples
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def draw_inflated_samples(self, num_samples):
|
| 106 |
+
"""
|
| 107 |
+
Draws samples from the d-dimensional inflated Gaussian Mixture Model.
|
| 108 |
+
Args:
|
| 109 |
+
num_samples (int): Number of samples to draw.
|
| 110 |
+
Returns:
|
| 111 |
+
torch.Tensor: samples drawn from the inflated GMM.
|
| 112 |
+
"""
|
| 113 |
+
samples = torch.zeros(num_samples, self.d, device=self.device)
|
| 114 |
+
component_choices = torch.multinomial(self.weights, num_samples, replacement=True)
|
| 115 |
+
|
| 116 |
+
for cluster_id in range(self.num_cluster):
|
| 117 |
+
mask = (component_choices == cluster_id)
|
| 118 |
+
num_cluster_samples = mask.sum().item()
|
| 119 |
+
if num_cluster_samples > 0:
|
| 120 |
+
sample = self.GMM4inf[cluster_id].sample((num_cluster_samples,)) # .type_as(self.weights)
|
| 121 |
+
samples[mask] = sample
|
| 122 |
+
return samples
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def mahalanobis_distance(self, sample, mean, inv_covariance):
|
| 126 |
+
"""
|
| 127 |
+
Computes the Mahalanobis distance of a sample from a given mean and inverse covariance matrix.
|
| 128 |
+
Args:
|
| 129 |
+
sample (torch.Tensor): Sample point. (d, )
|
| 130 |
+
mean (torch.Tensor): Mean vector. (d, )
|
| 131 |
+
inv_covariance (torch.Tensor): Inverse covariance matrix. (sub-dims, )
|
| 132 |
+
Returns:
|
| 133 |
+
float: Mahalanobis distance of the sample from the mean.
|
| 134 |
+
"""
|
| 135 |
+
delta = sample[self.sub_dims] - mean[self.sub_dims]
|
| 136 |
+
return torch.sqrt((delta @ inv_covariance @ delta).sum())
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def batched_squared_mahalanobis_distance(self, X, mean, inv_cov):
|
| 140 |
+
# Select only the dimensions used for local anomaly detection,
|
| 141 |
+
# then subtract the corresponding mean values.
|
| 142 |
+
# X[:, self.sub_dims]: shape (num_samples, num_selected_dims)
|
| 143 |
+
# mean[self.sub_dims]: shape (num_selected_dims,)
|
| 144 |
+
delta = X[:, self.sub_dims] - mean[self.sub_dims]
|
| 145 |
+
|
| 146 |
+
# Compute squared Mahalanobis distance for each sample:
|
| 147 |
+
# distance_i = delta_i^T @ inv_cov @ delta_i
|
| 148 |
+
# delta @ inv_cov @ delta.T gives a matrix of pairwise quadratic forms
|
| 149 |
+
# between all samples. The diagonal contains each sample's own
|
| 150 |
+
# squared Mahalanobis distance.
|
| 151 |
+
return torch.diag(delta @ inv_cov @ delta.T)
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def draw_inliers(self, num_samples):
|
| 155 |
+
"""
|
| 156 |
+
Draw inlier samples from the original GMM using rejection sampling.
|
| 157 |
+
A sample is accepted as an inlier if its minimum squared Mahalanobis
|
| 158 |
+
distance to any Gaussian component, computed only on self.sub_dims,
|
| 159 |
+
is below self.threshold_minus_delta.
|
| 160 |
+
Args:
|
| 161 |
+
num_samples: Number of inlier samples to return.
|
| 162 |
+
Returns:
|
| 163 |
+
Tensor of shape (num_samples, self.d) containing accepted inlier samples.
|
| 164 |
+
"""
|
| 165 |
+
|
| 166 |
+
# Draw more candidates than needed, because some samples will be rejected.
|
| 167 |
+
# Use at least 1000 candidates per loop to avoid very small inefficient batches.
|
| 168 |
+
batch_size = max(num_samples * 2, 1000)
|
| 169 |
+
samples = []
|
| 170 |
+
total_samples_needed = num_samples
|
| 171 |
+
while total_samples_needed > 0:
|
| 172 |
+
raw_samples = self.draw_samples(batch_size)
|
| 173 |
+
batch_distances = self.get_squared_batched_dist(raw_samples)
|
| 174 |
+
min_squared_distances = torch.min(batch_distances, dim=1).values
|
| 175 |
+
inliner_mask = min_squared_distances < self.threshold_minus_delta
|
| 176 |
+
selected_samples = raw_samples[inliner_mask]
|
| 177 |
+
num_selected = selected_samples.shape[0]
|
| 178 |
+
if num_selected > 0:
|
| 179 |
+
if num_selected >= total_samples_needed:
|
| 180 |
+
samples.append(selected_samples[:total_samples_needed])
|
| 181 |
+
total_samples_needed = 0
|
| 182 |
+
else:
|
| 183 |
+
samples.append(selected_samples)
|
| 184 |
+
total_samples_needed -= num_selected
|
| 185 |
+
samples = torch.cat(samples)
|
| 186 |
+
return samples
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def draw_local_anomalies(self, num_samples):
|
| 190 |
+
"""
|
| 191 |
+
Draw local anomaly samples from the inflated GMM using rejection sampling.
|
| 192 |
+
|
| 193 |
+
A sample is accepted as a local anomaly if its minimum squared Mahalanobis
|
| 194 |
+
distance to any original Gaussian component, computed only on self.sub_dims,
|
| 195 |
+
is above self.threshold_plus_delta.
|
| 196 |
+
|
| 197 |
+
Args:
|
| 198 |
+
num_samples: Number of local anomaly samples to return.
|
| 199 |
+
|
| 200 |
+
Returns:
|
| 201 |
+
Tensor of shape (num_samples, self.d) containing accepted local anomaly samples.
|
| 202 |
+
"""
|
| 203 |
+
batch_size = max(num_samples * 2, 1000)
|
| 204 |
+
samples = []
|
| 205 |
+
total_samples_needed = num_samples
|
| 206 |
+
while total_samples_needed > 0:
|
| 207 |
+
raw_samples = self.draw_inflated_samples(batch_size)
|
| 208 |
+
batch_distances = self.get_squared_batched_dist(raw_samples)
|
| 209 |
+
min_squared_distances = torch.min(batch_distances, dim=1).values
|
| 210 |
+
anomaly_mask = min_squared_distances > self.threshold_plus_delta
|
| 211 |
+
selected_samples = raw_samples[anomaly_mask]
|
| 212 |
+
num_selected = selected_samples.shape[0]
|
| 213 |
+
if num_selected > 0:
|
| 214 |
+
if num_selected >= total_samples_needed:
|
| 215 |
+
samples.append(selected_samples[:total_samples_needed])
|
| 216 |
+
total_samples_needed = 0
|
| 217 |
+
else:
|
| 218 |
+
samples.append(selected_samples)
|
| 219 |
+
total_samples_needed -= num_selected
|
| 220 |
+
samples = torch.cat(samples)
|
| 221 |
+
return samples
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def assert_inliers(self, samples):
|
| 225 |
+
"""
|
| 226 |
+
Verify that all given samples satisfy the inlier criterion.
|
| 227 |
+
A sample is considered an inlier if its minimum squared Mahalanobis
|
| 228 |
+
distance to any Gaussian component, computed on self.sub_dims, is below
|
| 229 |
+
self.threshold_minus_delta.
|
| 230 |
+
Args:
|
| 231 |
+
samples: Tensor of shape (num_samples, self.d) containing samples
|
| 232 |
+
to check.
|
| 233 |
+
Raises:
|
| 234 |
+
AssertionError: If any sample does not satisfy the inlier condition.
|
| 235 |
+
"""
|
| 236 |
+
for sample in samples:
|
| 237 |
+
distances = [self.mahalanobis_distance(sample, mean, inv_cov) for mean, inv_cov in
|
| 238 |
+
zip(self.means, self.inv_sub_covariances)]
|
| 239 |
+
assert min(distances) ** 2 < self.threshold_minus_delta
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def assert_local_anomalies(self, samples):
|
| 243 |
+
"""
|
| 244 |
+
Verify that all given samples satisfy the local anomaly criterion.
|
| 245 |
+
A sample is considered a local anomaly if its minimum squared Mahalanobis
|
| 246 |
+
distance to any Gaussian component, computed on self.sub_dims, is above
|
| 247 |
+
self.threshold_plus_delta.
|
| 248 |
+
Args:
|
| 249 |
+
samples: Tensor of shape (num_samples, self.d) containing samples
|
| 250 |
+
to check.
|
| 251 |
+
Raises:
|
| 252 |
+
AssertionError: If any sample does not satisfy the local anomaly condition.
|
| 253 |
+
"""
|
| 254 |
+
for sample in samples:
|
| 255 |
+
distances = [self.mahalanobis_distance(sample, mean, inv_cov) for mean, inv_cov in
|
| 256 |
+
zip(self.means, self.inv_sub_covariances)]
|
| 257 |
+
assert min(distances) ** 2 > self.threshold_plus_delta
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def get_squared_batched_dist(self, raw_samples):
|
| 261 |
+
"""
|
| 262 |
+
Compute squared Mahalanobis distances from samples to all GMM components.
|
| 263 |
+
For each sample, this computes its squared Mahalanobis distance to each
|
| 264 |
+
Gaussian component using only self.sub_dims.
|
| 265 |
+
Args:
|
| 266 |
+
raw_samples: Tensor of shape (num_samples, self.d) containing samples
|
| 267 |
+
to evaluate.
|
| 268 |
+
Returns:
|
| 269 |
+
Tensor of shape (num_samples, num_cluster), where entry (i, j) is the
|
| 270 |
+
squared Mahalanobis distance from sample i to component j.
|
| 271 |
+
"""
|
| 272 |
+
batch_dist = []
|
| 273 |
+
for mean, inv_cov in zip(self.means, self.inv_sub_covariances):
|
| 274 |
+
distances = self.batched_squared_mahalanobis_distance(X=raw_samples, mean=mean, inv_cov=inv_cov)
|
| 275 |
+
batch_dist.append(distances)
|
| 276 |
+
return torch.stack(batch_dist, dim=1) # (#samples, num_cluster)
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
def draw_batched_data(self, num_inliers, num_local_anomalies):
|
| 280 |
+
"""
|
| 281 |
+
Draw a batch containing both inliers and local anomalies.
|
| 282 |
+
|
| 283 |
+
This method first oversamples candidate inliers from the original GMM and
|
| 284 |
+
candidate anomalies from the inflated GMM. It then filters them using
|
| 285 |
+
Mahalanobis-distance thresholds. If not enough valid samples are found,
|
| 286 |
+
it calls draw_inliers or draw_local_anomalies to fill the missing amount.
|
| 287 |
+
|
| 288 |
+
Args:
|
| 289 |
+
num_inliers: Number of accepted inlier samples to return.
|
| 290 |
+
num_local_anomalies: Number of accepted local anomaly samples to return.
|
| 291 |
+
|
| 292 |
+
Returns:
|
| 293 |
+
A tuple:
|
| 294 |
+
inliers: Tensor of shape (num_inliers, self.d)
|
| 295 |
+
local_anomalies: Tensor of shape (num_local_anomalies, self.d)
|
| 296 |
+
"""
|
| 297 |
+
raw_inliers = self.draw_samples(num_samples=int(num_inliers * 2))
|
| 298 |
+
raw_local_anomalies = self.draw_inflated_samples(num_samples=int(num_local_anomalies * 2))
|
| 299 |
+
|
| 300 |
+
inliers_squared_dist = self.get_squared_batched_dist(raw_samples=raw_inliers)
|
| 301 |
+
local_anomalies_squared_dist = self.get_squared_batched_dist(raw_samples=raw_local_anomalies)
|
| 302 |
+
|
| 303 |
+
min_inliers_squared_dist = torch.min(inliers_squared_dist, dim=1).values
|
| 304 |
+
min_local_anomalies_squared_dist = torch.min(local_anomalies_squared_dist, dim=1).values
|
| 305 |
+
|
| 306 |
+
inliers_mask = min_inliers_squared_dist < self.threshold_minus_delta # (#raw-inliers, )
|
| 307 |
+
local_anomalies_mask = min_local_anomalies_squared_dist > self.threshold_plus_delta # (#raw-la, )
|
| 308 |
+
|
| 309 |
+
inliers = raw_inliers[inliers_mask][:num_inliers]
|
| 310 |
+
local_anomalies = raw_local_anomalies[local_anomalies_mask][:num_local_anomalies]
|
| 311 |
+
|
| 312 |
+
def add_extra(existing_samples, target_num_samples, draw_func):
|
| 313 |
+
if existing_samples.shape[0] < target_num_samples:
|
| 314 |
+
extra_samples = draw_func(num_samples=target_num_samples - existing_samples.shape[0])
|
| 315 |
+
existing_samples = torch.concat([existing_samples, extra_samples], dim=0)
|
| 316 |
+
return existing_samples
|
| 317 |
+
|
| 318 |
+
inliers = add_extra(existing_samples=inliers, target_num_samples=num_inliers, draw_func=self.draw_inliers)
|
| 319 |
+
local_anomalies = add_extra(existing_samples=local_anomalies, target_num_samples=num_local_anomalies,
|
| 320 |
+
draw_func=self.draw_local_anomalies)
|
| 321 |
+
return inliers, local_anomalies
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
def make_NdMclusterGMM(dim: int, num_cluster: int, weights: torch.Tensor, max_mean: int, max_var: int,
|
| 326 |
+
inflate_full: bool, device, sub_dims=None, percentile=0.80, delta=0.05):
|
| 327 |
+
# Generate means between -max_mean and max_mean
|
| 328 |
+
means = torch.rand(num_cluster, dim, device=device) * \
|
| 329 |
+
torch.randint(low=-max_mean, high=max_mean+1, size=(num_cluster, dim, ), device=device)
|
| 330 |
+
|
| 331 |
+
# Generate diagonal covariance matrices with positive entries between 1 and max_var
|
| 332 |
+
diag_values = torch.rand(num_cluster, dim, device=device) * \
|
| 333 |
+
torch.randint(low=1, high=max_var+1, size=(num_cluster, dim, ), device=device)
|
| 334 |
+
diag_values[diag_values == 0] = max_var / 2
|
| 335 |
+
|
| 336 |
+
# Create batch of diagonal covariance matrices
|
| 337 |
+
covariances = torch.diag_embed(diag_values) # Shape: (num_cluster, dim, dim)
|
| 338 |
+
|
| 339 |
+
N_d_M_cluster_gaussian = GaussianMixtureModel(
|
| 340 |
+
means=means,
|
| 341 |
+
covariances=covariances,
|
| 342 |
+
weights=weights,
|
| 343 |
+
inflate_full=inflate_full,
|
| 344 |
+
sub_dims=sub_dims,
|
| 345 |
+
percentile=percentile,
|
| 346 |
+
delta=delta,
|
| 347 |
+
device=device
|
| 348 |
+
)
|
| 349 |
+
return N_d_M_cluster_gaussian
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
#================= Helper functions ===================#
|
| 353 |
+
def generate_constrained_eigenvals(d):
|
| 354 |
+
# Generate uniformly distributed values in the range (-0.8, -0.2)
|
| 355 |
+
low_range = np.random.uniform(-1.0, -0.1, size=d)
|
| 356 |
+
|
| 357 |
+
# Generate uniformly distributed values in the range (0.2, 0.8)
|
| 358 |
+
high_range = np.random.uniform(0.1, 1.0, size=d)
|
| 359 |
+
|
| 360 |
+
# Randomly choose between the two ranges for each element
|
| 361 |
+
choice = np.random.choice([0, 1], size=d)
|
| 362 |
+
vector = np.where(choice == 0, low_range, high_range)
|
| 363 |
+
|
| 364 |
+
return vector
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
def generate_full_rank_matrix(dim, device, scale=1):
|
| 368 |
+
# Generate a random orthogonal matrix using QR decomposition
|
| 369 |
+
A = np.random.rand(dim, dim)
|
| 370 |
+
Q, _ = np.linalg.qr(A)
|
| 371 |
+
|
| 372 |
+
eigenvals = generate_constrained_eigenvals(d=dim)
|
| 373 |
+
eigenvals = np.diag(eigenvals)
|
| 374 |
+
|
| 375 |
+
full_rank_matrix = Q @ eigenvals @ Q.T
|
| 376 |
+
assert np.linalg.matrix_rank(full_rank_matrix) == dim
|
| 377 |
+
if device is None: # source is numpy
|
| 378 |
+
return full_rank_matrix
|
| 379 |
+
else:
|
| 380 |
+
return torch.from_numpy(full_rank_matrix).to(dtype=torch.float, device=device)
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
def generate_linear_transform(dim, device, A_scale=1, b_scale=1):
|
| 384 |
+
A = generate_full_rank_matrix(dim=dim, device=device, scale=A_scale)
|
| 385 |
+
b = np.random.rand(dim) * np.random.randint(low=-b_scale, high=b_scale + 1, size=dim) # [low, high)
|
| 386 |
+
|
| 387 |
+
if device is not None: # source is torch, transfer from numpy to torch
|
| 388 |
+
b = torch.from_numpy(b).to(dtype=torch.float, device=device)
|
| 389 |
+
return A, b
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
def transform_means(means, sub_dims, A, b):
|
| 393 |
+
trans = []
|
| 394 |
+
for mean in means:
|
| 395 |
+
new_mean = mean.clone()
|
| 396 |
+
new_mean[sub_dims] = A @ new_mean[sub_dims] + b
|
| 397 |
+
trans.append(new_mean)
|
| 398 |
+
return torch.stack(trans)
|
| 399 |
+
|
| 400 |
+
|
| 401 |
+
def transform_covs(covs, sub_dims, A):
|
| 402 |
+
trans = []
|
| 403 |
+
for cov in covs:
|
| 404 |
+
new_cov = cov.clone()
|
| 405 |
+
new_cov[sub_dims[:, None], sub_dims] = A @ new_cov[sub_dims[:, None], sub_dims] @ A.T
|
| 406 |
+
trans.append(new_cov)
|
| 407 |
+
return torch.stack(trans)
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
def transform_samples(samples, sub_dims, A, b, is_source_numpy=False):
|
| 411 |
+
if is_source_numpy:
|
| 412 |
+
new_samples = samples.copy()
|
| 413 |
+
else:
|
| 414 |
+
new_samples = samples.clone()
|
| 415 |
+
|
| 416 |
+
if sub_dims is None:
|
| 417 |
+
new_samples = new_samples @ A.T + b
|
| 418 |
+
else:
|
| 419 |
+
new_samples[:, sub_dims] = new_samples[:, sub_dims] @ A.T + b
|
| 420 |
+
|
| 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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import numpy as np
|
| 4 |
+
import time
|
| 5 |
+
import math
|
| 6 |
+
import random
|
| 7 |
+
|
| 8 |
+
def lognormal_discrete(mu,
|
| 9 |
+
sigma,
|
| 10 |
+
minval: int,
|
| 11 |
+
maxval: int):
|
| 12 |
+
"""
|
| 13 |
+
Sample an integer from a log-normal distribution, clamped to [minval, maxval].
|
| 14 |
+
|
| 15 |
+
Args:
|
| 16 |
+
mu : Mean of the underlying normal distribution.
|
| 17 |
+
sigma : Standard deviation of the underlying normal distribution.
|
| 18 |
+
minval : Minimum integer value (inclusive).
|
| 19 |
+
maxval : Maximum integer value (inclusive).
|
| 20 |
+
|
| 21 |
+
Returns:
|
| 22 |
+
int: A rounded, clipped sample from the log-normal distribution.
|
| 23 |
+
"""
|
| 24 |
+
val = int(np.round(np.random.lognormal(mu, sigma)))
|
| 25 |
+
return int(np.clip(val, minval, maxval))
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def sample_layers_and_nodes(min_num_layer =2,
|
| 29 |
+
max_num_layer =5,
|
| 30 |
+
min_hidden_size = 3,
|
| 31 |
+
max_hidden_size = 8):
|
| 32 |
+
"""
|
| 33 |
+
Randomly sample the number of hidden layers and the hidden-layer width.
|
| 34 |
+
|
| 35 |
+
Uses log-normal priors so moderate values are more likely than extremes.
|
| 36 |
+
|
| 37 |
+
Args:
|
| 38 |
+
min_num_layer : Minimum number of hidden layers (default 2).
|
| 39 |
+
max_num_layer : Maximum number of hidden layers (default 5).
|
| 40 |
+
min_hidden_size : Minimum number of nodes per hidden layer (default 3).
|
| 41 |
+
max_hidden_size : Maximum number of nodes per hidden layer (default 8).
|
| 42 |
+
|
| 43 |
+
Returns:
|
| 44 |
+
Tuple (l, h) where l is the number of layers and h is the hidden size.
|
| 45 |
+
"""
|
| 46 |
+
l = lognormal_discrete(mu=0.7, sigma=0.4, minval=min_num_layer, maxval=max_num_layer) # num layers
|
| 47 |
+
h = lognormal_discrete(mu=1.2, sigma=0.5, minval=min_hidden_size, maxval=max_hidden_size) # hidden size
|
| 48 |
+
return l, h
|
| 49 |
+
|
| 50 |
+
@torch.no_grad()
|
| 51 |
+
def sample_noise_distribution(device='cpu'):
|
| 52 |
+
"""
|
| 53 |
+
Create a random log-normal noise sampler with randomised parameters.
|
| 54 |
+
|
| 55 |
+
The log-normal parameters are drawn uniformly:
|
| 56 |
+
- mu ~ Uniform(-0.5, 0.5)
|
| 57 |
+
- sigma ~ Uniform(0.05, 0.5)
|
| 58 |
+
|
| 59 |
+
The returned callable samples n independent log-normal values and exposes
|
| 60 |
+
its ``mu`` and ``sigma`` attributes for later inspection.
|
| 61 |
+
|
| 62 |
+
Args:
|
| 63 |
+
device : Torch device on which to allocate noise tensors (default 'cpu').
|
| 64 |
+
|
| 65 |
+
Returns:
|
| 66 |
+
Callable noise_func(n) -> Tensor of shape (n,) drawn from
|
| 67 |
+
LogNormal(mu, sigma). The function has attributes ``mu`` and ``sigma``.
|
| 68 |
+
"""
|
| 69 |
+
mu = (torch.rand(1, device=device) - 0.5).item()
|
| 70 |
+
sigma = (torch.rand(1, device=device) * (0.5 - 0.05) + 0.05).item()
|
| 71 |
+
def noise_func(n):
|
| 72 |
+
return torch.exp(mu + sigma * torch.randn(n, device=device))
|
| 73 |
+
noise_func.mu = mu
|
| 74 |
+
noise_func.sigma = sigma
|
| 75 |
+
return noise_func
|
| 76 |
+
|
| 77 |
+
@torch.no_grad()
|
| 78 |
+
def sample_activation(device='cpu'):
|
| 79 |
+
"""
|
| 80 |
+
Uniformly sample one activation function from a fixed catalogue.
|
| 81 |
+
|
| 82 |
+
The catalogue contains: tanh, leaky ReLU (slope 0.01), ELU, and identity.
|
| 83 |
+
|
| 84 |
+
Args:
|
| 85 |
+
device : Torch device (unused at runtime but kept for API consistency).
|
| 86 |
+
|
| 87 |
+
Returns:
|
| 88 |
+
Tuple (name: str, fn: Callable) where fn maps a Tensor to a Tensor.
|
| 89 |
+
"""
|
| 90 |
+
activations = [
|
| 91 |
+
("tanh", torch.tanh),
|
| 92 |
+
("leaky_relu", lambda x: torch.where(x > 0, x, 0.01 * x)),
|
| 93 |
+
("elu", lambda x: torch.where(x > 0, x, torch.exp(x) - 1)),
|
| 94 |
+
("identity", lambda x: x),
|
| 95 |
+
]
|
| 96 |
+
idx = torch.randint(0, len(activations), (1,), device=device).item()
|
| 97 |
+
return activations[idx]
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
@torch.no_grad()
|
| 101 |
+
def random_noise_scales_per_sample(num_samples, layer_sizes, high_noise=5.0, high_noise_prob=0.2, device='cpu'):
|
| 102 |
+
"""
|
| 103 |
+
Generate random noise scales for each sample and node, for each layer.
|
| 104 |
+
Returns: List of tensors, each shape (num_samples, layer_size)
|
| 105 |
+
"""
|
| 106 |
+
noise_scales = [
|
| 107 |
+
torch.where(
|
| 108 |
+
torch.rand(num_samples, n, device=device) < high_noise_prob,
|
| 109 |
+
torch.full((num_samples, n), high_noise, device=device),
|
| 110 |
+
torch.ones(num_samples, n, device=device)
|
| 111 |
+
)
|
| 112 |
+
for n in layer_sizes
|
| 113 |
+
]
|
| 114 |
+
return noise_scales
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
@torch.no_grad()
|
| 118 |
+
def create_weight_mask(
|
| 119 |
+
num_samples, layers, chosen_nodes, perturb_prob=0.5, device='cpu'
|
| 120 |
+
):
|
| 121 |
+
"""
|
| 122 |
+
Vectorized version: No per-sample loop.
|
| 123 |
+
For each sample and layer, ensures that at least one parent of a chosen node is perturbed.
|
| 124 |
+
"""
|
| 125 |
+
masks = []
|
| 126 |
+
node_layer_size = layers[0].weight.shape[0] # assumes all layers same size
|
| 127 |
+
|
| 128 |
+
for l, layer in enumerate(layers):
|
| 129 |
+
weight = layer.weight # (out_features, in_features)
|
| 130 |
+
perturbable = (torch.abs(weight) > 0.5) # (out, in)
|
| 131 |
+
mask = torch.ones(num_samples, *weight.shape, device=device)
|
| 132 |
+
|
| 133 |
+
perturb_mask = (torch.rand(num_samples, *weight.shape, device=device) < perturb_prob) & perturbable.unsqueeze(0)
|
| 134 |
+
flip_mask = torch.rand(num_samples, *weight.shape, device=device) < 0.5
|
| 135 |
+
|
| 136 |
+
mask[perturb_mask & flip_mask] = -1.0
|
| 137 |
+
mask[perturb_mask & (~flip_mask)] = 0.0
|
| 138 |
+
|
| 139 |
+
# Find chosen nodes for this layer (global to local index)
|
| 140 |
+
chosen_nodes_this_layer = [idx for idx in chosen_nodes if (idx // node_layer_size) == l]
|
| 141 |
+
if len(chosen_nodes_this_layer) == 0:
|
| 142 |
+
masks.append(mask)
|
| 143 |
+
continue
|
| 144 |
+
|
| 145 |
+
for cidx in chosen_nodes_this_layer:
|
| 146 |
+
node_idx = cidx % node_layer_size # local node index for this layer
|
| 147 |
+
|
| 148 |
+
# For all samples: find if any parent is perturbed (and perturbable) for this node
|
| 149 |
+
perturbed = ((mask[:, node_idx, :] != 1.0) & perturbable[node_idx, :]) # (num_samples, in_features)
|
| 150 |
+
any_perturbed = perturbed.any(dim=1) # (num_samples,)
|
| 151 |
+
|
| 152 |
+
need_perturb = (~any_perturbed) # (num_samples,)
|
| 153 |
+
num_to_fix = need_perturb.sum().item()
|
| 154 |
+
if num_to_fix == 0:
|
| 155 |
+
continue
|
| 156 |
+
|
| 157 |
+
# For those samples, pick a random eligible parent and force a perturbation
|
| 158 |
+
eligible_parents = perturbable[node_idx, :].nonzero(as_tuple=True)[0]
|
| 159 |
+
if len(eligible_parents) == 0:
|
| 160 |
+
continue
|
| 161 |
+
|
| 162 |
+
# Pick a random parent for each sample needing fix
|
| 163 |
+
rand_idx = torch.randint(0, len(eligible_parents), (num_to_fix,), device=device)
|
| 164 |
+
parent_idx = eligible_parents[rand_idx] # (num_to_fix,)
|
| 165 |
+
sample_idx = need_perturb.nonzero(as_tuple=True)[0] # (num_to_fix,)
|
| 166 |
+
|
| 167 |
+
# Randomly decide flip or zero
|
| 168 |
+
random_flip = (torch.rand(num_to_fix, device=device) < 0.5)
|
| 169 |
+
mask[sample_idx, node_idx, parent_idx] = torch.where(random_flip, -1.0, 0.0)
|
| 170 |
+
|
| 171 |
+
masks.append(mask)
|
| 172 |
+
return masks
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
class MaskedLinear(nn.Linear):
|
| 177 |
+
"""
|
| 178 |
+
A linear layer whose effective weight matrix is element-wise multiplied by
|
| 179 |
+
a binary (or real-valued) mask, enabling sparse / structured connectivity.
|
| 180 |
+
|
| 181 |
+
Weights are initialised from N(0, 1). The mask is a non-gradient parameter
|
| 182 |
+
that can be set randomly via ``set_random_mask`` or overridden per-sample
|
| 183 |
+
during the forward pass.
|
| 184 |
+
"""
|
| 185 |
+
|
| 186 |
+
def __init__(self, in_features, out_features, min_abs=0.35, device='cpu'):
|
| 187 |
+
"""
|
| 188 |
+
Initialise MaskedLinear with N(0, 1) weights and an all-ones mask.
|
| 189 |
+
|
| 190 |
+
Args:
|
| 191 |
+
in_features : Size of each input sample.
|
| 192 |
+
out_features : Size of each output sample.
|
| 193 |
+
min_abs : Unused minimum absolute weight threshold (reserved).
|
| 194 |
+
device : Torch device for weight initialisation (default 'cpu').
|
| 195 |
+
"""
|
| 196 |
+
super().__init__(in_features, out_features, False)
|
| 197 |
+
# Sample weights from N(0, 1)
|
| 198 |
+
with torch.no_grad():
|
| 199 |
+
w = torch.normal(mean=0., std=1., size=self.weight.shape, device=device)
|
| 200 |
+
# abs_w = torch.clamp(torch.abs(w), min=torch.tensor(min_abs,device=device))
|
| 201 |
+
# w_clipped = torch.sign(w) * abs_w
|
| 202 |
+
self.weight.copy_(w) #_clipped)
|
| 203 |
+
self.mask = nn.Parameter(torch.ones_like(self.weight), requires_grad=False)
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def set_random_mask(self, keep_prob=0.7):
|
| 207 |
+
"""
|
| 208 |
+
Randomly zero out a fraction of mask entries (Bernoulli dropout-style).
|
| 209 |
+
|
| 210 |
+
Args:
|
| 211 |
+
keep_prob : Probability of keeping each connection (default 0.7).
|
| 212 |
+
Each mask entry is set to 1.0 with this probability and
|
| 213 |
+
0.0 otherwise.
|
| 214 |
+
"""
|
| 215 |
+
with torch.no_grad():
|
| 216 |
+
self.mask[:] = (torch.rand_like(self.mask) < keep_prob).float()
|
| 217 |
+
|
| 218 |
+
def forward(self, input, weight_mask=None):
|
| 219 |
+
"""
|
| 220 |
+
Compute the masked linear transformation.
|
| 221 |
+
|
| 222 |
+
When ``weight_mask`` is None the layer behaves like a standard linear
|
| 223 |
+
layer with weights replaced by ``self.weight * self.mask``.
|
| 224 |
+
When ``weight_mask`` is provided (shape ``(batch, out, in)``), each
|
| 225 |
+
sample in the batch gets its own additional per-element weight scaling,
|
| 226 |
+
enabling sample-specific structural perturbations.
|
| 227 |
+
|
| 228 |
+
Args:
|
| 229 |
+
input : Tensor of shape (batch, in_features).
|
| 230 |
+
weight_mask : Optional tensor of shape (batch, out_features, in_features)
|
| 231 |
+
applied on top of the stored mask. ``None`` means no
|
| 232 |
+
per-sample mask is used.
|
| 233 |
+
|
| 234 |
+
Returns:
|
| 235 |
+
Tensor of shape (batch, out_features).
|
| 236 |
+
"""
|
| 237 |
+
# input: (batch, in_features)
|
| 238 |
+
# self.weight: (out_features, in_features)
|
| 239 |
+
# weight_mask: (batch, out_features, in_features) or None
|
| 240 |
+
masked_weight = self.weight * self.mask
|
| 241 |
+
if weight_mask is None:
|
| 242 |
+
return nn.functional.linear(input, masked_weight, None)
|
| 243 |
+
# Use per-sample masked weights (batched matmul)
|
| 244 |
+
# weight_mask shape: (batch, out_features, in_features)
|
| 245 |
+
# input shape: (batch, in_features)
|
| 246 |
+
# Expand masked_weight for batch: (1, out_features, in_features)
|
| 247 |
+
batch = input.size(0)
|
| 248 |
+
masked_weight = masked_weight.unsqueeze(0) # (1, out_features, in_features)
|
| 249 |
+
# Broadcast for batch
|
| 250 |
+
weight = masked_weight.expand(batch, -1, -1) * weight_mask # (batch, out_features, in_features)
|
| 251 |
+
# Batched matmul: input (batch, in_features) × weight.transpose(-2, -1) (batch, in_features, out_features)
|
| 252 |
+
# Result: (batch, out_features)
|
| 253 |
+
out = torch.bmm(input.unsqueeze(1), weight.transpose(1,2)).squeeze(1)
|
| 254 |
+
return out
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
class SCM_MLP(nn.Module):
|
| 260 |
+
"""
|
| 261 |
+
A multi-layer perceptron used as the functional core of a Structural
|
| 262 |
+
Causal Model (SCM).
|
| 263 |
+
|
| 264 |
+
Each layer is a ``MaskedLinear`` unit followed by additive log-normal
|
| 265 |
+
noise and a randomly chosen activation function. The forward pass
|
| 266 |
+
returns the concatenated hidden activations from all layers, providing a
|
| 267 |
+
rich feature space from which the SCM can select its observable nodes.
|
| 268 |
+
"""
|
| 269 |
+
|
| 270 |
+
def __init__(self, hidden_dim, num_layers, activations, device='cuda'):
|
| 271 |
+
"""
|
| 272 |
+
Initialise the SCM-MLP.
|
| 273 |
+
|
| 274 |
+
Args:
|
| 275 |
+
hidden_dim : Width of every hidden layer (all layers share the same size).
|
| 276 |
+
num_layers : Number of hidden layers.
|
| 277 |
+
activations : List of callables of length ``num_layers``, one activation
|
| 278 |
+
function per layer.
|
| 279 |
+
device : Torch device (default 'cuda').
|
| 280 |
+
"""
|
| 281 |
+
super().__init__()
|
| 282 |
+
self.layers = nn.ModuleList()
|
| 283 |
+
for _ in range(num_layers):
|
| 284 |
+
self.layers.append(MaskedLinear(hidden_dim, hidden_dim,device=device))
|
| 285 |
+
assert len(activations) == len(self.layers)
|
| 286 |
+
self.activations = activations
|
| 287 |
+
|
| 288 |
+
# Per-node noise distributions for each layer and neuron
|
| 289 |
+
self.noise_funcs = [
|
| 290 |
+
[sample_noise_distribution(device) for _ in range(hidden_dim)] # per node
|
| 291 |
+
for _ in range(num_layers)
|
| 292 |
+
]
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
def set_masks(self, keep_prob=0.7):
|
| 296 |
+
"""
|
| 297 |
+
Apply random binary masks to all layers simultaneously.
|
| 298 |
+
|
| 299 |
+
Args:
|
| 300 |
+
keep_prob : Probability of retaining each weight connection
|
| 301 |
+
(default 0.7). Passed through to
|
| 302 |
+
``MaskedLinear.set_random_mask``.
|
| 303 |
+
"""
|
| 304 |
+
for layer in self.layers:
|
| 305 |
+
layer.set_random_mask(keep_prob)
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
def forward(self,
|
| 309 |
+
x):
|
| 310 |
+
"""
|
| 311 |
+
Standard forward pass: apply each masked layer, add per-node log-normal
|
| 312 |
+
noise, apply the activation, and collect hidden activations.
|
| 313 |
+
|
| 314 |
+
Args:
|
| 315 |
+
x : Input tensor of shape (batch, hidden_dim).
|
| 316 |
+
|
| 317 |
+
Returns:
|
| 318 |
+
Tensor of shape (batch, hidden_dim * num_layers) formed by
|
| 319 |
+
concatenating the post-activation outputs of all layers.
|
| 320 |
+
"""
|
| 321 |
+
activations = []
|
| 322 |
+
out = x
|
| 323 |
+
batch_size = x.shape[0]
|
| 324 |
+
for idx, layer in enumerate(self.layers):
|
| 325 |
+
out = layer(out)
|
| 326 |
+
# Generate per-node noise for the whole batch
|
| 327 |
+
noises = torch.stack([
|
| 328 |
+
self.noise_funcs[idx][j](batch_size) # shape (batch,)
|
| 329 |
+
for j in range(out.shape[1])
|
| 330 |
+
], dim=1) # shape (batch, nodes)
|
| 331 |
+
out = out + noises
|
| 332 |
+
out = self.activations[idx](out)
|
| 333 |
+
activations.append(out)
|
| 334 |
+
return torch.cat(activations, dim=1)
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
def forward_with_weight_masks(self,
|
| 338 |
+
x,
|
| 339 |
+
noise_std=0.1,
|
| 340 |
+
weight_masks=None):
|
| 341 |
+
"""
|
| 342 |
+
Forward pass with optional per-sample weight masks.
|
| 343 |
+
|
| 344 |
+
Applies a distinct weight mask to each sample in the batch, enabling
|
| 345 |
+
sample-specific structural perturbations used when generating structural
|
| 346 |
+
outliers.
|
| 347 |
+
|
| 348 |
+
Args:
|
| 349 |
+
x : Input tensor of shape (batch, in_features).
|
| 350 |
+
noise_std : Unused noise standard deviation (reserved for future use).
|
| 351 |
+
weight_masks : List of tensors, one per layer, each of shape
|
| 352 |
+
(batch, out_features, in_features), or ``None`` for
|
| 353 |
+
no per-sample masking.
|
| 354 |
+
|
| 355 |
+
Returns:
|
| 356 |
+
Tensor of shape (batch, hidden_dim * num_layers) formed by
|
| 357 |
+
concatenating the post-activation outputs of all layers.
|
| 358 |
+
"""
|
| 359 |
+
activations = []
|
| 360 |
+
out = x
|
| 361 |
+
batch_size = x.shape[0]
|
| 362 |
+
for idx, layer in enumerate(self.layers):
|
| 363 |
+
mask = weight_masks[idx] if weight_masks is not None else None
|
| 364 |
+
out = layer(out, weight_mask=mask) if mask is not None else layer(out)
|
| 365 |
+
# Generate per-node noise for the whole batch
|
| 366 |
+
noises = torch.stack([
|
| 367 |
+
self.noise_funcs[idx][j](batch_size) # shape (batch,)
|
| 368 |
+
for j in range(out.shape[1])
|
| 369 |
+
], dim=1) # shape (batch, nodes)
|
| 370 |
+
out = out + noises
|
| 371 |
+
out = self.activations[idx](out)
|
| 372 |
+
activations.append(out)
|
| 373 |
+
return torch.cat(activations, dim=1)
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
def forward_with_noise_scales(self,
|
| 378 |
+
x,
|
| 379 |
+
noise_scales=None,
|
| 380 |
+
return_noises=False):
|
| 381 |
+
"""
|
| 382 |
+
Forward pass with optional per-sample, per-node noise scaling.
|
| 383 |
+
|
| 384 |
+
Used during probabilistic outlier generation to amplify the log-normal
|
| 385 |
+
noise on selected nodes, pushing their activations to extreme values.
|
| 386 |
+
|
| 387 |
+
Args:
|
| 388 |
+
x : Input tensor of shape (batch, hidden_dim).
|
| 389 |
+
noise_scales : List of tensors, one per layer, each of shape
|
| 390 |
+
(batch, layer_size) containing multiplicative noise
|
| 391 |
+
scale factors. ``None`` defaults to all-ones (no scaling).
|
| 392 |
+
return_noises: If ``True``, also return the raw noise tensors and the
|
| 393 |
+
applied scale tensors (useful for filtering valid outliers).
|
| 394 |
+
|
| 395 |
+
Returns:
|
| 396 |
+
If ``return_noises`` is ``False``:
|
| 397 |
+
Tensor of shape (batch, hidden_dim * num_layers).
|
| 398 |
+
If ``return_noises`` is ``True``:
|
| 399 |
+
Tuple (activations, all_noises, all_scales) where ``all_noises``
|
| 400 |
+
and ``all_scales`` are lists of per-layer tensors.
|
| 401 |
+
"""
|
| 402 |
+
activations = []
|
| 403 |
+
out = x
|
| 404 |
+
batch_size = x.shape[0]
|
| 405 |
+
all_noises = []
|
| 406 |
+
all_scales = []
|
| 407 |
+
for idx, layer in enumerate(self.layers):
|
| 408 |
+
out = layer(out)
|
| 409 |
+
noises = torch.stack([
|
| 410 |
+
self.noise_funcs[idx][j](batch_size)
|
| 411 |
+
for j in range(out.shape[1])
|
| 412 |
+
], dim=1) # (batch, nodes)
|
| 413 |
+
scales = noise_scales[idx] if noise_scales is not None else torch.ones_like(noises)
|
| 414 |
+
noises = noises * scales
|
| 415 |
+
out = out + noises
|
| 416 |
+
out = self.activations[idx](out)
|
| 417 |
+
activations.append(out)
|
| 418 |
+
if return_noises:
|
| 419 |
+
all_noises.append(noises)
|
| 420 |
+
all_scales.append(scales)
|
| 421 |
+
if return_noises:
|
| 422 |
+
return torch.cat(activations, dim=1), all_noises, all_scales
|
| 423 |
+
else:
|
| 424 |
+
return torch.cat(activations, dim=1)
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
class StructuralCausalModel:
|
| 428 |
+
"""
|
| 429 |
+
A randomly instantiated Structural Causal Model (SCM) for generating
|
| 430 |
+
synthetic anomaly-detection datasets.
|
| 431 |
+
|
| 432 |
+
An MLP with masked layers and per-node log-normal noise serves as the
|
| 433 |
+
causal mechanism. A random subset of the hidden nodes is exposed as the
|
| 434 |
+
observable feature vector. Inliers are sampled directly from the model;
|
| 435 |
+
outliers are produced either by amplifying noise (``'prob'``) or by
|
| 436 |
+
perturbing the causal weights (``'structural'``).
|
| 437 |
+
"""
|
| 438 |
+
|
| 439 |
+
def __init__(self,
|
| 440 |
+
num_features: int = 3,
|
| 441 |
+
min_num_layer: int = 3,
|
| 442 |
+
max_num_layer: int = 5,
|
| 443 |
+
min_hidden_size: int = 8,
|
| 444 |
+
max_hidden_size: int = 8,
|
| 445 |
+
device='cpu',
|
| 446 |
+
outlier_type='structural',
|
| 447 |
+
drop_weight_prob: float = 0.7,
|
| 448 |
+
):
|
| 449 |
+
"""
|
| 450 |
+
Initialise the SCM by sampling a random MLP architecture.
|
| 451 |
+
|
| 452 |
+
The architecture is resampled until the total number of hidden nodes
|
| 453 |
+
(layers × width) is at least ``num_features``. A random subset of
|
| 454 |
+
those nodes is then selected as the observable features.
|
| 455 |
+
|
| 456 |
+
Args:
|
| 457 |
+
num_features : Number of observable output dimensions.
|
| 458 |
+
min_num_layer : Minimum number of MLP hidden layers.
|
| 459 |
+
max_num_layer : Maximum number of MLP hidden layers.
|
| 460 |
+
min_hidden_size : Minimum width of each hidden layer.
|
| 461 |
+
max_hidden_size : Maximum width of each hidden layer.
|
| 462 |
+
device : Torch device (default 'cpu').
|
| 463 |
+
outlier_type : Outlier strategy – ``'measurement'`` for noise-amplification
|
| 464 |
+
outliers, ``'structural'`` for weight-perturbation
|
| 465 |
+
outliers (default ``'structural'``).
|
| 466 |
+
drop_weight_prob: Probability of retaining each MLP weight connection
|
| 467 |
+
(default 0.7).
|
| 468 |
+
"""
|
| 469 |
+
self.device = device
|
| 470 |
+
self.l, self.h = sample_layers_and_nodes(min_num_layer,max_num_layer,min_hidden_size, max_hidden_size)
|
| 471 |
+
while self.l * self.h < num_features:
|
| 472 |
+
self.l, self.h = sample_layers_and_nodes(min_num_layer,max_num_layer,min_hidden_size, max_hidden_size)
|
| 473 |
+
self.activations = [sample_activation(device)[1] for _ in range(self.l)]
|
| 474 |
+
self.mlp = SCM_MLP(self.h, self.l, activations=self.activations, device=device)
|
| 475 |
+
self.mlp = self.mlp.to(device)
|
| 476 |
+
self.mlp.set_masks(keep_prob=drop_weight_prob)
|
| 477 |
+
self.num_features = num_features
|
| 478 |
+
self.chosen_nodes = np.random.choice(self.l * self.h, self.num_features, replace=False)
|
| 479 |
+
self.outlier_type = outlier_type
|
| 480 |
+
|
| 481 |
+
@torch.no_grad()
|
| 482 |
+
def sample_inliers(self, num_samples):
|
| 483 |
+
"""
|
| 484 |
+
Sample inlier observations from the SCM.
|
| 485 |
+
|
| 486 |
+
Feeds a constant all-ones input through the MLP (noise is injected
|
| 487 |
+
inside the MLP), then returns the values at the pre-selected
|
| 488 |
+
observable nodes.
|
| 489 |
+
|
| 490 |
+
Args:
|
| 491 |
+
num_samples : Number of inlier observations to generate.
|
| 492 |
+
|
| 493 |
+
Returns:
|
| 494 |
+
Tensor of shape (num_samples, num_features).
|
| 495 |
+
"""
|
| 496 |
+
# Constant input; randomness comes from per-node noise inside the MLP
|
| 497 |
+
x = torch.ones((num_samples, self.h), device=self.device)
|
| 498 |
+
acts = self.mlp(x) # shape: (num_samples, total_nodes)
|
| 499 |
+
# Return only the selected nodes for each sample
|
| 500 |
+
return acts[:, self.chosen_nodes]
|
| 501 |
+
|
| 502 |
+
@torch.no_grad()
|
| 503 |
+
def sample_measurement_outliers(self,
|
| 504 |
+
num_samples,
|
| 505 |
+
high_noise=5.0,
|
| 506 |
+
high_noise_prob=0.2,
|
| 507 |
+
batch_factor=2):
|
| 508 |
+
"""
|
| 509 |
+
Sample measurement outliers by amplifying per-node noise.
|
| 510 |
+
|
| 511 |
+
A random fraction of nodes receives a noise scale of ``high_noise``
|
| 512 |
+
instead of 1.0. Samples where the amplified noise values actually
|
| 513 |
+
deviate significantly from the base distribution mean are kept;
|
| 514 |
+
the rest are rejected and new candidates are drawn (rejection sampling).
|
| 515 |
+
|
| 516 |
+
Args:
|
| 517 |
+
num_samples : Number of valid outlier samples to collect.
|
| 518 |
+
high_noise : Noise scale applied to the selected anomalous nodes
|
| 519 |
+
(default 5.0).
|
| 520 |
+
high_noise_prob : Probability that any given node receives the high
|
| 521 |
+
noise scale (default 0.2).
|
| 522 |
+
batch_factor : Over-sampling factor to reduce rejection overhead
|
| 523 |
+
(default 2).
|
| 524 |
+
|
| 525 |
+
Returns:
|
| 526 |
+
Tensor of shape (num_samples, num_features).
|
| 527 |
+
"""
|
| 528 |
+
collected = []
|
| 529 |
+
while len(collected) < num_samples:
|
| 530 |
+
batch_size = max(int((num_samples - len(collected)) * batch_factor), 10000)
|
| 531 |
+
x = torch.ones((batch_size, self.h), device=self.device)
|
| 532 |
+
layer_sizes = [layer.out_features for layer in self.mlp.layers]
|
| 533 |
+
noise_scales = random_noise_scales_per_sample(
|
| 534 |
+
batch_size, layer_sizes,
|
| 535 |
+
high_noise=high_noise,
|
| 536 |
+
high_noise_prob=high_noise_prob,
|
| 537 |
+
device=self.device
|
| 538 |
+
)
|
| 539 |
+
activations, all_noises, all_noise_scales = self.mlp.forward_with_noise_scales(
|
| 540 |
+
x, noise_scales=noise_scales, return_noises=True
|
| 541 |
+
)
|
| 542 |
+
batch_mask = torch.ones(batch_size, dtype=torch.bool, device=x.device)
|
| 543 |
+
for idx, (noises, scales) in enumerate(zip(all_noises, all_noise_scales)):
|
| 544 |
+
high_noise_mask = (scales == high_noise)
|
| 545 |
+
if high_noise_mask.any():
|
| 546 |
+
# For each node in this layer, get its mean and std
|
| 547 |
+
means = torch.tensor(
|
| 548 |
+
[float(getattr(self.mlp.noise_funcs[idx][j], 'mu', 0.0)) for j in range(noises.shape[1])],
|
| 549 |
+
device=x.device
|
| 550 |
+
)
|
| 551 |
+
stds = torch.tensor(
|
| 552 |
+
[float(getattr(self.mlp.noise_funcs[idx][j], 'sigma', 1.0)) for j in range(noises.shape[1])],
|
| 553 |
+
device=x.device
|
| 554 |
+
)
|
| 555 |
+
thresholds = means + stds # shape: (nodes,)
|
| 556 |
+
# Broadcast to batch shape
|
| 557 |
+
thresholds = thresholds.unsqueeze(0).expand_as(noises)
|
| 558 |
+
means = means.unsqueeze(0).expand_as(noises)
|
| 559 |
+
# Check (for high noise) if |noise - mean| >= threshold
|
| 560 |
+
valid = ((noises - means).abs() >= thresholds) | (~high_noise_mask)
|
| 561 |
+
valid = valid.all(dim=1)
|
| 562 |
+
batch_mask &= valid
|
| 563 |
+
valid_idx = batch_mask.nonzero(as_tuple=True)[0]
|
| 564 |
+
if len(valid_idx) > 0:
|
| 565 |
+
acts_valid = activations[valid_idx][:, self.chosen_nodes]
|
| 566 |
+
collected.append(acts_valid)
|
| 567 |
+
total = sum(x.shape[0] for x in collected)
|
| 568 |
+
if total >= num_samples:
|
| 569 |
+
collected = torch.cat(collected)[:num_samples]
|
| 570 |
+
break
|
| 571 |
+
return collected
|
| 572 |
+
|
| 573 |
+
|
| 574 |
+
|
| 575 |
+
@torch.no_grad()
|
| 576 |
+
def sample_structural_outliers(self, num_samples, perturb_prob=0.2):
|
| 577 |
+
"""
|
| 578 |
+
Sample structural outliers by perturbing MLP weight connections.
|
| 579 |
+
|
| 580 |
+
For each sample, a random subset of the causal weights feeding into the
|
| 581 |
+
observable nodes is flipped or zeroed, producing activations that are
|
| 582 |
+
statistically unusual in the context of the inlier distribution.
|
| 583 |
+
|
| 584 |
+
Args:
|
| 585 |
+
num_samples : Number of structural outlier observations to generate.
|
| 586 |
+
perturb_prob : Probability of perturbing each eligible weight
|
| 587 |
+
connection (default 0.2).
|
| 588 |
+
|
| 589 |
+
Returns:
|
| 590 |
+
Tensor of shape (num_samples, num_features).
|
| 591 |
+
"""
|
| 592 |
+
x = torch.ones((num_samples, self.h), device=self.device)
|
| 593 |
+
weight_masks = create_weight_mask(
|
| 594 |
+
num_samples, self.mlp.layers, chosen_nodes = self.chosen_nodes, perturb_prob=perturb_prob, device=self.device
|
| 595 |
+
)
|
| 596 |
+
#print('draw weights', time.time()-start)
|
| 597 |
+
acts = self.mlp.forward_with_weight_masks(x, weight_masks=weight_masks)
|
| 598 |
+
return acts[:, self.chosen_nodes]
|
| 599 |
+
|
| 600 |
+
|
| 601 |
+
@torch.no_grad()
|
| 602 |
+
def draw_batched_data(self,
|
| 603 |
+
num_inliers,
|
| 604 |
+
num_local_anomalies):
|
| 605 |
+
"""
|
| 606 |
+
Generate a labelled dataset of inliers and outliers.
|
| 607 |
+
|
| 608 |
+
Delegates to ``sample_inliers`` and either ``sample_measurement_outliers`` or
|
| 609 |
+
``sample_structural_outliers`` depending on ``self.outlier_type``.
|
| 610 |
+
|
| 611 |
+
Args:
|
| 612 |
+
num_inliers : Number of normal observations.
|
| 613 |
+
num_local_anomalies: Number of anomalous observations.
|
| 614 |
+
|
| 615 |
+
Returns:
|
| 616 |
+
Tuple ``(raw_inliers, raw_local_anomalies)`` where each element is a
|
| 617 |
+
Tensor of shape (n, num_features).
|
| 618 |
+
"""
|
| 619 |
+
raw_inliers = self.sample_inliers(num_inliers)
|
| 620 |
+
if self.outlier_type == 'measurement':
|
| 621 |
+
raw_local_anomalies = self.sample_measurement_outliers(num_samples=num_local_anomalies)
|
| 622 |
+
elif self.outlier_type == 'structural':
|
| 623 |
+
raw_local_anomalies = self.sample_structural_outliers(num_samples=num_local_anomalies)
|
| 624 |
+
return raw_inliers, raw_local_anomalies
|
| 625 |
+
|
| 626 |
+
|
| 627 |
+
|
| 628 |
+
def make_measurementSCM(max_feature_dim: int,
|
| 629 |
+
min_num_layer: int,
|
| 630 |
+
max_num_layer: int,
|
| 631 |
+
min_hidden_size: int,
|
| 632 |
+
max_hidden_size: int,
|
| 633 |
+
alpha: float,
|
| 634 |
+
beta: float,
|
| 635 |
+
device):
|
| 636 |
+
"""
|
| 637 |
+
Factory function for a measurement-outlier SCM.
|
| 638 |
+
|
| 639 |
+
Constructs a ``StructuralCausalModel`` configured to generate outliers via
|
| 640 |
+
noise amplification (``outlier_type='measurement'``) with a fixed weight-keep
|
| 641 |
+
probability of 0.6.
|
| 642 |
+
|
| 643 |
+
Args:
|
| 644 |
+
max_feature_dim : Number of observable feature dimensions.
|
| 645 |
+
min_num_layer : Minimum number of MLP hidden layers.
|
| 646 |
+
max_num_layer : Maximum number of MLP hidden layers.
|
| 647 |
+
min_hidden_size : Minimum hidden-layer width.
|
| 648 |
+
max_hidden_size : Maximum hidden-layer width.
|
| 649 |
+
alpha : Unused (reserved for future parameterisation).
|
| 650 |
+
beta : Unused (reserved for future parameterisation).
|
| 651 |
+
device : Torch device string.
|
| 652 |
+
|
| 653 |
+
Returns:
|
| 654 |
+
A freshly initialised ``StructuralCausalModel`` instance.
|
| 655 |
+
"""
|
| 656 |
+
return StructuralCausalModel(num_features = max_feature_dim,
|
| 657 |
+
min_num_layer=min_num_layer,
|
| 658 |
+
max_num_layer = max_num_layer,
|
| 659 |
+
min_hidden_size = min_hidden_size,
|
| 660 |
+
max_hidden_size = max_hidden_size,
|
| 661 |
+
device = device,
|
| 662 |
+
outlier_type = 'measurement',
|
| 663 |
+
drop_weight_prob = 0.6)
|
| 664 |
+
|
| 665 |
+
|
| 666 |
+
def make_structuralSCM(max_feature_dim: int,
|
| 667 |
+
min_num_layer: int,
|
| 668 |
+
max_num_layer: int,
|
| 669 |
+
min_hidden_size: int,
|
| 670 |
+
max_hidden_size: int,
|
| 671 |
+
alpha: float,
|
| 672 |
+
beta: float,
|
| 673 |
+
device):
|
| 674 |
+
"""
|
| 675 |
+
Factory function for a structural-outlier SCM.
|
| 676 |
+
|
| 677 |
+
Constructs a ``StructuralCausalModel`` configured to generate outliers via
|
| 678 |
+
causal weight perturbation (``outlier_type='structural'``) with a fixed
|
| 679 |
+
weight-keep probability of 0.6.
|
| 680 |
+
|
| 681 |
+
Args:
|
| 682 |
+
max_feature_dim : Number of observable feature dimensions.
|
| 683 |
+
min_num_layer : Minimum number of MLP hidden layers.
|
| 684 |
+
max_num_layer : Maximum number of MLP hidden layers.
|
| 685 |
+
min_hidden_size : Minimum hidden-layer width.
|
| 686 |
+
max_hidden_size : Maximum hidden-layer width.
|
| 687 |
+
alpha : Unused (reserved for future parameterisation).
|
| 688 |
+
beta : Unused (reserved for future parameterisation).
|
| 689 |
+
device : Torch device string.
|
| 690 |
+
|
| 691 |
+
Returns:
|
| 692 |
+
A freshly initialised ``StructuralCausalModel`` instance.
|
| 693 |
+
"""
|
| 694 |
+
return StructuralCausalModel(num_features = max_feature_dim,
|
| 695 |
+
min_num_layer=min_num_layer,
|
| 696 |
+
max_num_layer = max_num_layer,
|
| 697 |
+
min_hidden_size = min_hidden_size,
|
| 698 |
+
max_hidden_size = max_hidden_size,
|
| 699 |
+
device = device,
|
| 700 |
+
outlier_type = 'structural',
|
| 701 |
+
drop_weight_prob = 0.6)
|
| 702 |
+
|