| from copula import CopulaGenerator |
| from gmm import make_NdMclusterGMM |
| from scm import make_structuralSCM |
|
|
| import math |
| import os |
| import random |
|
|
| import numpy as np |
| import torch |
| from sklearn.metrics import roc_auc_score |
| from sklearn.neighbors import LocalOutlierFactor |
| from tqdm import tqdm |
|
|
| |
| def set_seed(seed: int = 0): |
| |
| random.seed(seed) |
| |
| np.random.seed(seed) |
| |
| torch.manual_seed(seed) |
| |
| if torch.cuda.is_available(): |
| torch.cuda.manual_seed(seed) |
| torch.cuda.manual_seed_all(seed) |
| torch.backends.cudnn.deterministic = True |
| torch.backends.cudnn.benchmark = False |
| |
| def evaluate_with_lof(X, y, num_outliers): |
| contamination = num_outliers / len(y) |
| lof = LocalOutlierFactor(n_neighbors=20, contamination=contamination) |
| _ = lof.fit_predict(X) |
| scores = -lof.negative_outlier_factor_ |
| return roc_auc_score(y, scores) |
|
|
|
|
| def run_generation( |
| model_builder, |
| save_path_builder, |
| accept_auc, |
| base_seed, |
| dimension_range, |
| samples_per_dim_range=32, |
| device='cuda:0', |
| ): |
| for j, dimension in tqdm(enumerate(dimension_range)): |
| count = 0 |
| i = 0 |
| begin_idx = j * samples_per_dim_range |
|
|
| while count < samples_per_dim_range: |
| set_seed(base_seed + i) |
| dim = np.random.randint(low=dimension[0], high=dimension[1]) |
|
|
| num_inliers = np.random.randint(1_000, 5_000) |
| outliers_ratio = np.random.uniform(0.05, 0.15) |
| num_outliers = int(outliers_ratio * num_inliers) |
|
|
| model = model_builder(dim=dim, device=device) |
| X_in, X_out = model.draw_batched_data(num_inliers, num_outliers) |
|
|
| X = torch.cat([X_in, X_out]).cpu().numpy() |
| y = np.concatenate([np.zeros(num_inliers), np.ones(num_outliers)]) |
|
|
| auc = evaluate_with_lof(X, y, num_outliers) |
| if accept_auc(auc): |
| saved = begin_idx + count |
| output_path = save_path_builder(saved) |
| os.makedirs(os.path.dirname(output_path), exist_ok=True) |
| np.savez(output_path, X=X, y=y) |
| count += 1 |
| i += 1 |
|
|
| print( |
| f"For dimension [{dimension[0]}, {dimension[1]}), accepted ratio:", |
| (count / i), |
| ) |
|
|
|
|
| def build_gmm_model(dim, device): |
| num_cluster = np.random.randint(low=2, high=6) |
| max_mean = np.random.randint(low=2, high=6) |
| max_var = np.random.randint(low=2, high=6) |
| return make_NdMclusterGMM( |
| dim=dim, |
| num_cluster=num_cluster, |
| weights=torch.tensor([1 / num_cluster] * num_cluster, device=device), |
| max_mean=max_mean, |
| max_var=max_var, |
| inflate_full=False, |
| sub_dims=None, |
| percentile=0.9, |
| delta=0.05, |
| device=device, |
| ) |
|
|
|
|
| def build_copula_model(dim, device): |
| return CopulaGenerator(num_dims=dim, device=device) |
|
|
|
|
| def build_scm_model(dim, device): |
| max_num_layer = 5 |
| min_num_layer = max(int(np.sqrt(dim)) - 3, 2) |
| min_hidden_size = max(int(math.floor(dim / min_num_layer)) + 2, 2) |
| max_hidden_size = min(min_hidden_size + 7, 40) |
| return make_structuralSCM( |
| max_feature_dim=dim, |
| min_num_layer=min_num_layer, |
| max_num_layer=max_num_layer, |
| min_hidden_size=min_hidden_size, |
| max_hidden_size=max_hidden_size, |
| alpha=1.5, |
| beta=4.0, |
| device=device, |
| ) |
|
|
|
|
| if __name__ == '__main__': |
| dimension_range = [(2, 21), (21, 41), (41, 61), (61, 81), (81, 101)] |
|
|
| print('generate GMM based') |
| run_generation( |
| model_builder=build_gmm_model, |
| save_path_builder=lambda saved: f"gaussian/gaussian_{saved}.npz", |
| accept_auc=lambda auc: auc < 0.95, |
| base_seed=52324, |
| dimension_range=dimension_range, |
| ) |
|
|
| print('generate copula based') |
| run_generation( |
| model_builder=build_copula_model, |
| save_path_builder=lambda saved: f"copula_disturb/copuladisturb_{saved}.npz", |
| accept_auc=lambda auc: 0.5 < auc < 0.95, |
| base_seed=52324, |
| dimension_range=dimension_range, |
| ) |
|
|
| print('generate scm based') |
| run_generation( |
| model_builder=build_scm_model, |
| save_path_builder=lambda saved: f"scm_contextual/scmcontextual_{saved}.npz", |
| accept_auc=lambda auc: 0.5 < auc < 0.95, |
| base_seed=52324, |
| dimension_range=dimension_range, |
| ) |
|
|