├── models ├── __init__.py ├── cae_model.py ├── gan_model.py └── classifier_model.py ├── helpers ├── __init__.py ├── noise_generator.py ├── noise_generator_full.py ├── sample_generator.py └── base_model.py ├── trainers ├── __init__.py ├── gan_sampler.py ├── cae_train.py ├── gan_train.py └── gan_cae_train.py ├── data_handler ├── __init__.py ├── embedding_dim.py ├── data_reader.py ├── classifier_transformer.py ├── data_sampler.py └── data_transformer.py ├── reconstructor ├── __init__.py ├── main_cae_constructor.py └── cae_reconstructor.py ├── saved_models └── __init__.py ├── requirements.txt ├── dataset └── adult │ └── meta_data.json ├── README.md ├── .gitignore ├── sampler.py ├── main.py ├── commands_sampler.txt ├── commands.txt ├── commands_sampler1.txt └── LICENSE /models/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /helpers/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /trainers/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /data_handler/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /reconstructor/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /saved_models/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | torch 2 | torchvision 3 | torchaudio 4 | pandas 5 | joblib 6 | rdt 7 | wandb -------------------------------------------------------------------------------- /data_handler/embedding_dim.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | 3 | 4 | def cal_dim(df, categorical_columns, labels): 5 | X = df.drop(labels, axis=1) 6 | numerical_columns = [col for col in df.columns if col not in categorical_columns] 7 | categorical_columns = [col for col in categorical_columns if col not in labels] 8 | X_num = X[numerical_columns] 9 | cat_dims = [int(X[col].nunique()) for col in categorical_columns] 10 | # Define the embedding size per categorical column (rule of thumb: min(50, (size+1)//2)) 11 | emb_dims = [(size, min(50, (size + 1) // 2)) for size in cat_dims] 12 | num_feature_no = X_num.shape[1] 13 | output_sizes = [df[label].nunique() for label in labels] 14 | 15 | return num_feature_no, emb_dims, output_sizes 16 | -------------------------------------------------------------------------------- /dataset/adult/meta_data.json: -------------------------------------------------------------------------------- 1 | { 2 | "columns": { 3 | "age": { 4 | "sdtype": "numerical" 5 | }, 6 | "workclass": { 7 | "sdtype": "categorical" 8 | }, 9 | "fnlwgt": { 10 | "sdtype": "numerical" 11 | }, 12 | "education": { 13 | "sdtype": "categorical" 14 | }, 15 | "education-num": { 16 | "sdtype": "numerical" 17 | }, 18 | "marital-status": { 19 | "sdtype": "categorical" 20 | }, 21 | "occupation": { 22 | "sdtype": "categorical" 23 | }, 24 | "relationship": { 25 | "sdtype": "categorical" 26 | }, 27 | "race": { 28 | "sdtype": "categorical" 29 | }, 30 | "sex": { 31 | "sdtype": "categorical" 32 | }, 33 | "capital-gain": { 34 | "sdtype": "numerical" 35 | }, 36 | "capital-loss": { 37 | "sdtype": "numerical" 38 | }, 39 | "hours-per-week": { 40 | "sdtype": "numerical" 41 | }, 42 | "native-country": { 43 | "sdtype": "categorical" 44 | }, 45 | "income": { 46 | "sdtype": "categorical" 47 | } 48 | }, 49 | "METADATA_SPEC_VERSION": "SINGLE_TABLE_V1" 50 | } -------------------------------------------------------------------------------- /data_handler/data_reader.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | import torch 4 | import pandas as pd 5 | 6 | 7 | def read_csv(csv_filename, header=True): 8 | """Read a csv file.""" 9 | data = pd.read_csv(csv_filename,low_memory=False, header='infer' if header else None) 10 | return data 11 | 12 | 13 | def save_csv(df, dataset, model, samples): 14 | """Save a csv file.""" 15 | df.to_csv(f"results/{dataset}_{model}_{samples}.csv", index=False) 16 | 17 | 18 | def get_discrete_columns(json_path): 19 | with open(json_path, 'r') as f: 20 | data = json.load(f) 21 | columns = data.get("columns", {}) 22 | discrete_columns = [col for col, details in columns.items() if details.get("sdtype") in ["categorical", "boolean"]] 23 | return discrete_columns 24 | 25 | 26 | def get_device(): 27 | if torch.backends.mps.is_available(): 28 | device = torch.device("mps") 29 | else: 30 | device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') 31 | return device 32 | 33 | 34 | def get_model_path(model, dataset, model_name): 35 | model_path = f"saved_models/{model}/{dataset}/{model_name}.pth" 36 | return model_path 37 | -------------------------------------------------------------------------------- /models/cae_model.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | 4 | 5 | class CAE(nn.Module): 6 | def __init__(self, input_size, hidden_size, latent_size): 7 | super(CAE, self).__init__() 8 | 9 | # Encoding layers 10 | self.encoder1 = nn.Linear(input_size, hidden_size) 11 | self.encoder2 = nn.Linear(hidden_size, latent_size) 12 | 13 | # Decoding layers 14 | self.decoder1 = nn.Linear(latent_size, hidden_size) 15 | self.decoder2 = nn.Linear(hidden_size, input_size) 16 | 17 | def encode(self, x): 18 | x = torch.sigmoid(self.encoder1(x)) 19 | latent = torch.sigmoid(self.encoder2(x)) 20 | return latent 21 | 22 | def decode(self, latent): 23 | x = torch.sigmoid(self.decoder1(latent)) 24 | decoded = torch.sigmoid(self.decoder2(x)) 25 | return decoded 26 | 27 | def forward(self, x): 28 | latent = self.encode(x) 29 | decoded = self.decode(latent) 30 | return latent, decoded 31 | 32 | def jacobian_penalty(self, x, h): 33 | # Ensure the tensor for which we compute the Jacobian has gradient computation enabled 34 | x.requires_grad_(True) 35 | jacobian = torch.autograd.grad(h, x, grad_outputs=torch.ones_like(h), create_graph=True)[0] 36 | penalty = torch.norm(jacobian, p=2) ** 2 37 | return penalty 38 | -------------------------------------------------------------------------------- /reconstructor/main_cae_constructor.py: -------------------------------------------------------------------------------- 1 | """CLI.""" 2 | 3 | from data_handler.data_reader import read_csv 4 | from reconstructor.cae_reconstructor import CAEReconstructor 5 | import torch 6 | 7 | 8 | if __name__ == '__main__': 9 | discrete_columns = [ 10 | 'workclass', 11 | 'education', 12 | 'marital-status', 13 | 'occupation', 14 | 'relationship', 15 | 'race', 16 | 'sex', 17 | 'native-country', 18 | 'income' 19 | ] 20 | 21 | real_data = read_csv("../dataset/adults/adult.csv") 22 | 23 | 24 | # device = torch.device( 25 | # 'cuda' if torch.cuda.is_available() else ('mps' if torch.backends.mps.is_available() else 'cpu')) 26 | 27 | device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') 28 | model_path = '/ctgan/saved_models/cae_final_saved_model_09242023.pth' 29 | # model.load_state_dict(torch.load('/mnt/d/sources/cgan/saved_models/transformer_final_saved_model_09162023.pth')) 30 | 31 | cae = CAEReconstructor(model_path=model_path,verbose=True, device=device) 32 | input_data = real_data[:5] 33 | print(input_data) 34 | outputs = cae.fit(real_data, input_data , discrete_columns) 35 | 36 | 37 | # Decode the data using trained model 38 | # model.eval() 39 | # sample_latent = torch.randn(1, 64) 40 | # decoded_data = model.decode(sample_latent) 41 | # print(decoded_data.shape) 42 | 43 | # main() -------------------------------------------------------------------------------- /helpers/noise_generator.py: -------------------------------------------------------------------------------- 1 | from helpers.base_model import BaseModel, random_state 2 | from data_handler.data_transformer import DataTransformer 3 | from data_handler.data_sampler import DataSampler 4 | from models.cae_model import CAE 5 | import torch 6 | import pandas as pd 7 | import numpy as np 8 | 9 | 10 | class NoiseGenerator(BaseModel): 11 | """Contractive Autoencoder 12 | """ 13 | 14 | def __init__(self, model_path, input_size, hidden_size=256, latent_size=64, device='cpu'): 15 | self._input_size = input_size 16 | self._hidden_size = hidden_size 17 | self._latent_size = latent_size 18 | 19 | self._device = torch.device(device) 20 | self._model_path = model_path 21 | 22 | self._loaded_model = None 23 | 24 | def forward(self, n_samples=2, input_data = None, discrete_columns=None): 25 | self._loaded_model = CAE(self._input_size, self._hidden_size, self._latent_size).to(self._device) 26 | self._loaded_model.load_state_dict(torch.load(self._model_path)) 27 | self._loaded_model.eval() 28 | 29 | # tensor = torch.randn(n_samples, 64).to(self._device) 30 | # normalized_tensor = torch.sigmoid(tensor) 31 | 32 | mean = torch.zeros(n_samples, 64, device=self._device) 33 | std = mean + 1 34 | normalized_tensor = torch.normal(mean=mean, std=std) 35 | noise = self._loaded_model.decode(normalized_tensor) 36 | 37 | return noise 38 | -------------------------------------------------------------------------------- /helpers/noise_generator_full.py: -------------------------------------------------------------------------------- 1 | from helpers.base_model import BaseModel, random_state 2 | from data_handler.data_transformer import DataTransformer 3 | from data_handler.data_sampler import DataSampler 4 | from models.cae_model import CAE 5 | import torch 6 | import pandas as pd 7 | import numpy as np 8 | 9 | 10 | class NoiseGenerator(BaseModel): 11 | """Contractive Autoencoder 12 | """ 13 | 14 | def __init__(self, model_path, input_size, hidden_size=256, latent_size=64, device='cpu'): 15 | super(NoiseGenerator, self).__init__() 16 | self._input_size = input_size 17 | self._hidden_size = hidden_size 18 | self._latent_size = latent_size 19 | 20 | self._device = torch.device(device) 21 | self._model_path = model_path 22 | 23 | self._loaded_model = None 24 | 25 | def forward(self, n_samples=2, input_data = None, discrete_columns=None): 26 | self._loaded_model = CAE(self._input_size, self._hidden_size, self._latent_size).to(self._device) 27 | # self._loaded_model.load_state_dict(torch.load(self._model_path)) 28 | self._loaded_model.load_state_dict(torch.load(self._model_path, map_location=self._device)) 29 | self._loaded_model.eval() 30 | 31 | # tensor = torch.randn(n_samples, 64).to(self._device) 32 | # normalized_tensor = torch.sigmoid(tensor) 33 | 34 | mean = torch.zeros(n_samples, self._input_size, device=self._device) 35 | std = mean + 1 36 | normalized_tensor = torch.normal(mean=mean, std=std) 37 | latent, noise = self._loaded_model(normalized_tensor) 38 | 39 | return noise 40 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Context Aware Conditional Tabular GAN Training CLI 2 | 3 | This repository contains a command-line interface (CLI) tool for training deep learning models. 4 | 5 | ## Requirements 6 | 7 | This project requires Python 3.8 or later. The required packages are listed in the requirements.txt file. To install these packages, use the following command: 8 | `pip install -r requirements.txt` 9 | ### Data 10 | 11 | This tool assumes CSV data and metadata in JSON format in the dataset_test directory. Alter `DEFAULT_DATA_PATH` and `DEFAULT_METADATA_PATH` in the script for different directories. 12 | 13 | 14 | ## Usage 15 | 16 | The main script is `main.py`, and it can be run from the command-line using the following syntax: 17 | `python main.py --epochs --train_type --data_path --metadata_path --device --dataset_name --pretrained_cae --labels --debug ` 18 | * `number_of_epochs`: The number of epochs. Default is 300. 19 | * `training_type`: The type of training run. Can be 'cae', 'cae_gan' or 'gan'. Default is 'cae_gan'. 20 | * `path_to_data`: The path where CSV data is located. 21 | * `path_to_metadata`: The path where JSON metadata is located. 22 | * `device`: The device on which to train the models. It could be 'cpu', 'mps' or 'cuda'. Default is 'cpu'. 23 | * `dataset_name`: A tag used for identifying the dataset. 24 | * `pretrained_model_name`: The name of a pretrained CAE model. 25 | * `labels`: A list of labels for the classifier. 26 | * `debug_flag`: A boolean flag using wandb for debugging purposes. 27 | 28 | ## Example 29 | 30 | Here is an example of how you might use this script: 31 | `python main.py --epochs 100 --train_type gan --data_path dataset/adult/adult.csv --metadata_path dataset/adult/meta_data.json --device cuda --dataset_name adult --pretrained_cae cae_adult_09262023_mps --labels '["income"]' --debug True` 32 | 33 | In this example, we're performing 'gan' training for 100 epochs on the 'adult' dataset using the GPU ('cuda'). -------------------------------------------------------------------------------- /data_handler/classifier_transformer.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | from sklearn.preprocessing import LabelEncoder 4 | from torch.utils.data import DataLoader, TensorDataset 5 | 6 | 7 | class ClassifierDataTransformer(nn.Module): 8 | def __init__(self, categorical_columns, label): 9 | super(ClassifierDataTransformer, self).__init__() 10 | # self.categorical_columns = categorical_columns 11 | self.categorical_columns = [col for col in categorical_columns if col not in label] 12 | self.label = label 13 | 14 | def forward(self, data): 15 | # Split features and target label 16 | X = data.drop(self.label, axis=1) 17 | y = data[self.label] 18 | # numerical_columns = [col for col in data.columns if col not in self.categorical_columns + [self.label]] 19 | numerical_columns = [col for col in data.columns if col not in self.categorical_columns + self.label] 20 | # Separate categorical and numerical data 21 | X_num = X[numerical_columns] 22 | 23 | # Initialize label encoders for each categorical column 24 | label_encoders = {} 25 | for col in self.categorical_columns: 26 | label_encoders[col] = LabelEncoder() 27 | X[col] = label_encoders[col].fit_transform(X[col]) 28 | 29 | # Convert categorical columns to tensors 30 | X_cat = torch.tensor(X[self.categorical_columns].values, dtype=torch.int64) 31 | 32 | # Convert numerical columns to tensor 33 | X_num = torch.tensor(X_num.values, dtype=torch.float32) 34 | 35 | # Convert the target variable to a tensor 36 | label_encoder = LabelEncoder() 37 | # y = label_encoder.fit_transform(y.ravel()) 38 | y = label_encoder.fit_transform(y.values.ravel()) 39 | y = torch.tensor(y, dtype=torch.float32) 40 | y = y.unsqueeze(1) # Add an extra dimension 41 | 42 | # Create TensorDatasets for training and testing data 43 | dataset = TensorDataset(X_cat, X_num, y) 44 | 45 | data_loader = DataLoader(dataset=dataset, batch_size=len(dataset), shuffle=True) 46 | 47 | return data_loader 48 | -------------------------------------------------------------------------------- /helpers/sample_generator.py: -------------------------------------------------------------------------------- 1 | from data_handler.data_reader import read_csv 2 | from helpers.noise_generator_full import NoiseGenerator 3 | from models.gan_model import Generator 4 | from trainers.gan_sampler import CTGAN 5 | import torch 6 | 7 | if __name__ == '__main__': 8 | # discrete_columns = [ 9 | # 'workclass', 10 | # 'education', 11 | # 'marital-status', 12 | # 'occupation', 13 | # 'relationship', 14 | # 'race', 15 | # 'sex', 16 | # 'native-country', 17 | # 'income' 18 | # ] 19 | 20 | discrete_columns = ['protocol_type', 'service', 'flag', 'land', 'logged_in', 'lroot_shell', 'is_guest_login', 21 | 'label'] 22 | 23 | # real_data = read_csv("/mnt/d/sources/ca-cgan/ctgan/dataset/adult.csv") 24 | # input_size = 156 25 | real_data = read_csv("/mnt/d/sources/ca-cgan/ctgan/dataset/kddcup99e.csv") 26 | input_size = 261 27 | 28 | device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') 29 | 30 | # cae_path = '/mnt/d/sources/ca-cgan/ctgan/saved_models/cae_final_saved_model_09262023.pth' 31 | cae_path = '/mnt/d/sources/ca-cgan/ctgan/saved_models/kdd/cae/cae_final_saved_model_kdd_10202023.pth' 32 | noise_generator = NoiseGenerator(model_path=cae_path, input_size=input_size, hidden_size=256, latent_size=64, 33 | device=device) 34 | 35 | # model_path = '/mnt/d/sources/ca-cgan/ctgan/saved_models/generator_cae_final_saved_model_09272023_cuda_latent_random_noise.pth' 36 | # model_name = "generator_cae_final_saved_model_09272023_cuda_full_normal_noise" 37 | # model_name = "generator_cae_final_saved_model_09272023_cuda_latent_normal_noise" 38 | model_name = "kdd_vanilla_gan" 39 | 40 | model_path = '/mnt/d/sources/ca-cgan/ctgan/saved_models/kdd/vanila_gan/generator_final_saved_model_10212023_cuda.pth' 41 | 42 | ctgan = CTGAN(saved_generator=model_path, verbose=True, save_directory='saved_models', 43 | noise_generator=noise_generator, 44 | device=device) 45 | ctgan.fit(real_data, discrete_columns) 46 | 47 | # model_path = '/Users/mfallahi/Sources/ca-cgan/ctgan/saved_models/cae_final_saved_model_09242023.pth' 48 | 49 | # generator.load_state_dict(torch.load(model_path)) 50 | # generator.eval() 51 | 52 | # loaded_model = ctgan.load(model_path) 53 | # 54 | synthetic_data = ctgan.sample(10000) 55 | 56 | synthetic_data.to_csv(f"/mnt/d/sources/ca-cgan/ctgan/results/{model_name}.csv", index=False) 57 | 58 | print(synthetic_data.head(10)) 59 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | .idea 131 | evaluation 132 | dataset_test 133 | results 134 | local_saved_model 135 | local_playground 136 | README1.md 137 | output*.txt 138 | wandb -------------------------------------------------------------------------------- /models/gan_model.py: -------------------------------------------------------------------------------- 1 | import torch.nn as nn 2 | import torch 3 | 4 | 5 | class Discriminator(nn.Module): 6 | """Discriminator for the CTGAN.""" 7 | 8 | def __init__(self, input_dim, discriminator_dim, pac=10, slope=0.2, dropout=0.5): 9 | super(Discriminator, self).__init__() 10 | dim = input_dim * pac 11 | self.pac = pac 12 | self.pacdim = dim 13 | seq = [] 14 | for item in list(discriminator_dim): 15 | seq += [nn.Linear(dim, item), nn.LeakyReLU(slope), nn.Dropout(dropout)] 16 | dim = item 17 | 18 | seq += [nn.Linear(dim, 1)] 19 | self.seq = nn.Sequential(*seq) 20 | 21 | def calc_gradient_penalty(self, real_data, fake_data, device='cpu', pac=10, lambda_=10): 22 | """Compute the gradient penalty.""" 23 | alpha = torch.rand(real_data.size(0) // pac, 1, 1, device=device) 24 | alpha = alpha.repeat(1, pac, real_data.size(1)) 25 | alpha = alpha.view(-1, real_data.size(1)) 26 | 27 | interpolates = alpha * real_data + ((1 - alpha) * fake_data) 28 | 29 | disc_interpolates = self(interpolates) 30 | 31 | gradients = torch.autograd.grad( 32 | outputs=disc_interpolates, inputs=interpolates, 33 | grad_outputs=torch.ones(disc_interpolates.size(), device=device), 34 | create_graph=True, retain_graph=True, only_inputs=True 35 | )[0] 36 | 37 | gradients_view = gradients.view(-1, pac * real_data.size(1)).norm(2, dim=1) - 1 38 | gradient_penalty = ((gradients_view) ** 2).mean() * lambda_ 39 | 40 | return gradient_penalty 41 | 42 | def forward(self, input_): 43 | """Apply the Discriminator to the `input_`.""" 44 | assert input_.size()[0] % self.pac == 0 45 | return self.seq(input_.view(-1, self.pacdim)) 46 | 47 | 48 | class Residual(nn.Module): 49 | """Residual layer for the CTGAN.""" 50 | 51 | def __init__(self, i, o): 52 | super(Residual, self).__init__() 53 | self.fc = nn.Linear(i, o) 54 | self.bn = nn.BatchNorm1d(o) 55 | self.relu = nn.ReLU() 56 | 57 | def forward(self, input_): 58 | """Apply the Residual layer to the `input_`.""" 59 | out = self.fc(input_) 60 | out = self.bn(out) 61 | out = self.relu(out) 62 | return torch.cat([out, input_], dim=1) 63 | 64 | 65 | class Generator(nn.Module): 66 | """Generator for the CTGAN.""" 67 | 68 | def __init__(self, embedding_dim, generator_dim, data_dim): 69 | super(Generator, self).__init__() 70 | dim = embedding_dim 71 | seq = [] 72 | for item in list(generator_dim): 73 | seq += [Residual(dim, item)] 74 | dim += item 75 | seq.append(nn.Linear(dim, data_dim)) 76 | self.seq = nn.Sequential(*seq) 77 | 78 | def forward(self, input_): 79 | """Apply the Generator to the `input_`.""" 80 | data = self.seq(input_) 81 | return data 82 | -------------------------------------------------------------------------------- /models/classifier_model.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | 4 | 5 | # class ClassifierModel(nn.Module): 6 | # def __init__(self, emb_dims, no_of_num): 7 | # super(ClassifierModel, self).__init__() 8 | # self.emb_layers = EntityEmbedding(emb_dims) 9 | # self.no_of_cat = sum([emb_dim for _, emb_dim in emb_dims]) 10 | # self.no_of_num = no_of_num 11 | # 12 | # # Define additional layers 13 | # self.lin1 = nn.Linear(self.no_of_cat + no_of_num, 200) 14 | # self.lin2 = nn.Linear(200, 100) 15 | # self.lin3 = nn.Linear(100, 50) 16 | # self.out = nn.Linear(50, 1) 17 | # self.bn1 = nn.BatchNorm1d(200) 18 | # self.bn2 = nn.BatchNorm1d(100) 19 | # self.bn3 = nn.BatchNorm1d(50) 20 | # self.dropout = nn.Dropout(0.3) 21 | # 22 | # def forward(self, x_cat, x_num): 23 | # x_cat = self.emb_layers(x_cat) 24 | # x = torch.cat([x_cat, x_num], 1) 25 | # x = self.lin1(x) 26 | # x = self.bn1(x) 27 | # x = torch.relu(x) 28 | # x = self.lin2(x) 29 | # x = self.bn2(x) 30 | # x = torch.relu(x) 31 | # x = self.lin3(x) 32 | # x = self.bn3(x) 33 | # x = torch.relu(x) 34 | # x = self.out(x) 35 | # return x 36 | class ClassifierModel(nn.Module): 37 | def __init__(self, emb_dims, no_of_num, output_sizes): 38 | super(ClassifierModel, self).__init__() 39 | self.emb_layers = EntityEmbedding(emb_dims) 40 | self.no_of_cat = sum([emb_dim for _, emb_dim in emb_dims]) 41 | self.no_of_num = no_of_num 42 | # Define additional layers 43 | self.lin1 = nn.Linear(self.no_of_cat + no_of_num, 200) 44 | self.lin2 = nn.Linear(200, 100) 45 | self.lin3 = nn.Linear(100, 50) 46 | 47 | self.outs = nn.ModuleList([nn.Linear(50, size) for size in output_sizes]) 48 | 49 | self.bn1 = nn.BatchNorm1d(200) 50 | self.bn2 = nn.BatchNorm1d(100) 51 | self.bn3 = nn.BatchNorm1d(50) 52 | self.dropout = nn.Dropout(0.3) 53 | 54 | def forward(self, x_cat, x_num): 55 | x_cat = self.emb_layers(x_cat) 56 | x = torch.cat([x_cat, x_num], 1) 57 | x = self.lin1(x) 58 | x = self.bn1(x) 59 | x = torch.relu(x) 60 | x = self.lin2(x) 61 | x = self.bn2(x) 62 | x = torch.relu(x) 63 | x = self.lin3(x) 64 | x = self.bn3(x) 65 | x = torch.relu(x) 66 | outs = [out(x) for out in self.outs] 67 | return outs 68 | 69 | class EntityEmbedding(nn.Module): 70 | def __init__(self, emb_dims): 71 | super(EntityEmbedding, self).__init__() 72 | # Create an embedding layer for each pair in emb_dims 73 | self.embeddings = nn.ModuleList([nn.Embedding(cat_dim, emb_dim) for cat_dim, emb_dim in emb_dims]) 74 | 75 | def forward(self, x_cat): 76 | # Apply each embedding layer to the corresponding categorical feature 77 | x_cat = [emb(x_cat[:, i]) for i, emb in enumerate(self.embeddings)] 78 | x_cat = torch.cat(x_cat, 1) 79 | return x_cat 80 | -------------------------------------------------------------------------------- /sampler.py: -------------------------------------------------------------------------------- 1 | """CLI.""" 2 | 3 | import argparse 4 | 5 | from data_handler.data_reader import read_csv, get_discrete_columns, get_device, get_model_path, save_csv 6 | from data_handler.data_transformer import DataTransformer 7 | from trainers.gan_sampler import CTGAN 8 | from helpers.noise_generator_full import NoiseGenerator 9 | import ast 10 | 11 | TRAIN_TYPE = "gan" # gan or cae_gan 12 | DATA_PATH = "dataset_test/adult/adult.csv" 13 | METADATA_PATH = "dataset_test/adult/meta_data.json" 14 | DEVICE = get_device() 15 | DATASET_NAME = "adult" 16 | PRETRAINED_CAE = "cae_adult_09262023_mps" 17 | PRETRAINED_GEN = "vanilla_generator_adult_01282024_mps" 18 | # PRETRAINED_GAN = "generator_adult_02012024_mps" 19 | # LABELS = ['income'] 20 | SAMPLES = 3000 21 | 22 | if __name__ == '__main__': 23 | parser = argparse.ArgumentParser(description='CLI') 24 | parser.add_argument('--train_type', type=str, default=TRAIN_TYPE, help='Type of training (cae_gan, gan)') 25 | parser.add_argument('--data_path', type=str, default=DATA_PATH, help='Path to the data file') 26 | parser.add_argument('--metadata_path', type=str, default=METADATA_PATH, help='Path to the metadata file') 27 | parser.add_argument('--device', type=str, default=DEVICE, help='Training device (cpu, mps or cuda)') 28 | parser.add_argument('--dataset_name', type=str, default=DATASET_NAME, 29 | help='A tag to identify the dataset (dataset name)') 30 | parser.add_argument('--pretrained_cae', type=str, default=PRETRAINED_CAE, help='CAE pretrained model name') 31 | parser.add_argument('--pretrained_generator', type=str, default=PRETRAINED_GEN, help='Generator pretrained model name') 32 | # parser.add_argument('--labels', type=ast.literal_eval, default=LABELS, help='A list of labels for classifier') 33 | parser.add_argument('--samples', type=int, default=SAMPLES, help='Number of samples to generate') 34 | args = parser.parse_args() 35 | TRAIN_TYPE = args.train_type 36 | DATA_PATH = args.data_path 37 | METADATA_PATH = args.metadata_path 38 | DEVICE = args.device 39 | DATASET_NAME = args.dataset_name 40 | PRETRAINED_CAE = args.pretrained_cae 41 | PRETRAINED_GEN = args.pretrained_generator 42 | # LABELS = args.labels 43 | SAMPLES = args.samples 44 | 45 | discrete_columns = get_discrete_columns(METADATA_PATH) 46 | real_data = read_csv(DATA_PATH) 47 | 48 | transformer = DataTransformer() 49 | transformer.fit(real_data, discrete_columns) 50 | data_dim = transformer.output_dimensions 51 | 52 | cae_model_path = get_model_path("cae", DATASET_NAME, PRETRAINED_CAE) 53 | gan_model_path = get_model_path(TRAIN_TYPE, DATASET_NAME, PRETRAINED_GEN) 54 | 55 | noise_generator = NoiseGenerator(model_path=cae_model_path, input_size=data_dim, device=DEVICE) 56 | 57 | ctgan = CTGAN(transformer=transformer, data_dim=data_dim, verbose=True, generator_model=gan_model_path, 58 | noise_generator=noise_generator, device=DEVICE, dataset=DATASET_NAME) 59 | ctgan.fit(real_data) 60 | synthetic_data = ctgan.sample(SAMPLES) 61 | save_csv(synthetic_data, DATASET_NAME, TRAIN_TYPE, SAMPLES) 62 | 63 | print(synthetic_data.head(20)) 64 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | """CLI.""" 2 | import argparse 3 | from data_handler.data_reader import read_csv, get_discrete_columns, get_device, get_model_path 4 | from data_handler.data_transformer import DataTransformer 5 | from trainers.gan_cae_train import CTGAN 6 | from trainers.cae_train import CAETrain 7 | from helpers.noise_generator_full import NoiseGenerator 8 | import ast 9 | 10 | DEFAULT_TRAIN_TYPE = "cae" 11 | DEFAULT_DATA_PATH = "dataset_test/HouseholdPowerConsumption/household_power_consumption_final.csv" 12 | DEFAULT_METADATA_PATH = "dataset_test/HouseholdPowerConsumption/meta_data.json" 13 | DEFAULT_DEVICE = get_device() 14 | DEFAULT_DATASET_NAME = "PowerConsumption" 15 | DEFAULT_PRETRAINED_CAE = "cae_adult_09262023_mps" 16 | DEFAULT_LABELS = ['month'] 17 | DEFAULT_EPOCHS = 50 18 | DEFAULT_DEBUG = False 19 | 20 | 21 | def main(epochs, train_type, data_path, metadata_path, device, dataset_name, pretrained_cae, labels, debug): 22 | """ 23 | 24 | This method trains a model based on the given parameters. 25 | 26 | Parameters: 27 | - epochs (int): The number of epochs to train the model. 28 | - train_type (str): The type of training to perform. Supported values are 'gan', and 'cae'. 29 | - data_path (str): The path to the data file. 30 | - metadata_path (str): The path to the metadata file. 31 | - device (str): The device on which to run the model (e.g., 'cpu', 'cuda'). 32 | - dataset_name (str): The name of the dataset. 33 | - pretrained_cae (bool): Indicates whether to use a pre-trained CAE model. 34 | - labels (list): A list of labels for the data. 35 | - debug (bool): Indicates whether to enable wandb debug mode. 36 | 37 | Returns: 38 | - None 39 | 40 | """ 41 | discrete_columns = get_discrete_columns(metadata_path) 42 | real_data = read_csv(data_path) 43 | transformer = DataTransformer() 44 | transformer.fit(real_data, discrete_columns) 45 | data_dim = transformer.output_dimensions 46 | if train_type == 'gan': 47 | cae_model_path = get_model_path("cae", dataset_name, pretrained_cae) 48 | noise_generator = NoiseGenerator(model_path=cae_model_path, input_size=data_dim, device=device) 49 | 50 | ctgan = CTGAN(transformer=transformer, data_dim=data_dim, epochs=epochs, verbose=True, 51 | noise_generator=noise_generator, device=device, dataset=dataset_name, is_wandb=debug) 52 | ctgan.fit(real_data, discrete_columns, labels) 53 | synthetic_data = ctgan.sample(20) 54 | print(synthetic_data) 55 | 56 | elif train_type == 'cae': 57 | cae = CAETrain(transformer=transformer, data_dim=data_dim, epochs=epochs, verbose=True, device=device, 58 | dataset=dataset_name, is_wandb=debug) 59 | cae.fit(real_data, discrete_columns) 60 | 61 | 62 | if __name__ == '__main__': 63 | parser = argparse.ArgumentParser(description='CLI') 64 | parser.add_argument('--epochs', type=int, default=DEFAULT_EPOCHS, help='Training epochs') 65 | parser.add_argument('--train_type', type=str, default=DEFAULT_TRAIN_TYPE, 66 | help='Type of training (cae, cae_gan, gan)') 67 | parser.add_argument('--data_path', type=str, default=DEFAULT_DATA_PATH, help='Path to the data file') 68 | parser.add_argument('--metadata_path', type=str, default=DEFAULT_METADATA_PATH, help='Path to the metadata file') 69 | parser.add_argument('--device', type=str, default=DEFAULT_DEVICE, help='Training device (cpu, mps or cuda)') 70 | parser.add_argument('--dataset_name', type=str, default=DEFAULT_DATASET_NAME, 71 | help='A tag to identify the dataset (dataset name)') 72 | parser.add_argument('--pretrained_cae', type=str, default=DEFAULT_PRETRAINED_CAE, help='CAE pretrained model name') 73 | parser.add_argument('--labels', type=ast.literal_eval, default=DEFAULT_LABELS, 74 | help='A list of labels for classifier') 75 | parser.add_argument('--debug', type=bool, default=DEFAULT_DEBUG, help='Use wandb for debugging purposes') 76 | args = parser.parse_args() 77 | 78 | main(args.epochs, args.train_type, args.data_path, args.metadata_path, args.device, args.dataset_name, 79 | args.pretrained_cae, args.labels, args.debug) 80 | -------------------------------------------------------------------------------- /commands_sampler.txt: -------------------------------------------------------------------------------- 1 | python sampler.py --train_type gan --data_path dataset_test/adult/adult.csv --metadata_path dataset_test/adult/meta_data.json --dataset_name adult --pretrained_cae cae_adult_adult_03012024_cuda --pretrained_generator generator_adult_03022024_cuda --samples 5000 2 | python sampler.py --train_type gan --data_path dataset_test/AirQuality/AirQuality_final.csv --metadata_path dataset_test/AirQuality/meta_data.json --dataset_name AirQuality --pretrained_cae cae_AirQuality_AirQuality_03012024_cuda --pretrained_generator generator_AirQuality_03022024_cuda --samples 5000 3 | python sampler.py --train_type gan --data_path dataset_test/ApartmentRent/apartments_for_rent_final.csv --metadata_path dataset_test/ApartmentRent/meta_data.json --dataset_name ApartmentRent --pretrained_cae cae_ApartmentRent_ApartmentRent_03012024_cuda --pretrained_generator generator_ApartmentRent_03032024_cuda --samples 5000 4 | python sampler.py --train_type gan --data_path dataset_test/BankMarketing/bank-final.csv --metadata_path dataset_test/BankMarketing/meta_data.json --dataset_name BankMarketing --pretrained_cae cae_BankMarketing_BankMarketing_03012024_cuda --pretrained_generator generator_BankMarketing_03022024_cuda --samples 5000 5 | python sampler.py --train_type gan --data_path dataset_test/BeijingPM/PRSA_data_final.csv --metadata_path dataset_test/BeijingPM/meta_data.json --dataset_name BeijingPM --pretrained_cae cae_BeijingPM_BeijingPM_03012024_cuda --pretrained_generator generator_BeijingPM_03022024_cuda --samples 5000 6 | python sampler.py --train_type gan --data_path dataset_test/BikeSharing/final.csv --metadata_path dataset_test/BikeSharing/meta_data.json --dataset_name BikeSharing --pretrained_cae cae_BikeSharing_BikeSharing_03012024_cuda --pretrained_generator generator_BikeSharing_03022024_cuda --samples 5000 7 | python sampler.py --train_type gan --data_path dataset_test/MetroPTDataset/MetroPT3_final.csv --metadata_path dataset_test/MetroPTDataset/meta_data.json --dataset_name MetroPT --pretrained_cae cae_MetroPT_MetroPT_03022024_cuda --pretrained_generator generator_MetroPT_03052024_cuda --samples 5000 8 | python sampler.py --train_type gan --data_path dataset_test/MetroInterstateTraffic/Metro_Interstate_Traffic_Volume_Final.csv --metadata_path dataset_test/MetroInterstateTraffic/meta_data.json --dataset_name MetroTraffic --pretrained_cae cae_MetroTraffic_MetroTraffic_03012024_cuda --pretrained_generator generator_MetroTraffic_03022024_cuda --samples 5000 9 | python sampler.py --train_type gan --data_path dataset_test/HouseholdPowerConsumption/household_power_consumption_final.csv --metadata_path dataset_test/HouseholdPowerConsumption/meta_data.json --dataset_name PowerConsumption --pretrained_cae cae_PowerConsumption_PowerConsumption_03042024_cuda --pretrained_generator generator_PowerConsumption_03052024_cuda --samples 5000 10 | python sampler.py --train_type cae_gan --data_path dataset_test/adult/adult.csv --metadata_path dataset_test/adult/meta_data.json --dataset_name adult --pretrained_cae cae_adult_adult_03012024_cuda --pretrained_generator generator_adult_03042024_cuda --samples 5000 11 | python sampler.py --train_type cae_gan --data_path dataset_test/AirQuality/AirQuality_final.csv --metadata_path dataset_test/AirQuality/meta_data.json --dataset_name AirQuality --pretrained_cae cae_AirQuality_AirQuality_03012024_cuda --pretrained_generator generator_AirQuality_03032024_cuda --samples 5000 12 | python sampler.py --train_type cae_gan --data_path dataset_test/ApartmentRent/apartments_for_rent_final.csv --metadata_path dataset_test/ApartmentRent/meta_data.json --dataset_name ApartmentRent --pretrained_cae cae_ApartmentRent_ApartmentRent_03012024_cuda --pretrained_generator generator_ApartmentRent_03042024_cuda --samples 5000 13 | python sampler.py --train_type cae_gan --data_path dataset_test/BankMarketing/bank-final.csv --metadata_path dataset_test/BankMarketing/meta_data.json --dataset_name BankMarketing --pretrained_cae cae_BankMarketing_BankMarketing_03012024_cuda --pretrained_generator generator_BankMarketing_03042024_cuda --samples 5000 14 | python sampler.py --train_type cae_gan --data_path dataset_test/BeijingPM/PRSA_data_final.csv --metadata_path dataset_test/BeijingPM/meta_data.json --dataset_name BeijingPM --pretrained_cae cae_BeijingPM_BeijingPM_03012024_cuda --pretrained_generator generator_BeijingPM_03042024_cuda --samples 5000 15 | python sampler.py --train_type cae_gan --data_path dataset_test/BikeSharing/final.csv --metadata_path dataset_test/BikeSharing/meta_data.json --dataset_name BikeSharing --pretrained_cae cae_BikeSharing_BikeSharing_03012024_cuda --pretrained_generator generator_BikeSharing_03042024_cuda --samples 5000 16 | python sampler.py --train_type cae_gan --data_path dataset_test/MetroPTDataset/MetroPT3_final.csv --metadata_path dataset_test/MetroPTDataset/meta_data.json --dataset_name MetroPT --pretrained_cae cae_MetroPT_MetroPT_03022024_cuda --pretrained_generator generator_MetroPT_03062024_cuda --samples 5000 17 | python sampler.py --train_type cae_gan --data_path dataset_test/MetroInterstateTraffic/Metro_Interstate_Traffic_Volume_Final.csv --metadata_path dataset_test/MetroInterstateTraffic/meta_data.json --dataset_name MetroTraffic --pretrained_cae cae_MetroTraffic_MetroTraffic_03012024_cuda --pretrained_generator generator_MetroTraffic_03042024_cuda --samples 5000 18 | python sampler.py --train_type cae_gan --data_path dataset_test/HouseholdPowerConsumption/household_power_consumption_final.csv --metadata_path dataset_test/HouseholdPowerConsumption/meta_data.json --dataset_name PowerConsumption --pretrained_cae cae_PowerConsumption_PowerConsumption_03042024_cuda --pretrained_generator generator_PowerConsumption_03062024_cuda --samples 5000 -------------------------------------------------------------------------------- /helpers/base_model.py: -------------------------------------------------------------------------------- 1 | import contextlib 2 | import torch.nn as nn 3 | import numpy as np 4 | import torch 5 | 6 | 7 | @contextlib.contextmanager 8 | def set_random_states(random_state, set_model_random_state): 9 | """Context manager for managing the random state. 10 | 11 | Args: 12 | random_state (int or tuple): 13 | The random seed or a tuple of (numpy.random.RandomState, torch.Generator). 14 | set_model_random_state (function): 15 | Function to set the random state on the model. 16 | """ 17 | original_np_state = np.random.get_state() 18 | original_torch_state = torch.get_rng_state() 19 | 20 | random_np_state, random_torch_state = random_state 21 | 22 | np.random.set_state(random_np_state.get_state()) 23 | torch.set_rng_state(random_torch_state.get_state()) 24 | 25 | try: 26 | yield 27 | finally: 28 | current_np_state = np.random.RandomState() 29 | current_np_state.set_state(np.random.get_state()) 30 | current_torch_state = torch.Generator() 31 | current_torch_state.set_state(torch.get_rng_state()) 32 | set_model_random_state((current_np_state, current_torch_state)) 33 | 34 | np.random.set_state(original_np_state) 35 | torch.set_rng_state(original_torch_state) 36 | 37 | 38 | def random_state(function): 39 | """Set the random state before calling the function. 40 | 41 | Args: 42 | function (Callable): 43 | The function to wrap around. 44 | """ 45 | 46 | def wrapper(self, *args, **kwargs): 47 | if self.random_states is None: 48 | return function(self, *args, **kwargs) 49 | 50 | else: 51 | with set_random_states(self.random_states, self.set_random_state): 52 | return function(self, *args, **kwargs) 53 | 54 | return wrapper 55 | 56 | 57 | class BaseModel(nn.Module): 58 | """Base class for all default synthesizers of ``CTGAN``.""" 59 | 60 | random_states = None 61 | 62 | def __getstate__(self): 63 | """Improve pickling state for ``BaseSynthesizer``. 64 | 65 | Convert to ``cpu`` device before starting the pickling process in order to be able to 66 | load the model even when used from an external tool such as ``SDV``. Also, if 67 | ``random_states`` are set, store their states as dictionaries rather than generators. 68 | 69 | Returns: 70 | dict: 71 | Python dict representing the object. 72 | """ 73 | device_backup = self._device 74 | self.set_device(torch.device('cpu')) 75 | state = self.__dict__.copy() 76 | self.set_device(device_backup) 77 | if ( 78 | isinstance(self.random_states, tuple) and 79 | isinstance(self.random_states[0], np.random.RandomState) and 80 | isinstance(self.random_states[1], torch.Generator) 81 | ): 82 | state['_numpy_random_state'] = self.random_states[0].get_state() 83 | state['_torch_random_state'] = self.random_states[1].get_state() 84 | state.pop('random_states') 85 | 86 | return state 87 | 88 | def __setstate__(self, state): 89 | """Restore the state of a ``BaseSynthesizer``. 90 | 91 | Restore the ``random_states`` from the state dict if those are present and then 92 | set the device according to the current hardware. 93 | """ 94 | if '_numpy_random_state' in state and '_torch_random_state' in state: 95 | np_state = state.pop('_numpy_random_state') 96 | torch_state = state.pop('_torch_random_state') 97 | 98 | current_torch_state = torch.Generator() 99 | current_torch_state.set_state(torch_state) 100 | 101 | current_numpy_state = np.random.RandomState() 102 | current_numpy_state.set_state(np_state) 103 | state['random_states'] = ( 104 | current_numpy_state, 105 | current_torch_state 106 | ) 107 | 108 | self.__dict__ = state 109 | # device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') 110 | if torch.backends.mps.is_available(): 111 | device = torch.device("mps") 112 | else: 113 | device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') 114 | self.set_device(device) 115 | 116 | def save(self, path): 117 | """Save the model in the passed `path`.""" 118 | device_backup = self._device 119 | self.set_device(torch.device('cpu')) 120 | torch.save(self, path) 121 | self.set_device(device_backup) 122 | 123 | @classmethod 124 | def load(cls, path): 125 | """Load the model stored in the passed `path`.""" 126 | # device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') 127 | if torch.backends.mps.is_available(): 128 | device = torch.device("mps") 129 | else: 130 | device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') 131 | model = torch.load(path, map_location=torch.device(device)) 132 | # model.set_device(device) 133 | return model 134 | 135 | def set_random_state(self, random_state): 136 | """Set the random state. 137 | 138 | Args: 139 | random_state (int, tuple, or None): 140 | Either a tuple containing the (numpy.random.RandomState, torch.Generator) 141 | or an int representing the random seed to use for both random states. 142 | """ 143 | if random_state is None: 144 | self.random_states = random_state 145 | elif isinstance(random_state, int): 146 | self.random_states = ( 147 | np.random.RandomState(seed=random_state), 148 | torch.Generator().manual_seed(random_state), 149 | ) 150 | elif ( 151 | isinstance(random_state, tuple) and 152 | isinstance(random_state[0], np.random.RandomState) and 153 | isinstance(random_state[1], torch.Generator) 154 | ): 155 | self.random_states = random_state 156 | else: 157 | raise TypeError( 158 | f'`random_state` {random_state} expected to be an int or a tuple of ' 159 | '(`np.random.RandomState`, `torch.Generator`)') 160 | -------------------------------------------------------------------------------- /data_handler/data_sampler.py: -------------------------------------------------------------------------------- 1 | """DataSampler module.""" 2 | 3 | import numpy as np 4 | 5 | 6 | class DataSampler(object): 7 | """DataSampler samples the conditional vector and corresponding data for CTGAN.""" 8 | 9 | def __init__(self, data, output_info, log_frequency): 10 | self._data = data 11 | 12 | def is_discrete_column(column_info): 13 | return (len(column_info) == 1 14 | and column_info[0].activation_fn == 'softmax') 15 | 16 | n_discrete_columns = sum( 17 | [1 for column_info in output_info if is_discrete_column(column_info)]) 18 | 19 | self._discrete_column_matrix_st = np.zeros( 20 | n_discrete_columns, dtype='int32') 21 | 22 | # Store the row id for each category in each discrete column. 23 | # For example _rid_by_cat_cols[a][b] is a list of all rows with the 24 | # a-th discrete column equal value b. 25 | self._rid_by_cat_cols = [] 26 | 27 | # Compute _rid_by_cat_cols 28 | st = 0 29 | for column_info in output_info: 30 | if is_discrete_column(column_info): 31 | span_info = column_info[0] 32 | ed = st + span_info.dim 33 | 34 | rid_by_cat = [] 35 | for j in range(span_info.dim): 36 | rid_by_cat.append(np.nonzero(data[:, st + j])[0]) 37 | self._rid_by_cat_cols.append(rid_by_cat) 38 | st = ed 39 | else: 40 | st += sum([span_info.dim for span_info in column_info]) 41 | assert st == data.shape[1] 42 | 43 | # Prepare an interval matrix for efficiently sample conditional vector 44 | max_category = max([ 45 | column_info[0].dim 46 | for column_info in output_info 47 | if is_discrete_column(column_info) 48 | ], default=0) 49 | 50 | self._discrete_column_cond_st = np.zeros(n_discrete_columns, dtype='int32') 51 | self._discrete_column_n_category = np.zeros(n_discrete_columns, dtype='int32') 52 | self._discrete_column_category_prob = np.zeros((n_discrete_columns, max_category)) 53 | self._n_discrete_columns = n_discrete_columns 54 | self._n_categories = sum([ 55 | column_info[0].dim 56 | for column_info in output_info 57 | if is_discrete_column(column_info) 58 | ]) 59 | 60 | st = 0 61 | current_id = 0 62 | current_cond_st = 0 63 | for column_info in output_info: 64 | if is_discrete_column(column_info): 65 | span_info = column_info[0] 66 | ed = st + span_info.dim 67 | category_freq = np.sum(data[:, st:ed], axis=0) 68 | if log_frequency: 69 | category_freq = np.log(category_freq + 1) 70 | category_prob = category_freq / np.sum(category_freq) 71 | self._discrete_column_category_prob[current_id, :span_info.dim] = category_prob 72 | self._discrete_column_cond_st[current_id] = current_cond_st 73 | self._discrete_column_n_category[current_id] = span_info.dim 74 | current_cond_st += span_info.dim 75 | current_id += 1 76 | st = ed 77 | else: 78 | st += sum([span_info.dim for span_info in column_info]) 79 | 80 | def _random_choice_prob_index(self, discrete_column_id): 81 | probs = self._discrete_column_category_prob[discrete_column_id] 82 | r = np.expand_dims(np.random.rand(probs.shape[0]), axis=1) 83 | return (probs.cumsum(axis=1) > r).argmax(axis=1) 84 | 85 | def sample_condvec(self, batch): 86 | """Generate the conditional vector for training. 87 | 88 | Returns: 89 | cond (batch x #categories): 90 | The conditional vector. 91 | mask (batch x #discrete columns): 92 | A one-hot vector indicating the selected discrete column. 93 | discrete column id (batch): 94 | Integer representation of mask. 95 | category_id_in_col (batch): 96 | Selected category in the selected discrete column. 97 | """ 98 | if self._n_discrete_columns == 0: 99 | return None 100 | 101 | discrete_column_id = np.random.choice( 102 | np.arange(self._n_discrete_columns), batch) 103 | 104 | cond = np.zeros((batch, self._n_categories), dtype='float32') 105 | mask = np.zeros((batch, self._n_discrete_columns), dtype='float32') 106 | mask[np.arange(batch), discrete_column_id] = 1 107 | category_id_in_col = self._random_choice_prob_index(discrete_column_id) 108 | category_id = (self._discrete_column_cond_st[discrete_column_id] + category_id_in_col) 109 | cond[np.arange(batch), category_id] = 1 110 | 111 | return cond, mask, discrete_column_id, category_id_in_col 112 | 113 | def sample_original_condvec(self, batch): 114 | """Generate the conditional vector for generation use original frequency.""" 115 | if self._n_discrete_columns == 0: 116 | return None 117 | 118 | cond = np.zeros((batch, self._n_categories), dtype='float32') 119 | 120 | for i in range(batch): 121 | row_idx = np.random.randint(0, len(self._data)) 122 | col_idx = np.random.randint(0, self._n_discrete_columns) 123 | matrix_st = self._discrete_column_matrix_st[col_idx] 124 | matrix_ed = matrix_st + self._discrete_column_n_category[col_idx] 125 | pick = np.argmax(self._data[row_idx, matrix_st:matrix_ed]) 126 | cond[i, pick + self._discrete_column_cond_st[col_idx]] = 1 127 | 128 | return cond 129 | 130 | def sample_data(self, n, col, opt): 131 | """Sample data from original training data satisfying the sampled conditional vector. 132 | 133 | Returns: 134 | n rows of matrix data. 135 | """ 136 | if col is None: 137 | idx = np.random.randint(len(self._data), size=n) 138 | return self._data[idx] 139 | 140 | idx = [] 141 | for c, o in zip(col, opt): 142 | idx.append(np.random.choice(self._rid_by_cat_cols[c][o])) 143 | 144 | return self._data[idx] 145 | 146 | def dim_cond_vec(self): 147 | """Return the total number of categories.""" 148 | return self._n_categories 149 | 150 | def generate_cond_from_condition_column_info(self, condition_info, batch): 151 | """Generate the condition vector.""" 152 | vec = np.zeros((batch, self._n_categories), dtype='float32') 153 | id_ = self._discrete_column_matrix_st[condition_info['discrete_column_id']] 154 | id_ += condition_info['value_id'] 155 | vec[:, id_] = 1 156 | return vec 157 | -------------------------------------------------------------------------------- /reconstructor/cae_reconstructor.py: -------------------------------------------------------------------------------- 1 | from helpers.base_model import BaseModel, random_state 2 | from data_handler.data_transformer import DataTransformer 3 | from data_handler.data_sampler import DataSampler 4 | from models.cae_model import CAE 5 | import torch 6 | import pandas as pd 7 | import numpy as np 8 | 9 | 10 | class CAEReconstructor(BaseModel): 11 | """Contractive Autoencoder 12 | """ 13 | 14 | def __init__(self, model_path, hidden_size=256, latent_size=64, 15 | optim_decay=1e-6, log_frequency=True, verbose=False, device='cpu'): 16 | 17 | self._hidden_size = hidden_size 18 | self._latent_size = latent_size 19 | 20 | self._optim_decay = optim_decay 21 | 22 | self._log_frequency = log_frequency 23 | self._verbose = verbose 24 | 25 | if self._verbose: 26 | print("Device: ", device) 27 | 28 | self._device = torch.device(device) 29 | self._model_path = model_path 30 | 31 | self._transformer = None 32 | self._data_sampler = None 33 | 34 | self._loaded_model = None 35 | 36 | def _validate_discrete_columns(self, train_data, discrete_columns): 37 | """Check whether ``discrete_columns`` exists in ``train_data``. 38 | 39 | Args: 40 | train_data (numpy.ndarray or pandas.DataFrame): 41 | Training Data. It must be a 2-dimensional numpy array or a pandas.DataFrame. 42 | discrete_columns (list-like): 43 | List of discrete columns to be used to generate the Conditional 44 | Vector. If ``train_data`` is a Numpy array, this list should 45 | contain the integer indices of the columns. Otherwise, if it is 46 | a ``pandas.DataFrame``, this list should contain the column names. 47 | """ 48 | if isinstance(train_data, pd.DataFrame): 49 | invalid_columns = set(discrete_columns) - set(train_data.columns) 50 | elif isinstance(train_data, np.ndarray): 51 | invalid_columns = [] 52 | for column in discrete_columns: 53 | if column < 0 or column >= train_data.shape[1]: 54 | invalid_columns.append(column) 55 | else: 56 | raise TypeError('``train_data`` should be either pd.DataFrame or np.array.') 57 | 58 | if invalid_columns: 59 | raise ValueError(f'Invalid columns found: {invalid_columns}') 60 | 61 | @random_state 62 | def fit(self, train_data, input_data, discrete_columns=()): 63 | """Fit the CTGAN Synthesizer models to the training data. 64 | 65 | Args: 66 | train_data (numpy.ndarray or pandas.DataFrame): 67 | Training Data. It must be a 2-dimensional numpy array or a pandas.DataFrame. 68 | discrete_columns (list-like): 69 | List of discrete columns to be used to generate the Conditional 70 | Vector. If ``train_data`` is a Numpy array, this list should 71 | contain the integer indices of the columns. Otherwise, if it is 72 | a ``pandas.DataFrame``, this list should contain the column names. 73 | """ 74 | self._validate_discrete_columns(train_data, discrete_columns) 75 | 76 | self._transformer = DataTransformer() 77 | self._transformer.fit(train_data, discrete_columns) 78 | 79 | train_data = self._transformer.transform(train_data) 80 | 81 | 82 | self._data_sampler = DataSampler( 83 | train_data, 84 | self._transformer.output_info_list, 85 | self._log_frequency) 86 | 87 | data_dim = self._transformer.output_dimensions 88 | print("data_dim", data_dim) 89 | 90 | self._loaded_model = CAE(data_dim, self._hidden_size, self._latent_size).to(self._device) 91 | 92 | self._loaded_model.load_state_dict(torch.load(self._model_path)) 93 | print(self._loaded_model) 94 | 95 | self._loaded_model.eval() 96 | 97 | # Reconstruct and store all data 98 | reconstructed_data_list = [] 99 | 100 | with torch.no_grad(): 101 | # for id_ in range(len(train_data)): 102 | 103 | condvec = self._data_sampler.sample_condvec(len(input_data)) 104 | 105 | if condvec is None: 106 | c1, m1, col, opt = None, None, None, None 107 | real = self._data_sampler.sample_data(len(input_data), col, opt) 108 | else: 109 | c1, m1, col, opt = condvec 110 | 111 | perm = np.arange(len(input_data)) 112 | np.random.shuffle(perm) 113 | real = self._data_sampler.sample_data( 114 | len(input_data), col[perm], opt[perm]) 115 | 116 | inputs = torch.from_numpy(real.astype('float32')).to(self._device) 117 | print("inputs", self._transformer.inverse_transform(inputs)) 118 | 119 | # Forward pass 120 | latent, outputs = self._loaded_model(inputs) 121 | 122 | # # Concatenate the reconstructed data 123 | # reconstructed_data = torch.cat(reconstructed_data_list, dim=0) 124 | # 125 | # # Save the reconstructed data 126 | # torch.save(reconstructed_data, 'reconstructed_data.pth') 127 | print("outputs", outputs.shape) 128 | print("outputs", self._transformer.inverse_transform(outputs)) 129 | 130 | return outputs 131 | 132 | @random_state 133 | def sample(self, n): 134 | """Sample data similar to the training data. 135 | 136 | Choosing a condition_column and condition_value will increase the probability of the 137 | discrete condition_value happening in the condition_column. 138 | 139 | Args: 140 | n (int): 141 | Number of rows to sample. 142 | condition_column (string): 143 | Name of a discrete column. 144 | condition_value (string): 145 | Name of the category in the condition_column which we wish to increase the 146 | probability of happening. 147 | 148 | Returns: 149 | numpy.ndarray or pandas.DataFrame 150 | """ 151 | global_condition_vec = None 152 | 153 | steps = n // self._batch_size + 1 154 | data = [] 155 | for i in range(steps): 156 | mean = torch.zeros(self._batch_size, self._embedding_dim) 157 | std = mean + 1 158 | fakez = torch.normal(mean=mean, std=std).to(self._device) 159 | 160 | condvec = self._data_sampler.sample_original_condvec(self._batch_size) 161 | 162 | if condvec is None: 163 | pass 164 | else: 165 | c1 = condvec 166 | c1 = torch.from_numpy(c1).to(self._device) 167 | fakez = torch.cat([fakez, c1], dim=1) 168 | 169 | fake = self._generator(fakez) 170 | fakeact = self._apply_activate(fake) 171 | data.append(fakeact.detach().cpu().numpy()) 172 | 173 | data = np.concatenate(data, axis=0) 174 | data = data[:n] 175 | 176 | return self._transformer.inverse_transform(data) 177 | -------------------------------------------------------------------------------- /commands.txt: -------------------------------------------------------------------------------- 1 | python main.py --epochs 500 --train_type cae --data_path dataset_test/adult/adult.csv --metadata_path dataset_test/adult/meta_data.json --dataset_name adult --debug True --labels "['income']" > output_adult.log 2 | python main.py --epochs 600 --train_type cae --data_path dataset_test/AirQuality/AirQuality_final.csv --metadata_path dataset_test/AirQuality/meta_data.json --debug True --dataset_name AirQuality --labels "['month', 'day']" > output_AirQuality.log 3 | python main.py --epochs 600 --train_type cae --data_path dataset_test/ApartmentRent/apartments_for_rent_final.csv --metadata_path dataset_test/ApartmentRent/meta_data.json --debug True --dataset_name ApartmentRent --labels "['cityname','state']" > output_ApartmentRent.log 4 | python main.py --epochs 600 --train_type cae --data_path dataset_test/BankMarketing/bank-final.csv --metadata_path dataset_test/BankMarketing/meta_data.json --debug True --dataset_name BankMarketing --labels "['y']" > output_BankMarketing.log 5 | python main.py --epochs 700 --train_type cae --data_path dataset_test/BeijingPM/PRSA_data_final.csv --metadata_path dataset_test/BeijingPM/meta_data.json --debug True --dataset_name BeijingPM --labels "['year','month','day','hour']" > output_BeijingPM.log 6 | python main.py --epochs 700 --train_type cae --data_path dataset_test/BikeSharing/final.csv --metadata_path dataset_test/BikeSharing/meta_data.json --debug True --dataset_name BikeSharing --labels "['mnth','hr']" > output_BikeSharing.log 7 | python main.py --epochs 700 --train_type cae --data_path dataset_test/HAR70/final.csv --metadata_path dataset_test/HAR70/meta_data.json --debug True --dataset_name HAR70 --labels "['label']" > output_HAR70.log 8 | python main.py --epochs 700 --train_type cae --data_path dataset_test/HouseholdPowerConsumption/household_power_consumption_final.csv --metadata_path dataset_test/HouseholdPowerConsumption/meta_data.json --debug True --dataset_name PowerConsumption --labels "['month','day']" > output_PowerConsumption.log 9 | python main.py --epochs 600 --train_type cae --data_path dataset_test/MetroInterstateTraffic/Metro_Interstate_Traffic_Volume_Final.csv --metadata_path dataset_test/MetroInterstateTraffic/meta_data.json --debug True --dataset_name MetroTraffic --labels "['month','day']" > output_MetroTraffic.log 10 | python main.py --epochs 600 --train_type cae --data_path dataset_test/MetroPTDataset/MetroPT3_final.csv --metadata_path dataset_test/MetroPTDataset/meta_data.json --debug True --dataset_name MetroPT --labels "['month','day']" > output_MetroPT.log 11 | python main.py --epochs 600 --train_type cae --data_path dataset_test/WeatherDataset/weatherHistory_final.csv --metadata_path dataset_test/WeatherDataset/meta_data.json --debug True --dataset_name Weather --labels "['month','day']" > output_Weather.log 12 | python main.py --epochs 300 --train_type gan --data_path dataset_test/adult/adult.csv --metadata_path dataset_test/adult/meta_data.json --debug True --dataset_name adult --labels "['income']" > output_adult_GAN.log 13 | python main.py --epochs 300 --train_type gan --data_path dataset_test/AirQuality/AirQuality_final.csv --metadata_path dataset_test/AirQuality/meta_data.json --debug True --dataset_name AirQuality --labels "['month']" > output_AirQuality_GAN.log 14 | python main.py --epochs 300 --train_type gan --data_path dataset_test/ApartmentRent/apartments_for_rent_final.csv --metadata_path dataset_test/ApartmentRent/meta_data.json --debug True --dataset_name ApartmentRent --labels "['cityname']" > output_ApartmentRent_GAN.log 15 | python main.py --epochs 300 --train_type gan --data_path dataset_test/BeijingPM/PRSA_data_final.csv --metadata_path dataset_test/BeijingPM/meta_data.json --debug True --dataset_name BeijingPM --labels "['month']" > output_BeijingPM_GAN.log 16 | python main.py --epochs 300 --train_type gan --data_path dataset_test/BikeSharing/final.csv --metadata_path dataset_test/BikeSharing/meta_data.json --debug True --dataset_name BikeSharing --labels "['mnth']" > output_BikeSharing_GAN.log 17 | python main.py --epochs 300 --train_type gan --data_path dataset_test/MetroInterstateTraffic/Metro_Interstate_Traffic_Volume_Final.csv --metadata_path dataset_test/MetroInterstateTraffic/meta_data.json --debug True --dataset_name MetroTraffic --labels "['month']" > output_MetroTraffic_GAN.log 18 | python main.py --epochs 300 --train_type gan --data_path dataset_test/MetroPTDataset/MetroPT3_final.csv --metadata_path dataset_test/MetroPTDataset/meta_data.json --debug True --dataset_name MetroPT --labels "['month']" > output_MetroPT_GAN.log 19 | python main.py --epochs 300 --train_type gan --data_path dataset_test/BankMarketing/bank-final.csv --metadata_path dataset_test/BankMarketing/meta_data.json --debug True --dataset_name BankMarketing --labels "['y']" > output_BankMarketing_GAN.log 20 | python main.py --epochs 300 --train_type gan --data_path dataset_test/WeatherDataset/weatherHistory_final.csv --metadata_path dataset_test/WeatherDataset/meta_data.json --debug True --dataset_name Weather --labels "['month']" > output_Weather_GAN.log 21 | python main.py --epochs 300 --train_type gan --data_path dataset_test/HouseholdPowerConsumption/household_power_consumption_final.csv --metadata_path dataset_test/HouseholdPowerConsumption/meta_data.json --debug True --dataset_name PowerConsumption --labels "['month']" > output_PowerConsumption_GAN.log 22 | python main.py --epochs 300 --train_type gan --data_path dataset_test/HAR70/final.csv --metadata_path dataset_test/HAR70/meta_data.json --debug True --dataset_name HAR70 --labels "['label']" > output_HAR70_GAN.log 23 | python main.py --pretrained_cae cae_adult_adult_03012024_cuda --epochs 300 --train_type cae_gan --data_path dataset_test/adult/adult.csv --metadata_path dataset_test/adult/meta_data.json --debug True --dataset_name adult --labels "['income']" > output_adult_GAN.log 24 | python main.py --pretrained_cae cae_AirQuality_AirQuality_03012024_cuda --epochs 300 --train_type cae_gan --data_path dataset_test/AirQuality/AirQuality_final.csv --metadata_path dataset_test/AirQuality/meta_data.json --debug True --dataset_name AirQuality --labels "['month']" > output_AirQuality_GAN.log 25 | python main.py --pretrained_cae cae_ApartmentRent_ApartmentRent_03012024_cuda --epochs 300 --train_type cae_gan --data_path dataset_test/ApartmentRent/apartments_for_rent_final.csv --metadata_path dataset_test/ApartmentRent/meta_data.json --debug True --dataset_name ApartmentRent --labels "['cityname']" > output_ApartmentRent_GAN.log 26 | python main.py --pretrained_cae cae_BeijingPM_BeijingPM_03012024_cuda --epochs 300 --train_type cae_gan --data_path dataset_test/BeijingPM/PRSA_data_final.csv --metadata_path dataset_test/BeijingPM/meta_data.json --debug True --dataset_name BeijingPM --labels "['month']" > output_BeijingPM_GAN.log 27 | python main.py --pretrained_cae cae_BikeSharing_BikeSharing_03012024_cuda --epochs 300 --train_type cae_gan --data_path dataset_test/BikeSharing/final.csv --metadata_path dataset_test/BikeSharing/meta_data.json --debug True --dataset_name BikeSharing --labels "['mnth']" > output_BikeSharing_GAN.log 28 | python main.py --pretrained_cae cae_MetroTraffic_MetroTraffic_03012024_cuda --epochs 300 --train_type cae_gan --data_path dataset_test/MetroInterstateTraffic/Metro_Interstate_Traffic_Volume_Final.csv --metadata_path dataset_test/MetroInterstateTraffic/meta_data.json --debug True --dataset_name MetroTraffic --labels "['month']" > output_MetroTraffic_GAN.log 29 | python main.py --pretrained_cae cae_MetroPT_MetroPT_03022024_cuda --epochs 300 --train_type cae_gan --data_path dataset_test/MetroPTDataset/MetroPT3_final.csv --metadata_path dataset_test/MetroPTDataset/meta_data.json --debug True --dataset_name MetroPT --labels "['month']" > output_MetroPT_GAN.log 30 | python main.py --pretrained_cae cae_BankMarketing_BankMarketing_03012024_cuda --epochs 300 --train_type cae_gan --data_path dataset_test/BankMarketing/bank-final.csv --metadata_path dataset_test/BankMarketing/meta_data.json --debug True --dataset_name BankMarketing --labels "['y']" > output_BankMarketing_GAN.log 31 | python main.py --pretrained_cae cae_PowerConsumption_PowerConsumption_03042024_cuda --epochs 200 --train_type cae_gan --data_path dataset_test/HouseholdPowerConsumption/household_power_consumption_final.csv --metadata_path dataset_test/HouseholdPowerConsumption/meta_data.json --debug True --dataset_name PowerConsumption --labels "['month']" > output_PowerConsumption_GAN.log 32 | -------------------------------------------------------------------------------- /trainers/gan_sampler.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | import os 3 | from helpers.base_model import BaseModel, random_state 4 | from data_handler import embedding_dim 5 | from data_handler.data_sampler import DataSampler 6 | from data_handler.classifier_transformer import ClassifierDataTransformer 7 | from models.gan_model import Generator, Discriminator 8 | from models.classifier_model import ClassifierModel 9 | import torch 10 | import torch.nn as nn 11 | import torch.nn.functional as F 12 | import pandas as pd 13 | import numpy as np 14 | import warnings 15 | from torch import optim 16 | 17 | 18 | class CTGAN(BaseModel): 19 | def __init__(self, transformer, data_dim, generator_model = None, noise_generator=None, 20 | generator_dim=(256, 256), 21 | batch_size=500,log_frequency=True, 22 | verbose=False, device='cpu', 23 | dataset=None): 24 | super(CTGAN, self).__init__() 25 | 26 | assert batch_size % 2 == 0 27 | self._embedding_dim = None 28 | self._data_dim = data_dim 29 | self._generator_dim = generator_dim 30 | self._log_frequency = log_frequency 31 | 32 | 33 | self._batch_size = batch_size 34 | self._verbose = verbose 35 | 36 | if self._verbose: 37 | print("Device: ", device) 38 | 39 | self._device = torch.device(device) 40 | 41 | self.dataset = dataset 42 | self._transformer = transformer 43 | self._data_sampler = None 44 | self._generator = None 45 | self._noise_generator = noise_generator 46 | self._generator_model = generator_model 47 | 48 | @staticmethod 49 | def _gumbel_softmax(logits, tau=1, hard=False, eps=1e-10, dim=-1): 50 | """Deals with the instability of the gumbel_softmax for older versions of torch. 51 | 52 | For more details about the issue: 53 | https://drive.google.com/file/d/1AA5wPfZ1kquaRtVruCd6BiYZGcDeNxyP/view?usp=sharing 54 | 55 | Args: 56 | logits […, num_features]: 57 | Unnormalized log probabilities 58 | tau: 59 | Non-negative scalar temperature 60 | hard (bool): 61 | If True, the returned samples will be discretized as one-hot vectors, 62 | but will be differentiated as if it is the soft sample in autograd 63 | dim (int): 64 | A dimension along which softmax will be computed. Default: -1. 65 | 66 | Returns: 67 | Sampled tensor of same shape as logits from the Gumbel-Softmax distribution. 68 | """ 69 | for _ in range(10): 70 | transformed = nn.functional.gumbel_softmax(logits, tau=tau, hard=hard, eps=eps, dim=dim) 71 | if not torch.isnan(transformed).any(): 72 | return transformed 73 | 74 | raise ValueError('gumbel_softmax returning NaN.') 75 | 76 | def _apply_activate(self, data): 77 | """Apply proper activation function to the output of the generator.""" 78 | data_t = [] 79 | st = 0 80 | for column_info in self._transformer.output_info_list: 81 | for span_info in column_info: 82 | if span_info.activation_fn == 'tanh': 83 | ed = st + span_info.dim 84 | data_t.append(torch.tanh(data[:, st:ed])) 85 | st = ed 86 | elif span_info.activation_fn == 'softmax': 87 | ed = st + span_info.dim 88 | transformed = self._gumbel_softmax(data[:, st:ed], tau=0.2) 89 | data_t.append(transformed) 90 | st = ed 91 | else: 92 | raise ValueError(f'Unexpected activation function {span_info.activation_fn}.') 93 | 94 | return torch.cat(data_t, dim=1) 95 | 96 | def _cond_loss(self, data, c, m): 97 | """Compute the cross entropy loss on the fixed discrete column.""" 98 | loss = [] 99 | st = 0 100 | st_c = 0 101 | for column_info in self._transformer.output_info_list: 102 | for span_info in column_info: 103 | if len(column_info) != 1 or span_info.activation_fn != 'softmax': 104 | # not discrete column 105 | st += span_info.dim 106 | else: 107 | ed = st + span_info.dim 108 | ed_c = st_c + span_info.dim 109 | tmp = nn.functional.cross_entropy( 110 | data[:, st:ed], 111 | torch.argmax(c[:, st_c:ed_c], dim=1), 112 | reduction='none' 113 | ) 114 | loss.append(tmp) 115 | st = ed 116 | st_c = ed_c 117 | 118 | loss = torch.stack(loss, dim=1) # noqa: PD013 119 | 120 | return (loss * m).sum() / data.size()[0] 121 | 122 | @random_state 123 | def fit(self, train_data): 124 | 125 | train_data = self._transformer.transform(train_data) 126 | 127 | self._data_sampler = DataSampler( 128 | train_data, 129 | self._transformer.output_info_list, 130 | self._log_frequency) 131 | 132 | self._embedding_dim = self._data_dim 133 | 134 | self._generator = Generator( 135 | self._embedding_dim + self._data_sampler.dim_cond_vec(), 136 | self._generator_dim, 137 | self._data_dim 138 | ).to(self._device) 139 | 140 | self._generator.load_state_dict(torch.load(self._generator_model, map_location=self._device)) 141 | 142 | 143 | 144 | @random_state 145 | def sample(self, n, condition_column=None, condition_value=None): 146 | """Sample data similar to the training data. 147 | 148 | Choosing a condition_column and condition_value will increase the probability of the 149 | discrete condition_value happening in the condition_column. 150 | 151 | Args: 152 | n (int): 153 | Number of rows to sample. 154 | condition_column (string): 155 | Name of a discrete column. 156 | condition_value (string): 157 | Name of the category in the condition_column which we wish to increase the 158 | probability of happening. 159 | 160 | Returns: 161 | numpy.ndarray or pandas.DataFrame 162 | """ 163 | if condition_column is not None and condition_value is not None: 164 | condition_info = self._transformer.convert_column_name_value_to_id( 165 | condition_column, condition_value) 166 | global_condition_vec = self._data_sampler.generate_cond_from_condition_column_info( 167 | condition_info, self._batch_size) 168 | else: 169 | global_condition_vec = None 170 | 171 | steps = n // self._batch_size + 1 172 | data = [] 173 | for i in range(steps): 174 | mean = torch.zeros(self._batch_size, self._embedding_dim) 175 | std = mean + 1 176 | fakez = torch.normal(mean=mean, std=std).to(self._device) 177 | 178 | # if self._noise_generator is None: 179 | # fakez = torch.normal(mean=mean, std=std) 180 | # else: 181 | # fakez = self._noise_generator.forward(n_samples=self._batch_size).to(self._device) 182 | 183 | if global_condition_vec is not None: 184 | condvec = global_condition_vec.copy() 185 | else: 186 | condvec = self._data_sampler.sample_original_condvec(self._batch_size) 187 | 188 | if condvec is None: 189 | pass 190 | else: 191 | c1 = condvec 192 | c1 = torch.from_numpy(c1).to(self._device) 193 | fakez = torch.cat([fakez, c1], dim=1) 194 | 195 | fake = self._generator(fakez) 196 | fakeact = self._apply_activate(fake) 197 | data.append(fakeact.detach().cpu().numpy()) 198 | 199 | data = np.concatenate(data, axis=0) 200 | data = data[:n] 201 | 202 | return self._transformer.inverse_transform(data) 203 | 204 | def set_device(self, device): 205 | """Set the `device` to be used ('GPU' or 'CPU).""" 206 | self._device = device 207 | if self._generator is not None: 208 | self._generator.to(self._device) 209 | -------------------------------------------------------------------------------- /trainers/cae_train.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | import os 3 | from helpers.base_model import BaseModel, random_state 4 | # from data_handler.data_transformer import DataTransformer 5 | from data_handler.data_sampler import DataSampler 6 | from models.cae_model import CAE 7 | import torch 8 | import torch.nn as nn 9 | import pandas as pd 10 | import numpy as np 11 | from torch import optim 12 | import torch.nn.functional as F 13 | import wandb 14 | 15 | 16 | class CAETrain(BaseModel): 17 | """Conditional Table GAN Synthesizer. 18 | 19 | This is the core class of the CTGAN project, where the different components 20 | are orchestrated together. 21 | For more details about the process, please check the [Modeling Tabular data using 22 | Conditional GAN](https://arxiv.org/abs/1907.00503) paper. 23 | 24 | Args: 25 | embedding_dim (int): 26 | Size of the random sample passed to the Generator. Defaults to 128. 27 | generator_dim (tuple or list of ints): 28 | Size of the output samples for each one of the Residuals. A Residual Layer 29 | will be created for each one of the values provided. Defaults to (256, 256). 30 | discriminator_dim (tuple or list of ints): 31 | Size of the output samples for each one of the Discriminator Layers. A Linear Layer 32 | will be created for each one of the values provided. Defaults to (256, 256). 33 | generator_lr (float): 34 | Learning rate for the generator. Defaults to 2e-4. 35 | generator_decay (float): 36 | Generator weight decay for the Adam Optimizer. Defaults to 1e-6. 37 | batch_size (int): 38 | Number of data samples to process in each step. 39 | log_frequency (boolean): 40 | Whether to use log frequency of categorical levels in conditional 41 | sampling. Defaults to ``True``. 42 | verbose (boolean): 43 | Whether to have print statements for progress results. Defaults to ``False``. 44 | epochs (int): 45 | Number of training epochs. Defaults to 300. 46 | cuda (bool): 47 | Whether to attempt to use cuda for GPU computation. 48 | If this is False or CUDA is not available, CPU will be used. 49 | Defaults to ``True``. 50 | """ 51 | 52 | def __init__(self, transformer, data_dim, hidden_size=256, latent_size=64, lr=1e-3, optim_decay=1e-6, 53 | batch_size=500, contractive_weight=0.25, beta=0.25, log_frequency=True, verbose=False, epochs=300, 54 | device='cpu', save_directory='saved_models', dataset=None, is_wandb=False, *args, **kwargs): 55 | 56 | super().__init__(*args, **kwargs) 57 | assert batch_size % 2 == 0 58 | 59 | self.is_wandb = is_wandb 60 | 61 | if is_wandb: 62 | wandb.init(project='cactgan', name=f"CAE-{dataset}-{datetime.now().date().strftime('%m-%d-%Y')}-{int(datetime.now().timestamp())}", 63 | config={ 64 | "learning_rate": lr, 65 | "batch_size": batch_size, 66 | "dataset": dataset, 67 | "epochs": epochs, 68 | } 69 | ) 70 | 71 | self._data_dim = data_dim 72 | 73 | self._hidden_size = hidden_size 74 | self._latent_size = latent_size 75 | 76 | self._lr = lr 77 | self._optim_decay = optim_decay 78 | 79 | self._batch_size = batch_size 80 | self._log_frequency = log_frequency 81 | self._verbose = verbose 82 | self._epochs = epochs 83 | self.contractive_weight = contractive_weight 84 | self._beta = beta 85 | 86 | if self._verbose: 87 | print("Device: ", device) 88 | 89 | self._device = torch.device(device) 90 | 91 | self.save_directory = save_directory + "/cae/" + dataset 92 | self.dataset = dataset 93 | if save_directory: 94 | os.makedirs(self.save_directory, exist_ok=True) # Create the save directory if it doesn't exist 95 | self.df_result = pd.DataFrame( 96 | columns=["epoch", "batch", "loss", "time"]) 97 | 98 | self._transformer = transformer 99 | self._data_sampler = None 100 | 101 | def _loss_fn(self, output, target): 102 | mse_loss = nn.MSELoss() 103 | MSE = mse_loss(output, target) 104 | output_normalized = F.softmax(output, dim=1) 105 | target_normalized = F.softmax(target, dim=1) 106 | # KLD = torch.sum(target * (torch.log(target) - torch.log(output))) 107 | KLD = torch.sum( 108 | target_normalized * (torch.log(target_normalized + 1e-10) - torch.log(output_normalized + 1e-10))) 109 | 110 | total_loss = MSE + self._beta * KLD 111 | return total_loss 112 | 113 | def _validate_discrete_columns(self, train_data, discrete_columns): 114 | """Check whether ``discrete_columns`` exists in ``train_data``. 115 | 116 | Args: 117 | train_data (numpy.ndarray or pandas.DataFrame): 118 | Training Data. It must be a 2-dimensional numpy array or a pandas.DataFrame. 119 | discrete_columns (list-like): 120 | List of discrete columns to be used to generate the Conditional 121 | Vector. If ``train_data`` is a Numpy array, this list should 122 | contain the integer indices of the columns. Otherwise, if it is 123 | a ``pandas.DataFrame``, this list should contain the column names. 124 | """ 125 | if isinstance(train_data, pd.DataFrame): 126 | invalid_columns = set(discrete_columns) - set(train_data.columns) 127 | elif isinstance(train_data, np.ndarray): 128 | invalid_columns = [] 129 | for column in discrete_columns: 130 | if column < 0 or column >= train_data.shape[1]: 131 | invalid_columns.append(column) 132 | else: 133 | raise TypeError('``train_data`` should be either pd.DataFrame or np.array.') 134 | 135 | if invalid_columns: 136 | raise ValueError(f'Invalid columns found: {invalid_columns}') 137 | 138 | @random_state 139 | def fit(self, train_data, discrete_columns=()): 140 | """Fit the CTGAN Synthesizer models to the training data. 141 | 142 | Args: 143 | train_data (numpy.ndarray or pandas.DataFrame): 144 | Training Data. It must be a 2-dimensional numpy array or a pandas.DataFrame. 145 | discrete_columns (list-like): 146 | List of discrete columns to be used to generate the Conditional 147 | Vector. If ``train_data`` is a Numpy array, this list should 148 | contain the integer indices of the columns. Otherwise, if it is 149 | a ``pandas.DataFrame``, this list should contain the column names. 150 | """ 151 | self._validate_discrete_columns(train_data, discrete_columns) 152 | 153 | train_data = self._transformer.transform(train_data) 154 | 155 | self._data_sampler = DataSampler( 156 | train_data, 157 | self._transformer.output_info_list, 158 | self._log_frequency) 159 | 160 | data_dim = self._transformer.output_dimensions 161 | 162 | cae_model = CAE(data_dim, self._hidden_size, self._latent_size).to(self._device) 163 | 164 | optimizer = optim.Adam( 165 | cae_model.parameters(), lr=self._lr, betas=(0.5, 0.9), 166 | weight_decay=self._optim_decay 167 | ) 168 | 169 | # criterion = nn.MSELoss() 170 | 171 | steps_per_epoch = max(len(train_data) // self._batch_size, 1) 172 | for i in range(self._epochs): 173 | running_loss = 0. 174 | for id_ in range(steps_per_epoch): 175 | 176 | condvec = self._data_sampler.sample_condvec(self._batch_size) 177 | if condvec is None: 178 | c1, m1, col, opt = None, None, None, None 179 | real = self._data_sampler.sample_data(self._batch_size, col, opt) 180 | else: 181 | c1, m1, col, opt = condvec 182 | 183 | perm = np.arange(self._batch_size) 184 | np.random.shuffle(perm) 185 | real = self._data_sampler.sample_data( 186 | self._batch_size, col[perm], opt[perm]) 187 | 188 | inputs = torch.from_numpy(real.astype('float32')).to(self._device) 189 | 190 | inputs.requires_grad_(True) # Ensure gradient computation 191 | 192 | # Forward pass 193 | latent, outputs = cae_model(inputs) 194 | 195 | # Compute reconstruction loss and the jacobian penalty 196 | recon_loss = self._loss_fn(outputs, inputs) 197 | jacobian_loss = cae_model.jacobian_penalty(inputs, latent) # Use latent representation for penalty 198 | loss = recon_loss + self.contractive_weight * jacobian_loss 199 | 200 | # Backward pass and optimization 201 | optimizer.zero_grad() 202 | loss.backward() 203 | optimizer.step() 204 | 205 | running_loss += loss.item() 206 | 207 | self.df_result.loc[len(self.df_result.index)] = [i + 1, id_ + 1, loss.item(), datetime.now()] 208 | running_loss /= steps_per_epoch 209 | if self._verbose: 210 | print(f'Epoch {i + 1}, Loss: {running_loss: .4f}, Time: {datetime.now()}', 211 | flush=True) 212 | if self.is_wandb: 213 | wandb.log({"loss": running_loss}) 214 | 215 | if self.is_wandb: 216 | wandb.finish() 217 | if self.save_directory: 218 | # Save the final trained model 219 | torch.save(cae_model.state_dict(), os.path.join(self.save_directory, 220 | f"cae_{self.dataset}_{self.dataset}_{datetime.now().date().strftime('%m%d%Y')}_{self._device}.pth")) 221 | # Save training result 222 | self.df_result.to_csv(os.path.join(self.save_directory, 223 | f"cae_logs_{self.dataset}_{datetime.now().date().strftime('%m%d%Y')}.csv"), 224 | index=False) 225 | 226 | return cae_model 227 | -------------------------------------------------------------------------------- /data_handler/data_transformer.py: -------------------------------------------------------------------------------- 1 | """DataTransformer module.""" 2 | 3 | from collections import namedtuple 4 | 5 | import numpy as np 6 | import pandas as pd 7 | from joblib import Parallel, delayed 8 | from rdt.transformers import ClusterBasedNormalizer, OneHotEncoder 9 | 10 | SpanInfo = namedtuple('SpanInfo', ['dim', 'activation_fn']) 11 | ColumnTransformInfo = namedtuple( 12 | 'ColumnTransformInfo', [ 13 | 'column_name', 'column_type', 'transform', 'output_info', 'output_dimensions' 14 | ] 15 | ) 16 | 17 | 18 | class DataTransformer(object): 19 | """Data Transformer. 20 | 21 | Model continuous columns with a BayesianGMM and normalize them to a scalar between [-1, 1] 22 | and a vector. Discrete columns are encoded using a OneHotEncoder. 23 | """ 24 | 25 | def __init__(self, max_clusters=10, weight_threshold=0.005): 26 | """Create a data transformer. 27 | 28 | Args: 29 | max_clusters (int): 30 | Maximum number of Gaussian distributions in Bayesian GMM. 31 | weight_threshold (float): 32 | Weight threshold for a Gaussian distribution to be kept. 33 | """ 34 | self._max_clusters = max_clusters 35 | self._weight_threshold = weight_threshold 36 | 37 | def _fit_continuous(self, data): 38 | """Train Bayesian GMM for continuous columns. 39 | 40 | Args: 41 | data (pd.DataFrame): 42 | A dataframe containing a column. 43 | 44 | Returns: 45 | namedtuple: 46 | A ``ColumnTransformInfo`` object. 47 | """ 48 | column_name = data.columns[0] 49 | gm = ClusterBasedNormalizer( 50 | missing_value_generation='from_column', 51 | max_clusters=min(len(data), self._max_clusters), 52 | weight_threshold=self._weight_threshold 53 | ) 54 | gm.fit(data, column_name) 55 | num_components = sum(gm.valid_component_indicator) 56 | 57 | return ColumnTransformInfo( 58 | column_name=column_name, column_type='continuous', transform=gm, 59 | output_info=[SpanInfo(1, 'tanh'), SpanInfo(num_components, 'softmax')], 60 | output_dimensions=1 + num_components) 61 | 62 | def _fit_discrete(self, data): 63 | """Fit one hot encoder for discrete column. 64 | 65 | Args: 66 | data (pd.DataFrame): 67 | A dataframe containing a column. 68 | 69 | Returns: 70 | namedtuple: 71 | A ``ColumnTransformInfo`` object. 72 | """ 73 | column_name = data.columns[0] 74 | ohe = OneHotEncoder() 75 | ohe.fit(data, column_name) 76 | num_categories = len(ohe.dummies) 77 | 78 | return ColumnTransformInfo( 79 | column_name=column_name, column_type='discrete', transform=ohe, 80 | output_info=[SpanInfo(num_categories, 'softmax')], 81 | output_dimensions=num_categories) 82 | 83 | def fit(self, raw_data, discrete_columns=()): 84 | """Fit the ``DataTransformer``. 85 | 86 | Fits a ``ClusterBasedNormalizer`` for continuous columns and a 87 | ``OneHotEncoder`` for discrete columns. 88 | 89 | This step also counts the #columns in matrix data and span information. 90 | """ 91 | self.output_info_list = [] 92 | self.output_dimensions = 0 93 | self.dataframe = True 94 | 95 | if not isinstance(raw_data, pd.DataFrame): 96 | self.dataframe = False 97 | # work around for RDT issue #328 Fitting with numerical column names fails 98 | discrete_columns = [str(column) for column in discrete_columns] 99 | column_names = [str(num) for num in range(raw_data.shape[1])] 100 | raw_data = pd.DataFrame(raw_data, columns=column_names) 101 | 102 | self._column_raw_dtypes = raw_data.infer_objects().dtypes 103 | self._column_transform_info_list = [] 104 | for column_name in raw_data.columns: 105 | if column_name in discrete_columns: 106 | column_transform_info = self._fit_discrete(raw_data[[column_name]]) 107 | else: 108 | column_transform_info = self._fit_continuous(raw_data[[column_name]]) 109 | 110 | self.output_info_list.append(column_transform_info.output_info) 111 | self.output_dimensions += column_transform_info.output_dimensions 112 | self._column_transform_info_list.append(column_transform_info) 113 | 114 | def _transform_continuous(self, column_transform_info, data): 115 | column_name = data.columns[0] 116 | flattened_column = data[column_name].to_numpy().flatten() 117 | data = data.assign(**{column_name: flattened_column}) 118 | gm = column_transform_info.transform 119 | transformed = gm.transform(data) 120 | 121 | # Converts the transformed data to the appropriate output format. 122 | # The first column (ending in '.normalized') stays the same, 123 | # but the lable encoded column (ending in '.component') is one hot encoded. 124 | output = np.zeros((len(transformed), column_transform_info.output_dimensions)) 125 | output[:, 0] = transformed[f'{column_name}.normalized'].to_numpy() 126 | index = transformed[f'{column_name}.component'].to_numpy().astype(int) 127 | output[np.arange(index.size), index + 1] = 1.0 128 | 129 | return output 130 | 131 | def _transform_discrete(self, column_transform_info, data): 132 | ohe = column_transform_info.transform 133 | return ohe.transform(data).to_numpy() 134 | 135 | def _synchronous_transform(self, raw_data, column_transform_info_list): 136 | """Take a Pandas DataFrame and transform columns synchronous. 137 | 138 | Outputs a list with Numpy arrays. 139 | """ 140 | column_data_list = [] 141 | for column_transform_info in column_transform_info_list: 142 | column_name = column_transform_info.column_name 143 | data = raw_data[[column_name]] 144 | if column_transform_info.column_type == 'continuous': 145 | column_data_list.append(self._transform_continuous(column_transform_info, data)) 146 | else: 147 | column_data_list.append(self._transform_discrete(column_transform_info, data)) 148 | 149 | return column_data_list 150 | 151 | def _parallel_transform(self, raw_data, column_transform_info_list): 152 | """Take a Pandas DataFrame and transform columns in parallel. 153 | 154 | Outputs a list with Numpy arrays. 155 | """ 156 | processes = [] 157 | for column_transform_info in column_transform_info_list: 158 | column_name = column_transform_info.column_name 159 | data = raw_data[[column_name]] 160 | process = None 161 | if column_transform_info.column_type == 'continuous': 162 | process = delayed(self._transform_continuous)(column_transform_info, data) 163 | else: 164 | process = delayed(self._transform_discrete)(column_transform_info, data) 165 | processes.append(process) 166 | 167 | return Parallel(n_jobs=-1)(processes) 168 | 169 | def transform(self, raw_data): 170 | """Take raw data and output a matrix data.""" 171 | if not isinstance(raw_data, pd.DataFrame): 172 | column_names = [str(num) for num in range(raw_data.shape[1])] 173 | raw_data = pd.DataFrame(raw_data, columns=column_names) 174 | 175 | # Only use parallelization with larger data sizes. 176 | # Otherwise, the transformation will be slower. 177 | if raw_data.shape[0] < 500: 178 | column_data_list = self._synchronous_transform( 179 | raw_data, 180 | self._column_transform_info_list 181 | ) 182 | else: 183 | column_data_list = self._parallel_transform( 184 | raw_data, 185 | self._column_transform_info_list 186 | ) 187 | 188 | return np.concatenate(column_data_list, axis=1).astype(float) 189 | 190 | def _inverse_transform_continuous(self, column_transform_info, column_data, sigmas, st): 191 | gm = column_transform_info.transform 192 | data = pd.DataFrame(column_data[:, :2], columns=list(gm.get_output_sdtypes())) 193 | data[data.columns[1]] = np.argmax(column_data[:, 1:], axis=1) 194 | if sigmas is not None: 195 | selected_normalized_value = np.random.normal(data.iloc[:, 0], sigmas[st]) 196 | data.iloc[:, 0] = selected_normalized_value 197 | 198 | return gm.reverse_transform(data) 199 | 200 | def _inverse_transform_discrete(self, column_transform_info, column_data): 201 | ohe = column_transform_info.transform 202 | data = pd.DataFrame(column_data, columns=list(ohe.get_output_sdtypes())) 203 | return ohe.reverse_transform(data)[column_transform_info.column_name] 204 | 205 | def inverse_transform(self, data, sigmas=None): 206 | """Take matrix data and output raw data. 207 | 208 | Output uses the same type as input to the transform function. 209 | Either np array or pd dataframe. 210 | """ 211 | st = 0 212 | recovered_column_data_list = [] 213 | column_names = [] 214 | for column_transform_info in self._column_transform_info_list: 215 | dim = column_transform_info.output_dimensions 216 | column_data = data[:, st:st + dim] 217 | if column_transform_info.column_type == 'continuous': 218 | recovered_column_data = self._inverse_transform_continuous( 219 | column_transform_info, column_data, sigmas, st) 220 | else: 221 | recovered_column_data = self._inverse_transform_discrete( 222 | column_transform_info, column_data) 223 | 224 | recovered_column_data_list.append(recovered_column_data) 225 | column_names.append(column_transform_info.column_name) 226 | st += dim 227 | 228 | recovered_data = np.column_stack(recovered_column_data_list) 229 | recovered_data = (pd.DataFrame(recovered_data, columns=column_names) 230 | .astype(self._column_raw_dtypes)) 231 | if not self.dataframe: 232 | recovered_data = recovered_data.to_numpy() 233 | 234 | return recovered_data 235 | 236 | def convert_column_name_value_to_id(self, column_name, value): 237 | """Get the ids of the given `column_name`.""" 238 | discrete_counter = 0 239 | column_id = 0 240 | for column_transform_info in self._column_transform_info_list: 241 | if column_transform_info.column_name == column_name: 242 | break 243 | if column_transform_info.column_type == 'discrete': 244 | discrete_counter += 1 245 | 246 | column_id += 1 247 | 248 | else: 249 | raise ValueError(f"The column_name `{column_name}` doesn't exist in the data.") 250 | 251 | ohe = column_transform_info.transform 252 | data = pd.DataFrame([value], columns=[column_transform_info.column_name]) 253 | one_hot = ohe.transform(data).to_numpy()[0] 254 | if sum(one_hot) == 0: 255 | raise ValueError(f"The value `{value}` doesn't exist in the column `{column_name}`.") 256 | 257 | return { 258 | 'discrete_column_id': discrete_counter, 259 | 'column_id': column_id, 260 | 'value_id': np.argmax(one_hot) 261 | } 262 | -------------------------------------------------------------------------------- /trainers/gan_train.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | import os 3 | from helpers.base_model import BaseModel, random_state 4 | from data_handler.data_transformer import DataTransformer 5 | from data_handler.data_sampler import DataSampler 6 | from models.gan_model import Generator, Discriminator 7 | import torch 8 | import torch.nn as nn 9 | import pandas as pd 10 | import numpy as np 11 | import warnings 12 | from torch import optim 13 | 14 | 15 | class CTGAN(BaseModel): 16 | """Conditional Table GAN Synthesizer. 17 | 18 | This is the core class of the CTGAN project, where the different components 19 | are orchestrated together. 20 | For more details about the process, please check the [Modeling Tabular data using 21 | Conditional GAN](https://arxiv.org/abs/1907.00503) paper. 22 | 23 | Args: 24 | embedding_dim (int): 25 | Size of the random sample passed to the Generator. Defaults to 128. 26 | generator_dim (tuple or list of ints): 27 | Size of the output samples for each one of the Residuals. A Residual Layer 28 | will be created for each one of the values provided. Defaults to (256, 256). 29 | discriminator_dim (tuple or list of ints): 30 | Size of the output samples for each one of the Discriminator Layers. A Linear Layer 31 | will be created for each one of the values provided. Defaults to (256, 256). 32 | generator_lr (float): 33 | Learning rate for the generator. Defaults to 2e-4. 34 | generator_decay (float): 35 | Generator weight decay for the Adam Optimizer. Defaults to 1e-6. 36 | discriminator_lr (float): 37 | Learning rate for the discriminator. Defaults to 2e-4. 38 | discriminator_decay (float): 39 | Discriminator weight decay for the Adam Optimizer. Defaults to 1e-6. 40 | batch_size (int): 41 | Number of data samples to process in each step. 42 | discriminator_steps (int): 43 | Number of discriminator updates to do for each generator update. 44 | From the WGAN paper: https://arxiv.org/abs/1701.07875. WGAN paper 45 | default is 5. Default used is 1 to match original CTGAN implementation. 46 | log_frequency (boolean): 47 | Whether to use log frequency of categorical levels in conditional 48 | sampling. Defaults to ``True``. 49 | verbose (boolean): 50 | Whether to have print statements for progress results. Defaults to ``False``. 51 | epochs (int): 52 | Number of training epochs. Defaults to 300. 53 | pac (int): 54 | Number of samples to group together when applying the discriminator. 55 | Defaults to 10. 56 | cuda (bool): 57 | Whether to attempt to use cuda for GPU computation. 58 | If this is False or CUDA is not available, CPU will be used. 59 | Defaults to ``True``. 60 | """ 61 | 62 | def __init__(self, embedding_dim=156, generator_dim=(256, 256), discriminator_dim=(256, 256), 63 | generator_lr=2e-4, generator_decay=1e-6, discriminator_lr=2e-4, 64 | discriminator_decay=1e-6, batch_size=500, discriminator_steps=1, 65 | log_frequency=True, verbose=False, epochs=300, pac=10, device='cpu', 66 | save_directory=None, save_interval=50): 67 | 68 | assert batch_size % 2 == 0 69 | 70 | # self._embedding_dim = embedding_dim 71 | self._embedding_dim = None 72 | self._generator_dim = generator_dim 73 | self._discriminator_dim = discriminator_dim 74 | 75 | self._generator_lr = generator_lr 76 | self._generator_decay = generator_decay 77 | self._discriminator_lr = discriminator_lr 78 | self._discriminator_decay = discriminator_decay 79 | 80 | self._batch_size = batch_size 81 | self._discriminator_steps = discriminator_steps 82 | self._log_frequency = log_frequency 83 | self._verbose = verbose 84 | self._epochs = epochs 85 | self.pac = pac 86 | 87 | if self._verbose: 88 | print("Device: ", device) 89 | 90 | self._device = torch.device(device) 91 | 92 | self.save_interval = save_interval 93 | self.save_directory = save_directory 94 | if save_directory: 95 | os.makedirs(self.save_directory, exist_ok=True) # Create the save directory if it doesn't exist 96 | self.df_result = pd.DataFrame( 97 | columns=["epoch", "g_loss", "d_loss", "g_running_loss", "d_running_loss", "time"]) 98 | 99 | self._transformer = None 100 | self._data_sampler = None 101 | self._generator = None 102 | 103 | @staticmethod 104 | def _gumbel_softmax(logits, tau=1, hard=False, eps=1e-10, dim=-1): 105 | """Deals with the instability of the gumbel_softmax for older versions of torch. 106 | 107 | For more details about the issue: 108 | https://drive.google.com/file/d/1AA5wPfZ1kquaRtVruCd6BiYZGcDeNxyP/view?usp=sharing 109 | 110 | Args: 111 | logits […, num_features]: 112 | Unnormalized log probabilities 113 | tau: 114 | Non-negative scalar temperature 115 | hard (bool): 116 | If True, the returned samples will be discretized as one-hot vectors, 117 | but will be differentiated as if it is the soft sample in autograd 118 | dim (int): 119 | A dimension along which softmax will be computed. Default: -1. 120 | 121 | Returns: 122 | Sampled tensor of same shape as logits from the Gumbel-Softmax distribution. 123 | """ 124 | for _ in range(10): 125 | transformed = nn.functional.gumbel_softmax(logits, tau=tau, hard=hard, eps=eps, dim=dim) 126 | if not torch.isnan(transformed).any(): 127 | return transformed 128 | 129 | raise ValueError('gumbel_softmax returning NaN.') 130 | 131 | def _apply_activate(self, data): 132 | """Apply proper activation function to the output of the generator.""" 133 | data_t = [] 134 | st = 0 135 | for column_info in self._transformer.output_info_list: 136 | for span_info in column_info: 137 | if span_info.activation_fn == 'tanh': 138 | ed = st + span_info.dim 139 | data_t.append(torch.tanh(data[:, st:ed])) 140 | st = ed 141 | elif span_info.activation_fn == 'softmax': 142 | ed = st + span_info.dim 143 | transformed = self._gumbel_softmax(data[:, st:ed], tau=0.2) 144 | data_t.append(transformed) 145 | st = ed 146 | else: 147 | raise ValueError(f'Unexpected activation function {span_info.activation_fn}.') 148 | 149 | return torch.cat(data_t, dim=1) 150 | 151 | def _cond_loss(self, data, c, m): 152 | """Compute the cross entropy loss on the fixed discrete column.""" 153 | loss = [] 154 | st = 0 155 | st_c = 0 156 | for column_info in self._transformer.output_info_list: 157 | for span_info in column_info: 158 | if len(column_info) != 1 or span_info.activation_fn != 'softmax': 159 | # not discrete column 160 | st += span_info.dim 161 | else: 162 | ed = st + span_info.dim 163 | ed_c = st_c + span_info.dim 164 | tmp = nn.functional.cross_entropy( 165 | data[:, st:ed], 166 | torch.argmax(c[:, st_c:ed_c], dim=1), 167 | reduction='none' 168 | ) 169 | loss.append(tmp) 170 | st = ed 171 | st_c = ed_c 172 | 173 | loss = torch.stack(loss, dim=1) # noqa: PD013 174 | 175 | return (loss * m).sum() / data.size()[0] 176 | 177 | def _validate_discrete_columns(self, train_data, discrete_columns): 178 | """Check whether ``discrete_columns`` exists in ``train_data``. 179 | 180 | Args: 181 | train_data (numpy.ndarray or pandas.DataFrame): 182 | Training Data. It must be a 2-dimensional numpy array or a pandas.DataFrame. 183 | discrete_columns (list-like): 184 | List of discrete columns to be used to generate the Conditional 185 | Vector. If ``train_data`` is a Numpy array, this list should 186 | contain the integer indices of the columns. Otherwise, if it is 187 | a ``pandas.DataFrame``, this list should contain the column names. 188 | """ 189 | if isinstance(train_data, pd.DataFrame): 190 | invalid_columns = set(discrete_columns) - set(train_data.columns) 191 | elif isinstance(train_data, np.ndarray): 192 | invalid_columns = [] 193 | for column in discrete_columns: 194 | if column < 0 or column >= train_data.shape[1]: 195 | invalid_columns.append(column) 196 | else: 197 | raise TypeError('``train_data`` should be either pd.DataFrame or np.array.') 198 | 199 | if invalid_columns: 200 | raise ValueError(f'Invalid columns found: {invalid_columns}') 201 | 202 | @random_state 203 | def fit(self, train_data, discrete_columns=(), epochs=None): 204 | """Fit the CTGAN Synthesizer models to the training data. 205 | 206 | Args: 207 | train_data (numpy.ndarray or pandas.DataFrame): 208 | Training Data. It must be a 2-dimensional numpy array or a pandas.DataFrame. 209 | discrete_columns (list-like): 210 | List of discrete columns to be used to generate the Conditional 211 | Vector. If ``train_data`` is a Numpy array, this list should 212 | contain the integer indices of the columns. Otherwise, if it is 213 | a ``pandas.DataFrame``, this list should contain the column names. 214 | """ 215 | self._validate_discrete_columns(train_data, discrete_columns) 216 | 217 | if epochs is None: 218 | epochs = self._epochs 219 | else: 220 | warnings.warn( 221 | ('`epochs` argument in `fit` method has been deprecated and will be removed ' 222 | 'in a future version. Please pass `epochs` to the constructor instead'), 223 | DeprecationWarning 224 | ) 225 | 226 | self._transformer = DataTransformer() 227 | self._transformer.fit(train_data, discrete_columns) 228 | 229 | train_data = self._transformer.transform(train_data) 230 | 231 | self._data_sampler = DataSampler( 232 | train_data, 233 | self._transformer.output_info_list, 234 | self._log_frequency) 235 | 236 | data_dim = self._transformer.output_dimensions 237 | self._embedding_dim = data_dim 238 | 239 | print("_data_sampler: ", self._data_sampler.dim_cond_vec()) 240 | print("embedding_dim: ", self._embedding_dim + self._data_sampler.dim_cond_vec()) 241 | print("generator_dim: ", self._generator_dim) 242 | print("data_dim: ",data_dim) 243 | 244 | self._generator = Generator( 245 | self._embedding_dim + self._data_sampler.dim_cond_vec(), 246 | self._generator_dim, 247 | data_dim 248 | ).to(self._device) 249 | 250 | print(self._generator) 251 | 252 | discriminator = Discriminator( 253 | data_dim + self._data_sampler.dim_cond_vec(), 254 | self._discriminator_dim, 255 | pac=self.pac 256 | ).to(self._device) 257 | 258 | optimizerG = optim.Adam( 259 | self._generator.parameters(), lr=self._generator_lr, betas=(0.5, 0.9), 260 | weight_decay=self._generator_decay 261 | ) 262 | 263 | optimizerD = optim.Adam( 264 | discriminator.parameters(), lr=self._discriminator_lr, 265 | betas=(0.5, 0.9), weight_decay=self._discriminator_decay 266 | ) 267 | 268 | self.criterion = nn.MSELoss() 269 | 270 | mean = torch.zeros(self._batch_size, self._embedding_dim, device=self._device) 271 | std = mean + 1 272 | 273 | steps_per_epoch = max(len(train_data) // self._batch_size, 1) 274 | 275 | for i in range(epochs): 276 | running_loss_d = 0. 277 | running_loss_g = 0. 278 | running_loss_g_sol = 0. 279 | for id_ in range(steps_per_epoch): 280 | running_loss_d_i = 0. 281 | 282 | for n in range(self._discriminator_steps): 283 | fakez = torch.normal(mean=mean, std=std) 284 | 285 | condvec = self._data_sampler.sample_condvec(self._batch_size) 286 | if condvec is None: 287 | c1, m1, col, opt = None, None, None, None 288 | real = self._data_sampler.sample_data(self._batch_size, col, opt) 289 | else: 290 | c1, m1, col, opt = condvec 291 | c1 = torch.from_numpy(c1).to(self._device) 292 | 293 | # c1 torch.Size([500, 104]) 294 | # number of category 295 | m1 = torch.from_numpy(m1).to(self._device) 296 | fakez = torch.cat([fakez, c1], dim=1) 297 | # torch.Size([500, 232]) 298 | 299 | perm = np.arange(self._batch_size) 300 | np.random.shuffle(perm) 301 | real = self._data_sampler.sample_data( 302 | self._batch_size, col[perm], opt[perm]) 303 | c2 = c1[perm] 304 | 305 | fake = self._generator(fakez) 306 | fakeact = self._apply_activate(fake) 307 | 308 | real = torch.from_numpy(real.astype('float32')).to(self._device) 309 | # torch.Size([500, 156]) 310 | 311 | if c1 is not None: 312 | fake_cat = torch.cat([fakeact, c1], dim=1) 313 | real_cat = torch.cat([real, c2], dim=1) 314 | # fake_cat: torch.Size([500, 260]) 315 | # real_cat: torch.Size([500, 260]) 316 | # fakeact: torch.Size([500, 156]) 317 | # c1: torch.Size([500, 104]) 318 | # c2: torch.Size([500, 104]) 319 | else: 320 | real_cat = real 321 | fake_cat = fakeact 322 | 323 | y_fake = discriminator(fake_cat) 324 | y_real = discriminator(real_cat) 325 | 326 | pen = discriminator.calc_gradient_penalty( 327 | real_cat, fake_cat, self._device, self.pac) 328 | loss_d = -(torch.mean(y_real) - torch.mean(y_fake)) 329 | running_loss_d_i += abs((torch.mean(y_fake) - torch.mean(y_real)).item()) 330 | 331 | optimizerD.zero_grad(set_to_none=False) 332 | pen.backward(retain_graph=True) 333 | loss_d.backward() 334 | optimizerD.step() 335 | running_loss_d_i /= self._discriminator_steps 336 | running_loss_d += running_loss_d_i 337 | 338 | fakez = torch.normal(mean=mean, std=std) 339 | condvec = self._data_sampler.sample_condvec(self._batch_size) 340 | 341 | if condvec is None: 342 | c1, m1, col, opt = None, None, None, None 343 | else: 344 | c1, m1, col, opt = condvec 345 | c1 = torch.from_numpy(c1).to(self._device) 346 | m1 = torch.from_numpy(m1).to(self._device) 347 | fakez = torch.cat([fakez, c1], dim=1) 348 | 349 | fake = self._generator(fakez) 350 | fakeact = self._apply_activate(fake) 351 | 352 | if c1 is not None: 353 | y_fake = discriminator(torch.cat([fakeact, c1], dim=1)) 354 | else: 355 | y_fake = discriminator(fakeact) 356 | 357 | if condvec is None: 358 | cross_entropy = 0 359 | else: 360 | cross_entropy = self._cond_loss(fake, c1, m1) 361 | 362 | loss_g = -torch.mean(y_fake) + cross_entropy 363 | running_loss_g += abs((-torch.mean(y_fake) + cross_entropy).item()) 364 | running_loss_g_sol += abs(torch.mean(y_fake).item()) 365 | 366 | optimizerG.zero_grad(set_to_none=False) 367 | loss_g.backward() 368 | optimizerG.step() 369 | 370 | running_loss_g /= steps_per_epoch 371 | running_loss_g_sol /= steps_per_epoch 372 | running_loss_d /= steps_per_epoch 373 | 374 | self.df_result.loc[len(self.df_result.index)] = [i + 1, loss_g.item(), loss_d.item(), running_loss_d, 375 | running_loss_g, datetime.now()] 376 | if self._verbose: 377 | print(f'Epoch {i + 1}, Loss G: {loss_g.detach().cpu(): .4f},' 378 | f'Loss D: {loss_d.detach().cpu(): .4f}, Running Loss D: {running_loss_d: .4f}', 379 | f'Running Loss G: {running_loss_g: .4f}, Running Loss G C: {running_loss_g_sol: .4f}', 380 | flush=True) 381 | 382 | if (i + 1) % self.save_interval == 0: 383 | torch.save(self._generator.state_dict(), os.path.join(self.save_directory, 384 | f"generator_model_checkpoint_{i + 1}_{datetime.now().date().strftime('%m%d%Y')}_{self._device}.pth")) 385 | 386 | if self.save_directory: 387 | # Save the final trained model 388 | torch.save(self._generator.state_dict(), os.path.join(self.save_directory, 389 | f"generator_final_saved_model_{datetime.now().date().strftime('%m%d%Y')}_{self._device}.pth")) 390 | # Save training result 391 | self.df_result.to_csv(os.path.join(self.save_directory, 392 | f"gan_logs_{datetime.now().date().strftime('%m%d%Y')}.csv"), 393 | index=False) 394 | 395 | @random_state 396 | def sample(self, n, condition_column=None, condition_value=None): 397 | """Sample data similar to the training data. 398 | 399 | Choosing a condition_column and condition_value will increase the probability of the 400 | discrete condition_value happening in the condition_column. 401 | 402 | Args: 403 | n (int): 404 | Number of rows to sample. 405 | condition_column (string): 406 | Name of a discrete column. 407 | condition_value (string): 408 | Name of the category in the condition_column which we wish to increase the 409 | probability of happening. 410 | 411 | Returns: 412 | numpy.ndarray or pandas.DataFrame 413 | """ 414 | if condition_column is not None and condition_value is not None: 415 | condition_info = self._transformer.convert_column_name_value_to_id( 416 | condition_column, condition_value) 417 | global_condition_vec = self._data_sampler.generate_cond_from_condition_column_info( 418 | condition_info, self._batch_size) 419 | else: 420 | global_condition_vec = None 421 | 422 | steps = n // self._batch_size + 1 423 | data = [] 424 | for i in range(steps): 425 | mean = torch.zeros(self._batch_size, self._embedding_dim) 426 | std = mean + 1 427 | fakez = torch.normal(mean=mean, std=std).to(self._device) 428 | 429 | if global_condition_vec is not None: 430 | condvec = global_condition_vec.copy() 431 | else: 432 | condvec = self._data_sampler.sample_original_condvec(self._batch_size) 433 | 434 | if condvec is None: 435 | pass 436 | else: 437 | c1 = condvec 438 | c1 = torch.from_numpy(c1).to(self._device) 439 | fakez = torch.cat([fakez, c1], dim=1) 440 | 441 | fake = self._generator(fakez) 442 | fakeact = self._apply_activate(fake) 443 | data.append(fakeact.detach().cpu().numpy()) 444 | 445 | data = np.concatenate(data, axis=0) 446 | data = data[:n] 447 | 448 | return self._transformer.inverse_transform(data) 449 | 450 | def set_device(self, device): 451 | """Set the `device` to be used ('GPU' or 'CPU).""" 452 | self._device = device 453 | if self._generator is not None: 454 | self._generator.to(self._device) 455 | -------------------------------------------------------------------------------- /trainers/gan_cae_train.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | import os 3 | from helpers.base_model import BaseModel, random_state 4 | from data_handler import embedding_dim 5 | from data_handler.data_sampler import DataSampler 6 | from data_handler.classifier_transformer import ClassifierDataTransformer 7 | from models.gan_model import Generator, Discriminator 8 | from models.classifier_model import ClassifierModel 9 | import torch 10 | import torch.nn as nn 11 | import torch.nn.functional as F 12 | import pandas as pd 13 | import numpy as np 14 | import warnings 15 | from torch import optim 16 | import wandb 17 | 18 | 19 | class CTGAN(BaseModel): 20 | def __init__(self, transformer, data_dim, noise_generator=None, generator_dim=(256, 256), 21 | discriminator_dim=(256, 256), 22 | generator_lr=2e-4, generator_decay=1e-6, discriminator_lr=2e-4, 23 | discriminator_decay=1e-6, batch_size=500, discriminator_steps=1, is_wandb=False, 24 | log_frequency=True, verbose=False, epochs=300, pac=10, device='cpu', 25 | save_directory='saved_models', save_interval=50, dataset=None): 26 | super(CTGAN, self).__init__() 27 | 28 | assert batch_size % 2 == 0 29 | 30 | self.is_wandb = is_wandb 31 | 32 | if is_wandb: 33 | if noise_generator is None: 34 | wan_project = "cactgan_gan" 35 | wan_name = f"CTGAN-{dataset}-{datetime.now().date().strftime('%m-%d-%Y')}-{int(datetime.now().timestamp())}" 36 | else: 37 | wan_project = "cactgan_cae_gan" 38 | wan_name = f"CACTGAN-{dataset}-{datetime.now().date().strftime('%m-%d-%Y')}-{int(datetime.now().timestamp())}" 39 | 40 | wandb.init(project=wan_project, 41 | name=wan_name, 42 | config={ 43 | "learning_rate": generator_lr, 44 | "learning_rate_decay": generator_decay, 45 | "batch_size": batch_size, 46 | "dataset": dataset, 47 | "epochs": epochs, 48 | } 49 | ) 50 | 51 | self._embedding_dim = None 52 | self._data_dim = data_dim 53 | self._generator_dim = generator_dim 54 | self._discriminator_dim = discriminator_dim 55 | 56 | self._generator_lr = generator_lr 57 | self._generator_decay = generator_decay 58 | self._discriminator_lr = discriminator_lr 59 | self._discriminator_decay = discriminator_decay 60 | 61 | self._batch_size = batch_size 62 | self._discriminator_steps = discriminator_steps 63 | self._log_frequency = log_frequency 64 | self._verbose = verbose 65 | self._epochs = epochs 66 | self.pac = pac 67 | 68 | if self._verbose: 69 | print("Device: ", device) 70 | 71 | self._device = torch.device(device) 72 | 73 | self.save_interval = save_interval 74 | 75 | if self._noise_generator is None: 76 | self.save_directory = save_directory + "/gan/" + dataset 77 | else: 78 | self.save_directory = save_directory + "/cae_gan/" + dataset 79 | self.dataset = dataset 80 | if save_directory: 81 | os.makedirs(self.save_directory, exist_ok=True) # Create the save directory if it doesn't exist 82 | self.df_result = pd.DataFrame( 83 | columns=["epoch", "g_loss", "d_loss", "g_running_loss", "d_running_loss", "time"]) 84 | 85 | self._transformer = transformer 86 | self._data_sampler = None 87 | self._generator = None 88 | self._classifier = None 89 | self._noise_generator = None # noise_generator 90 | 91 | @staticmethod 92 | def _gumbel_softmax(logits, tau=1, hard=False, eps=1e-10, dim=-1): 93 | """Deals with the instability of the gumbel_softmax for older versions of torch. 94 | Args: 95 | logits […, num_features]: 96 | Unnormalized log probabilities 97 | tau: 98 | Non-negative scalar temperature 99 | hard (bool): 100 | If True, the returned samples will be discretized as one-hot vectors, 101 | but will be differentiated as if it is the soft sample in autograd 102 | dim (int): 103 | A dimension along which softmax will be computed. Default: -1. 104 | 105 | Returns: 106 | Sampled tensor of same shape as logits from the Gumbel-Softmax distribution. 107 | """ 108 | for _ in range(10): 109 | transformed = nn.functional.gumbel_softmax(logits, tau=tau, hard=hard, eps=eps, dim=dim) 110 | if not torch.isnan(transformed).any(): 111 | return transformed 112 | 113 | raise ValueError('gumbel_softmax returning NaN.') 114 | 115 | def _apply_activate(self, data): 116 | """Apply proper activation function to the output of the generator.""" 117 | data_t = [] 118 | st = 0 119 | for column_info in self._transformer.output_info_list: 120 | for span_info in column_info: 121 | if span_info.activation_fn == 'tanh': 122 | ed = st + span_info.dim 123 | data_t.append(torch.tanh(data[:, st:ed])) 124 | st = ed 125 | elif span_info.activation_fn == 'softmax': 126 | ed = st + span_info.dim 127 | transformed = self._gumbel_softmax(data[:, st:ed], tau=0.2) 128 | data_t.append(transformed) 129 | st = ed 130 | else: 131 | raise ValueError(f'Unexpected activation function {span_info.activation_fn}.') 132 | 133 | return torch.cat(data_t, dim=1) 134 | 135 | def _cond_loss(self, data, c, m): 136 | """Compute the cross entropy loss on the fixed discrete column.""" 137 | loss = [] 138 | st = 0 139 | st_c = 0 140 | for column_info in self._transformer.output_info_list: 141 | for span_info in column_info: 142 | if len(column_info) != 1 or span_info.activation_fn != 'softmax': 143 | # not discrete column 144 | st += span_info.dim 145 | else: 146 | ed = st + span_info.dim 147 | ed_c = st_c + span_info.dim 148 | tmp = nn.functional.cross_entropy( 149 | data[:, st:ed], 150 | torch.argmax(c[:, st_c:ed_c], dim=1), 151 | reduction='none' 152 | ) 153 | loss.append(tmp) 154 | st = ed 155 | st_c = ed_c 156 | 157 | loss = torch.stack(loss, dim=1) # noqa: PD013 158 | 159 | return (loss * m).sum() / data.size()[0] 160 | 161 | def _validate_discrete_columns(self, train_data, discrete_columns): 162 | """Check whether ``discrete_columns`` exists in ``train_data``. 163 | 164 | Args: 165 | train_data (numpy.ndarray or pandas.DataFrame): 166 | Training Data. It must be a 2-dimensional numpy array or a pandas.DataFrame. 167 | discrete_columns (list-like): 168 | List of discrete columns to be used to generate the Conditional 169 | Vector. If ``train_data`` is a Numpy array, this list should 170 | contain the integer indices of the columns. Otherwise, if it is 171 | a ``pandas.DataFrame``, this list should contain the column names. 172 | """ 173 | if isinstance(train_data, pd.DataFrame): 174 | invalid_columns = set(discrete_columns) - set(train_data.columns) 175 | elif isinstance(train_data, np.ndarray): 176 | invalid_columns = [] 177 | for column in discrete_columns: 178 | if column < 0 or column >= train_data.shape[1]: 179 | invalid_columns.append(column) 180 | else: 181 | raise TypeError('``train_data`` should be either pd.DataFrame or np.array.') 182 | 183 | if invalid_columns: 184 | raise ValueError(f'Invalid columns found: {invalid_columns}') 185 | 186 | def _genrator_loss(self, output, target): 187 | MSE = self.mse(output, target) 188 | output_normalized = F.softmax(output, dim=1) 189 | target_normalized = F.softmax(target, dim=1) 190 | # KLD = torch.sum(target * (torch.log(target) - torch.log(output))) 191 | KLD = torch.sum( 192 | target_normalized * (torch.log(target_normalized + 1e-10) - torch.log(output_normalized + 1e-10))) 193 | 194 | total_loss = MSE + self.beta * KLD 195 | return total_loss 196 | 197 | @random_state 198 | def fit(self, train_data, discrete_columns=(), label='label'): 199 | """Fit the CTGAN Synthesizer models to the training data. 200 | 201 | Args: 202 | train_data (numpy.ndarray or pandas.DataFrame): 203 | Training Data. It must be a 2-dimensional numpy array or a pandas.DataFrame. 204 | discrete_columns (list-like): 205 | List of discrete columns to be used to generate the Conditional 206 | Vector. If ``train_data`` is a Numpy array, this list should 207 | contain the integer indices of the columns. Otherwise, if it is 208 | a ``pandas.DataFrame``, this list should contain the column names. 209 | """ 210 | self._validate_discrete_columns(train_data, discrete_columns) 211 | 212 | # Classifier features and embedding layers 213 | num_feature_no, emb_dims, output_sizes = embedding_dim.cal_dim(train_data, discrete_columns, label) 214 | 215 | train_data = self._transformer.transform(train_data) 216 | 217 | self._data_sampler = DataSampler( 218 | train_data, 219 | self._transformer.output_info_list, 220 | self._log_frequency) 221 | 222 | self._embedding_dim = self._data_dim 223 | 224 | self._generator = Generator( 225 | self._embedding_dim + self._data_sampler.dim_cond_vec(), 226 | self._generator_dim, 227 | self._data_dim 228 | ).to(self._device) 229 | 230 | self._classifier = ClassifierModel(emb_dims, num_feature_no, output_sizes) 231 | self._classifier_data_handler = ClassifierDataTransformer(discrete_columns, label) 232 | 233 | # Use BCEWithLogitsLoss for binary classification 234 | # For multi-class classification, use CrossEntropyLoss instead: 235 | # loss_function = nn.CrossEntropyLoss() 236 | # self.bce_loss = nn.BCEWithLogitsLoss() 237 | optimizerC = torch.optim.Adam(self._classifier.parameters(), lr=0.001) 238 | 239 | discriminator = Discriminator( 240 | self._data_dim + self._data_sampler.dim_cond_vec(), 241 | self._discriminator_dim, 242 | pac=self.pac 243 | ).to(self._device) 244 | 245 | optimizerG = optim.Adam( 246 | self._generator.parameters(), lr=self._generator_lr, betas=(0.5, 0.9), 247 | weight_decay=self._generator_decay 248 | ) 249 | 250 | optimizerD = optim.Adam( 251 | discriminator.parameters(), lr=self._discriminator_lr, 252 | betas=(0.5, 0.9), weight_decay=self._discriminator_decay 253 | ) 254 | 255 | self.criterion = nn.MSELoss() 256 | 257 | mean = torch.zeros(self._batch_size, self._embedding_dim, device=self._device) 258 | std = mean + 1 259 | 260 | steps_per_epoch = max(len(train_data) // self._batch_size, 1) 261 | 262 | for i in range(self._epochs): 263 | running_loss_d = 0. 264 | running_loss_g = 0. 265 | running_loss_c = 0. 266 | running_loss_g_sol = 0. 267 | for id_ in range(steps_per_epoch): 268 | running_loss_d_i = 0. 269 | 270 | for n in range(self._discriminator_steps): 271 | if self._noise_generator is None: 272 | fakez = torch.normal(mean=mean, std=std) 273 | else: 274 | fakez = self._noise_generator.forward(n_samples=self._batch_size).to(self._device) 275 | new_min = -3 276 | new_max = 3 277 | fakez = (fakez - fakez.min()) * (new_max - new_min) / (fakez.max() - fakez.min()) + new_min 278 | 279 | condvec = self._data_sampler.sample_condvec(self._batch_size) 280 | if condvec is None: 281 | c1, m1, col, opt = None, None, None, None 282 | real = self._data_sampler.sample_data(self._batch_size, col, opt) 283 | else: 284 | c1, m1, col, opt = condvec 285 | c1 = torch.from_numpy(c1).to(self._device) 286 | 287 | # number of category 288 | m1 = torch.from_numpy(m1).to(self._device) 289 | fakez = torch.cat([fakez, c1], dim=1) 290 | 291 | perm = np.arange(self._batch_size) 292 | np.random.shuffle(perm) 293 | real = self._data_sampler.sample_data( 294 | self._batch_size, col[perm], opt[perm]) 295 | 296 | c2 = c1[perm] 297 | 298 | fake = self._generator(fakez) 299 | fakeact = self._apply_activate(fake) 300 | 301 | real = torch.from_numpy(real.astype('float32')).to(self._device) 302 | 303 | if c1 is not None: 304 | fake_cat = torch.cat([fakeact, c1], dim=1) 305 | real_cat = torch.cat([real, c2], dim=1) 306 | else: 307 | real_cat = real 308 | fake_cat = fakeact 309 | 310 | # classifier_data = self._classifier_data_handler(self._transformer.inverse_transform(real_cat.detach().cpu().numpy())) 311 | # for x_cat_batch, x_num_batch, y_batch in classifier_data: 312 | # optimizerC.zero_grad(set_to_none=False) 313 | # outputs_c = self._classifier(x_cat_batch, x_num_batch) 314 | # loss = self.bce_loss(outputs_c, y_batch) 315 | # loss.backward() 316 | # optimizerC.step() 317 | # total_loss += loss.item() 318 | 319 | y_fake = discriminator(fake_cat) 320 | y_real = discriminator(real_cat) 321 | 322 | pen = discriminator.calc_gradient_penalty( 323 | real_cat, fake_cat, self._device, self.pac) 324 | loss_d = -(torch.mean(y_real) - torch.mean(y_fake)) 325 | running_loss_d_i += abs((torch.mean(y_fake) - torch.mean(y_real)).item()) 326 | 327 | optimizerD.zero_grad(set_to_none=False) 328 | pen.backward(retain_graph=True) 329 | loss_d.backward() 330 | optimizerD.step() 331 | 332 | classifier_data = self._classifier_data_handler( 333 | self._transformer.inverse_transform(real_cat.detach().cpu().numpy())) 334 | for x_cat_batch, x_num_batch, y_batch in classifier_data: 335 | optimizerC.zero_grad(set_to_none=False) 336 | outputs_c = self._classifier(x_cat_batch, x_num_batch) 337 | # loss_c = self.bce_loss(outputs_c, y_batch) 338 | losses_c = [F.cross_entropy(out, target) for out, target in 339 | zip(outputs_c[0], y_batch.squeeze(1).long())] 340 | loss_c = torch.mean(torch.stack(losses_c)) 341 | # loss_c.backward() 342 | # optimizerC.step() 343 | running_loss_c += loss_c.item() 344 | 345 | running_loss_d_i /= self._discriminator_steps 346 | running_loss_d += running_loss_d_i 347 | 348 | if self._noise_generator is None: 349 | fakez = torch.normal(mean=mean, std=std) 350 | else: 351 | fakez = self._noise_generator.forward(n_samples=self._batch_size).to(self._device) 352 | new_min = -3 353 | new_max = 3 354 | fakez = (fakez - fakez.min()) * (new_max - new_min) / (fakez.max() - fakez.min()) + new_min 355 | 356 | condvec = self._data_sampler.sample_condvec(self._batch_size) 357 | 358 | if condvec is None: 359 | c1, m1, col, opt = None, None, None, None 360 | else: 361 | c1, m1, col, opt = condvec 362 | c1 = torch.from_numpy(c1).to(self._device) 363 | m1 = torch.from_numpy(m1).to(self._device) 364 | fakez = torch.cat([fakez, c1], dim=1) 365 | 366 | fake = self._generator(fakez) 367 | fakeact = self._apply_activate(fake) 368 | 369 | if c1 is not None: 370 | y_fake = discriminator(torch.cat([fakeact, c1], dim=1)) 371 | else: 372 | y_fake = discriminator(fakeact) 373 | 374 | if condvec is None: 375 | cross_entropy = 0 376 | else: 377 | cross_entropy = self._cond_loss(fake, c1, m1) 378 | loss_g = -torch.mean(y_fake) + cross_entropy + torch.tensor(loss_c.item(), device=self._device, 379 | requires_grad=True) 380 | running_loss_g += abs((-torch.mean(y_fake) + cross_entropy).item()) 381 | running_loss_g_sol += abs(torch.mean(y_fake).item()) 382 | loss_c.backward() 383 | optimizerC.step() 384 | 385 | optimizerG.zero_grad(set_to_none=False) 386 | loss_g.backward() 387 | optimizerG.step() 388 | 389 | running_loss_g /= steps_per_epoch 390 | running_loss_c /= steps_per_epoch 391 | running_loss_g_sol /= steps_per_epoch 392 | running_loss_d /= steps_per_epoch 393 | if self._verbose: 394 | print(f'Epoch {i + 1}, Loss G: {loss_g.detach().cpu(): .4f},' 395 | f'Loss D: {loss_d.detach().cpu(): .4f}, Running Loss D: {running_loss_d: .4f}', 396 | f'Running Loss G: {running_loss_g: .4f}, Running Loss G C: {running_loss_g_sol: .4f}', 397 | f'Running Loss C: {running_loss_c: .4f}', f'Time: {datetime.now()}', 398 | flush=True) 399 | if self.is_wandb: 400 | wandb.log({"Generator_loss": loss_g.detach().cpu(), "Discriminator_loss": loss_d.detach().cpu(), 401 | "Running_Discriminator_loss": running_loss_d, "Running_Generator_loss": running_loss_g, 402 | "Running_Generator_loss_mae": running_loss_g_sol, "Running_Classifier_loss": running_loss_c}) 403 | 404 | self.df_result.loc[len(self.df_result.index)] = [i + 1, loss_g.item(), loss_d.item(), running_loss_d, 405 | running_loss_g, datetime.now()] 406 | 407 | # if (i + 1) % self.save_interval == 0: 408 | # torch.save(self._generator.state_dict(), os.path.join(self.save_directory, 409 | # f"generator_checkpoint_{i + 1}_{self.dataset}_{datetime.now().date().strftime('%m%d%Y')}_{self._device}.pth")) 410 | 411 | if self.is_wandb: 412 | wandb.finish() 413 | 414 | if self.save_directory: 415 | # Save the final trained model 416 | torch.save(self._generator.state_dict(), os.path.join(self.save_directory, 417 | f"generator_{self.dataset}_{datetime.now().date().strftime('%m%d%Y')}_{self._device}.pth")) 418 | # Save training result 419 | self.df_result.to_csv(os.path.join(self.save_directory, 420 | f"gan_logs_{self.dataset}_{datetime.now().date().strftime('%m%d%Y')}.csv"), 421 | index=False) 422 | 423 | @random_state 424 | def sample(self, n, condition_column=None, condition_value=None): 425 | """Sample data similar to the training data. 426 | 427 | Choosing a condition_column and condition_value will increase the probability of the 428 | discrete condition_value happening in the condition_column. 429 | 430 | Args: 431 | n (int): 432 | Number of rows to sample. 433 | condition_column (string): 434 | Name of a discrete column. 435 | condition_value (string): 436 | Name of the category in the condition_column which we wish to increase the 437 | probability of happening. 438 | 439 | Returns: 440 | numpy.ndarray or pandas.DataFrame 441 | """ 442 | if condition_column is not None and condition_value is not None: 443 | condition_info = self._transformer.convert_column_name_value_to_id( 444 | condition_column, condition_value) 445 | global_condition_vec = self._data_sampler.generate_cond_from_condition_column_info( 446 | condition_info, self._batch_size) 447 | else: 448 | global_condition_vec = None 449 | 450 | steps = n // self._batch_size + 1 451 | data = [] 452 | for i in range(steps): 453 | mean = torch.zeros(self._batch_size, self._embedding_dim) 454 | std = mean + 1 455 | # fakez = torch.normal(mean=mean, std=std).to(self._device) 456 | 457 | if self._noise_generator is None: 458 | fakez = torch.normal(mean=mean, std=std) 459 | else: 460 | fakez = self._noise_generator.forward(n_samples=self._batch_size).to(self._device) 461 | 462 | if global_condition_vec is not None: 463 | condvec = global_condition_vec.copy() 464 | else: 465 | condvec = self._data_sampler.sample_original_condvec(self._batch_size) 466 | 467 | if condvec is None: 468 | pass 469 | else: 470 | c1 = condvec 471 | c1 = torch.from_numpy(c1).to(self._device) 472 | fakez = torch.cat([fakez, c1], dim=1) 473 | 474 | fake = self._generator(fakez) 475 | fakeact = self._apply_activate(fake) 476 | data.append(fakeact.detach().cpu().numpy()) 477 | 478 | data = np.concatenate(data, axis=0) 479 | data = data[:n] 480 | 481 | return self._transformer.inverse_transform(data) 482 | 483 | def set_device(self, device): 484 | """Set the `device` to be used ('GPU' or 'CPU).""" 485 | self._device = device 486 | if self._generator is not None: 487 | self._generator.to(self._device) 488 | -------------------------------------------------------------------------------- /commands_sampler1.txt: -------------------------------------------------------------------------------- 1 | python sampler.py --train_type gan --data_path dataset_test/adult/adult.csv --metadata_path dataset_test/adult/meta_data.json --dataset_name adult --pretrained_cae cae_adult_adult_03012024_cuda --pretrained_generator generator_adult_03022024_cuda --samples 100 2 | python sampler.py --train_type gan --data_path dataset_test/AirQuality/AirQuality_final.csv --metadata_path dataset_test/AirQuality/meta_data.json --dataset_name AirQuality --pretrained_cae cae_AirQuality_AirQuality_03012024_cuda --pretrained_generator generator_AirQuality_03022024_cuda --samples 100 3 | python sampler.py --train_type gan --data_path dataset_test/ApartmentRent/apartments_for_rent_final.csv --metadata_path dataset_test/ApartmentRent/meta_data.json --dataset_name ApartmentRent --pretrained_cae cae_ApartmentRent_ApartmentRent_03012024_cuda --pretrained_generator generator_ApartmentRent_03032024_cuda --samples 100 4 | python sampler.py --train_type gan --data_path dataset_test/BankMarketing/bank-final.csv --metadata_path dataset_test/BankMarketing/meta_data.json --dataset_name BankMarketing --pretrained_cae cae_BankMarketing_BankMarketing_03012024_cuda --pretrained_generator generator_BankMarketing_03022024_cuda --samples 100 5 | python sampler.py --train_type gan --data_path dataset_test/BeijingPM/PRSA_data_final.csv --metadata_path dataset_test/BeijingPM/meta_data.json --dataset_name BeijingPM --pretrained_cae cae_BeijingPM_BeijingPM_03012024_cuda --pretrained_generator generator_BeijingPM_03022024_cuda --samples 100 6 | python sampler.py --train_type gan --data_path dataset_test/BikeSharing/final.csv --metadata_path dataset_test/BikeSharing/meta_data.json --dataset_name BikeSharing --pretrained_cae cae_BikeSharing_BikeSharing_03012024_cuda --pretrained_generator generator_BikeSharing_03022024_cuda --samples 100 7 | python sampler.py --train_type gan --data_path dataset_test/MetroPTDataset/MetroPT3_final.csv --metadata_path dataset_test/MetroPTDataset/meta_data.json --dataset_name MetroPT --pretrained_cae cae_MetroPT_MetroPT_03022024_cuda --pretrained_generator generator_MetroPT_03052024_cuda --samples 100 8 | python sampler.py --train_type gan --data_path dataset_test/MetroInterstateTraffic/Metro_Interstate_Traffic_Volume_Final.csv --metadata_path dataset_test/MetroInterstateTraffic/meta_data.json --dataset_name MetroTraffic --pretrained_cae cae_MetroTraffic_MetroTraffic_03012024_cuda --pretrained_generator generator_MetroTraffic_03022024_cuda --samples 100 9 | python sampler.py --train_type gan --data_path dataset_test/HouseholdPowerConsumption/household_power_consumption_final.csv --metadata_path dataset_test/HouseholdPowerConsumption/meta_data.json --dataset_name PowerConsumption --pretrained_cae cae_PowerConsumption_PowerConsumption_03042024_cuda --pretrained_generator generator_PowerConsumption_03052024_cuda --samples 100 10 | python sampler.py --train_type cae_gan --data_path dataset_test/adult/adult.csv --metadata_path dataset_test/adult/meta_data.json --dataset_name adult --pretrained_cae cae_adult_adult_03012024_cuda --pretrained_generator generator_adult_03042024_cuda --samples 100 11 | python sampler.py --train_type cae_gan --data_path dataset_test/AirQuality/AirQuality_final.csv --metadata_path dataset_test/AirQuality/meta_data.json --dataset_name AirQuality --pretrained_cae cae_AirQuality_AirQuality_03012024_cuda --pretrained_generator generator_AirQuality_03032024_cuda --samples 100 12 | python sampler.py --train_type cae_gan --data_path dataset_test/ApartmentRent/apartments_for_rent_final.csv --metadata_path dataset_test/ApartmentRent/meta_data.json --dataset_name ApartmentRent --pretrained_cae cae_ApartmentRent_ApartmentRent_03012024_cuda --pretrained_generator generator_ApartmentRent_03042024_cuda --samples 100 13 | python sampler.py --train_type cae_gan --data_path dataset_test/BankMarketing/bank-final.csv --metadata_path dataset_test/BankMarketing/meta_data.json --dataset_name BankMarketing --pretrained_cae cae_BankMarketing_BankMarketing_03012024_cuda --pretrained_generator generator_BankMarketing_03042024_cuda --samples 100 14 | python sampler.py --train_type cae_gan --data_path dataset_test/BeijingPM/PRSA_data_final.csv --metadata_path dataset_test/BeijingPM/meta_data.json --dataset_name BeijingPM --pretrained_cae cae_BeijingPM_BeijingPM_03012024_cuda --pretrained_generator generator_BeijingPM_03042024_cuda --samples 100 15 | python sampler.py --train_type cae_gan --data_path dataset_test/BikeSharing/final.csv --metadata_path dataset_test/BikeSharing/meta_data.json --dataset_name BikeSharing --pretrained_cae cae_BikeSharing_BikeSharing_03012024_cuda --pretrained_generator generator_BikeSharing_03042024_cuda --samples 100 16 | python sampler.py --train_type cae_gan --data_path dataset_test/MetroPTDataset/MetroPT3_final.csv --metadata_path dataset_test/MetroPTDataset/meta_data.json --dataset_name MetroPT --pretrained_cae cae_MetroPT_MetroPT_03022024_cuda --pretrained_generator generator_MetroPT_03062024_cuda --samples 100 17 | python sampler.py --train_type cae_gan --data_path dataset_test/MetroInterstateTraffic/Metro_Interstate_Traffic_Volume_Final.csv --metadata_path dataset_test/MetroInterstateTraffic/meta_data.json --dataset_name MetroTraffic --pretrained_cae cae_MetroTraffic_MetroTraffic_03012024_cuda --pretrained_generator generator_MetroTraffic_03042024_cuda --samples 100 18 | python sampler.py --train_type cae_gan --data_path dataset_test/HouseholdPowerConsumption/household_power_consumption_final.csv --metadata_path dataset_test/HouseholdPowerConsumption/meta_data.json --dataset_name PowerConsumption --pretrained_cae cae_PowerConsumption_PowerConsumption_03042024_cuda --pretrained_generator generator_PowerConsumption_03062024_cuda --samples 100 19 | python sampler.py --train_type gan --data_path dataset_test/adult/adult.csv --metadata_path dataset_test/adult/meta_data.json --dataset_name adult --pretrained_cae cae_adult_adult_03012024_cuda --pretrained_generator generator_adult_03022024_cuda --samples 500 20 | python sampler.py --train_type gan --data_path dataset_test/AirQuality/AirQuality_final.csv --metadata_path dataset_test/AirQuality/meta_data.json --dataset_name AirQuality --pretrained_cae cae_AirQuality_AirQuality_03012024_cuda --pretrained_generator generator_AirQuality_03022024_cuda --samples 500 21 | python sampler.py --train_type gan --data_path dataset_test/ApartmentRent/apartments_for_rent_final.csv --metadata_path dataset_test/ApartmentRent/meta_data.json --dataset_name ApartmentRent --pretrained_cae cae_ApartmentRent_ApartmentRent_03012024_cuda --pretrained_generator generator_ApartmentRent_03032024_cuda --samples 500 22 | python sampler.py --train_type gan --data_path dataset_test/BankMarketing/bank-final.csv --metadata_path dataset_test/BankMarketing/meta_data.json --dataset_name BankMarketing --pretrained_cae cae_BankMarketing_BankMarketing_03012024_cuda --pretrained_generator generator_BankMarketing_03022024_cuda --samples 500 23 | python sampler.py --train_type gan --data_path dataset_test/BeijingPM/PRSA_data_final.csv --metadata_path dataset_test/BeijingPM/meta_data.json --dataset_name BeijingPM --pretrained_cae cae_BeijingPM_BeijingPM_03012024_cuda --pretrained_generator generator_BeijingPM_03022024_cuda --samples 500 24 | python sampler.py --train_type gan --data_path dataset_test/BikeSharing/final.csv --metadata_path dataset_test/BikeSharing/meta_data.json --dataset_name BikeSharing --pretrained_cae cae_BikeSharing_BikeSharing_03012024_cuda --pretrained_generator generator_BikeSharing_03022024_cuda --samples 500 25 | python sampler.py --train_type gan --data_path dataset_test/MetroPTDataset/MetroPT3_final.csv --metadata_path dataset_test/MetroPTDataset/meta_data.json --dataset_name MetroPT --pretrained_cae cae_MetroPT_MetroPT_03022024_cuda --pretrained_generator generator_MetroPT_03052024_cuda --samples 500 26 | python sampler.py --train_type gan --data_path dataset_test/MetroInterstateTraffic/Metro_Interstate_Traffic_Volume_Final.csv --metadata_path dataset_test/MetroInterstateTraffic/meta_data.json --dataset_name MetroTraffic --pretrained_cae cae_MetroTraffic_MetroTraffic_03012024_cuda --pretrained_generator generator_MetroTraffic_03022024_cuda --samples 500 27 | python sampler.py --train_type gan --data_path dataset_test/HouseholdPowerConsumption/household_power_consumption_final.csv --metadata_path dataset_test/HouseholdPowerConsumption/meta_data.json --dataset_name PowerConsumption --pretrained_cae cae_PowerConsumption_PowerConsumption_03042024_cuda --pretrained_generator generator_PowerConsumption_03052024_cuda --samples 500 28 | python sampler.py --train_type cae_gan --data_path dataset_test/adult/adult.csv --metadata_path dataset_test/adult/meta_data.json --dataset_name adult --pretrained_cae cae_adult_adult_03012024_cuda --pretrained_generator generator_adult_03042024_cuda --samples 500 29 | python sampler.py --train_type cae_gan --data_path dataset_test/AirQuality/AirQuality_final.csv --metadata_path dataset_test/AirQuality/meta_data.json --dataset_name AirQuality --pretrained_cae cae_AirQuality_AirQuality_03012024_cuda --pretrained_generator generator_AirQuality_03032024_cuda --samples 500 30 | python sampler.py --train_type cae_gan --data_path dataset_test/ApartmentRent/apartments_for_rent_final.csv --metadata_path dataset_test/ApartmentRent/meta_data.json --dataset_name ApartmentRent --pretrained_cae cae_ApartmentRent_ApartmentRent_03012024_cuda --pretrained_generator generator_ApartmentRent_03042024_cuda --samples 500 31 | python sampler.py --train_type cae_gan --data_path dataset_test/BankMarketing/bank-final.csv --metadata_path dataset_test/BankMarketing/meta_data.json --dataset_name BankMarketing --pretrained_cae cae_BankMarketing_BankMarketing_03012024_cuda --pretrained_generator generator_BankMarketing_03042024_cuda --samples 500 32 | python sampler.py --train_type cae_gan --data_path dataset_test/BeijingPM/PRSA_data_final.csv --metadata_path dataset_test/BeijingPM/meta_data.json --dataset_name BeijingPM --pretrained_cae cae_BeijingPM_BeijingPM_03012024_cuda --pretrained_generator generator_BeijingPM_03042024_cuda --samples 500 33 | python sampler.py --train_type cae_gan --data_path dataset_test/BikeSharing/final.csv --metadata_path dataset_test/BikeSharing/meta_data.json --dataset_name BikeSharing --pretrained_cae cae_BikeSharing_BikeSharing_03012024_cuda --pretrained_generator generator_BikeSharing_03042024_cuda --samples 500 34 | python sampler.py --train_type cae_gan --data_path dataset_test/MetroPTDataset/MetroPT3_final.csv --metadata_path dataset_test/MetroPTDataset/meta_data.json --dataset_name MetroPT --pretrained_cae cae_MetroPT_MetroPT_03022024_cuda --pretrained_generator generator_MetroPT_03062024_cuda --samples 500 35 | python sampler.py --train_type cae_gan --data_path dataset_test/MetroInterstateTraffic/Metro_Interstate_Traffic_Volume_Final.csv --metadata_path dataset_test/MetroInterstateTraffic/meta_data.json --dataset_name MetroTraffic --pretrained_cae cae_MetroTraffic_MetroTraffic_03012024_cuda --pretrained_generator generator_MetroTraffic_03042024_cuda --samples 500 36 | python sampler.py --train_type cae_gan --data_path dataset_test/HouseholdPowerConsumption/household_power_consumption_final.csv --metadata_path dataset_test/HouseholdPowerConsumption/meta_data.json --dataset_name PowerConsumption --pretrained_cae cae_PowerConsumption_PowerConsumption_03042024_cuda --pretrained_generator generator_PowerConsumption_03062024_cuda --samples 500 37 | python sampler.py --train_type gan --data_path dataset_test/adult/adult.csv --metadata_path dataset_test/adult/meta_data.json --dataset_name adult --pretrained_cae cae_adult_adult_03012024_cuda --pretrained_generator generator_adult_03022024_cuda --samples 1000 38 | python sampler.py --train_type gan --data_path dataset_test/AirQuality/AirQuality_final.csv --metadata_path dataset_test/AirQuality/meta_data.json --dataset_name AirQuality --pretrained_cae cae_AirQuality_AirQuality_03012024_cuda --pretrained_generator generator_AirQuality_03022024_cuda --samples 1000 39 | python sampler.py --train_type gan --data_path dataset_test/ApartmentRent/apartments_for_rent_final.csv --metadata_path dataset_test/ApartmentRent/meta_data.json --dataset_name ApartmentRent --pretrained_cae cae_ApartmentRent_ApartmentRent_03012024_cuda --pretrained_generator generator_ApartmentRent_03032024_cuda --samples 1000 40 | python sampler.py --train_type gan --data_path dataset_test/BankMarketing/bank-final.csv --metadata_path dataset_test/BankMarketing/meta_data.json --dataset_name BankMarketing --pretrained_cae cae_BankMarketing_BankMarketing_03012024_cuda --pretrained_generator generator_BankMarketing_03022024_cuda --samples 1000 41 | python sampler.py --train_type gan --data_path dataset_test/BeijingPM/PRSA_data_final.csv --metadata_path dataset_test/BeijingPM/meta_data.json --dataset_name BeijingPM --pretrained_cae cae_BeijingPM_BeijingPM_03012024_cuda --pretrained_generator generator_BeijingPM_03022024_cuda --samples 1000 42 | python sampler.py --train_type gan --data_path dataset_test/BikeSharing/final.csv --metadata_path dataset_test/BikeSharing/meta_data.json --dataset_name BikeSharing --pretrained_cae cae_BikeSharing_BikeSharing_03012024_cuda --pretrained_generator generator_BikeSharing_03022024_cuda --samples 1000 43 | python sampler.py --train_type gan --data_path dataset_test/MetroPTDataset/MetroPT3_final.csv --metadata_path dataset_test/MetroPTDataset/meta_data.json --dataset_name MetroPT --pretrained_cae cae_MetroPT_MetroPT_03022024_cuda --pretrained_generator generator_MetroPT_03052024_cuda --samples 1000 44 | python sampler.py --train_type gan --data_path dataset_test/MetroInterstateTraffic/Metro_Interstate_Traffic_Volume_Final.csv --metadata_path dataset_test/MetroInterstateTraffic/meta_data.json --dataset_name MetroTraffic --pretrained_cae cae_MetroTraffic_MetroTraffic_03012024_cuda --pretrained_generator generator_MetroTraffic_03022024_cuda --samples 1000 45 | python sampler.py --train_type gan --data_path dataset_test/HouseholdPowerConsumption/household_power_consumption_final.csv --metadata_path dataset_test/HouseholdPowerConsumption/meta_data.json --dataset_name PowerConsumption --pretrained_cae cae_PowerConsumption_PowerConsumption_03042024_cuda --pretrained_generator generator_PowerConsumption_03052024_cuda --samples 1000 46 | python sampler.py --train_type cae_gan --data_path dataset_test/adult/adult.csv --metadata_path dataset_test/adult/meta_data.json --dataset_name adult --pretrained_cae cae_adult_adult_03012024_cuda --pretrained_generator generator_adult_03042024_cuda --samples 1000 47 | python sampler.py --train_type cae_gan --data_path dataset_test/AirQuality/AirQuality_final.csv --metadata_path dataset_test/AirQuality/meta_data.json --dataset_name AirQuality --pretrained_cae cae_AirQuality_AirQuality_03012024_cuda --pretrained_generator generator_AirQuality_03032024_cuda --samples 1000 48 | python sampler.py --train_type cae_gan --data_path dataset_test/ApartmentRent/apartments_for_rent_final.csv --metadata_path dataset_test/ApartmentRent/meta_data.json --dataset_name ApartmentRent --pretrained_cae cae_ApartmentRent_ApartmentRent_03012024_cuda --pretrained_generator generator_ApartmentRent_03042024_cuda --samples 1000 49 | python sampler.py --train_type cae_gan --data_path dataset_test/BankMarketing/bank-final.csv --metadata_path dataset_test/BankMarketing/meta_data.json --dataset_name BankMarketing --pretrained_cae cae_BankMarketing_BankMarketing_03012024_cuda --pretrained_generator generator_BankMarketing_03042024_cuda --samples 1000 50 | python sampler.py --train_type cae_gan --data_path dataset_test/BeijingPM/PRSA_data_final.csv --metadata_path dataset_test/BeijingPM/meta_data.json --dataset_name BeijingPM --pretrained_cae cae_BeijingPM_BeijingPM_03012024_cuda --pretrained_generator generator_BeijingPM_03042024_cuda --samples 1000 51 | python sampler.py --train_type cae_gan --data_path dataset_test/BikeSharing/final.csv --metadata_path dataset_test/BikeSharing/meta_data.json --dataset_name BikeSharing --pretrained_cae cae_BikeSharing_BikeSharing_03012024_cuda --pretrained_generator generator_BikeSharing_03042024_cuda --samples 1000 52 | python sampler.py --train_type cae_gan --data_path dataset_test/MetroPTDataset/MetroPT3_final.csv --metadata_path dataset_test/MetroPTDataset/meta_data.json --dataset_name MetroPT --pretrained_cae cae_MetroPT_MetroPT_03022024_cuda --pretrained_generator generator_MetroPT_03062024_cuda --samples 1000 53 | python sampler.py --train_type cae_gan --data_path dataset_test/MetroInterstateTraffic/Metro_Interstate_Traffic_Volume_Final.csv --metadata_path dataset_test/MetroInterstateTraffic/meta_data.json --dataset_name MetroTraffic --pretrained_cae cae_MetroTraffic_MetroTraffic_03012024_cuda --pretrained_generator generator_MetroTraffic_03042024_cuda --samples 1000 54 | python sampler.py --train_type cae_gan --data_path dataset_test/HouseholdPowerConsumption/household_power_consumption_final.csv --metadata_path dataset_test/HouseholdPowerConsumption/meta_data.json --dataset_name PowerConsumption --pretrained_cae cae_PowerConsumption_PowerConsumption_03042024_cuda --pretrained_generator generator_PowerConsumption_03062024_cuda --samples 1000 55 | python sampler.py --train_type gan --data_path dataset_test/adult/adult.csv --metadata_path dataset_test/adult/meta_data.json --dataset_name adult --pretrained_cae cae_adult_adult_03012024_cuda --pretrained_generator generator_adult_03022024_cuda --samples 10000 56 | python sampler.py --train_type gan --data_path dataset_test/AirQuality/AirQuality_final.csv --metadata_path dataset_test/AirQuality/meta_data.json --dataset_name AirQuality --pretrained_cae cae_AirQuality_AirQuality_03012024_cuda --pretrained_generator generator_AirQuality_03022024_cuda --samples 10000 57 | python sampler.py --train_type gan --data_path dataset_test/ApartmentRent/apartments_for_rent_final.csv --metadata_path dataset_test/ApartmentRent/meta_data.json --dataset_name ApartmentRent --pretrained_cae cae_ApartmentRent_ApartmentRent_03012024_cuda --pretrained_generator generator_ApartmentRent_03032024_cuda --samples 10000 58 | python sampler.py --train_type gan --data_path dataset_test/BankMarketing/bank-final.csv --metadata_path dataset_test/BankMarketing/meta_data.json --dataset_name BankMarketing --pretrained_cae cae_BankMarketing_BankMarketing_03012024_cuda --pretrained_generator generator_BankMarketing_03022024_cuda --samples 10000 59 | python sampler.py --train_type gan --data_path dataset_test/BeijingPM/PRSA_data_final.csv --metadata_path dataset_test/BeijingPM/meta_data.json --dataset_name BeijingPM --pretrained_cae cae_BeijingPM_BeijingPM_03012024_cuda --pretrained_generator generator_BeijingPM_03022024_cuda --samples 10000 60 | python sampler.py --train_type gan --data_path dataset_test/BikeSharing/final.csv --metadata_path dataset_test/BikeSharing/meta_data.json --dataset_name BikeSharing --pretrained_cae cae_BikeSharing_BikeSharing_03012024_cuda --pretrained_generator generator_BikeSharing_03022024_cuda --samples 10000 61 | python sampler.py --train_type gan --data_path dataset_test/MetroPTDataset/MetroPT3_final.csv --metadata_path dataset_test/MetroPTDataset/meta_data.json --dataset_name MetroPT --pretrained_cae cae_MetroPT_MetroPT_03022024_cuda --pretrained_generator generator_MetroPT_03052024_cuda --samples 10000 62 | python sampler.py --train_type gan --data_path dataset_test/MetroInterstateTraffic/Metro_Interstate_Traffic_Volume_Final.csv --metadata_path dataset_test/MetroInterstateTraffic/meta_data.json --dataset_name MetroTraffic --pretrained_cae cae_MetroTraffic_MetroTraffic_03012024_cuda --pretrained_generator generator_MetroTraffic_03022024_cuda --samples 10000 63 | python sampler.py --train_type gan --data_path dataset_test/HouseholdPowerConsumption/household_power_consumption_final.csv --metadata_path dataset_test/HouseholdPowerConsumption/meta_data.json --dataset_name PowerConsumption --pretrained_cae cae_PowerConsumption_PowerConsumption_03042024_cuda --pretrained_generator generator_PowerConsumption_03052024_cuda --samples 10000 64 | python sampler.py --train_type cae_gan --data_path dataset_test/adult/adult.csv --metadata_path dataset_test/adult/meta_data.json --dataset_name adult --pretrained_cae cae_adult_adult_03012024_cuda --pretrained_generator generator_adult_03042024_cuda --samples 10000 65 | python sampler.py --train_type cae_gan --data_path dataset_test/AirQuality/AirQuality_final.csv --metadata_path dataset_test/AirQuality/meta_data.json --dataset_name AirQuality --pretrained_cae cae_AirQuality_AirQuality_03012024_cuda --pretrained_generator generator_AirQuality_03032024_cuda --samples 10000 66 | python sampler.py --train_type cae_gan --data_path dataset_test/ApartmentRent/apartments_for_rent_final.csv --metadata_path dataset_test/ApartmentRent/meta_data.json --dataset_name ApartmentRent --pretrained_cae cae_ApartmentRent_ApartmentRent_03012024_cuda --pretrained_generator generator_ApartmentRent_03042024_cuda --samples 10000 67 | python sampler.py --train_type cae_gan --data_path dataset_test/BankMarketing/bank-final.csv --metadata_path dataset_test/BankMarketing/meta_data.json --dataset_name BankMarketing --pretrained_cae cae_BankMarketing_BankMarketing_03012024_cuda --pretrained_generator generator_BankMarketing_03042024_cuda --samples 10000 68 | python sampler.py --train_type cae_gan --data_path dataset_test/BeijingPM/PRSA_data_final.csv --metadata_path dataset_test/BeijingPM/meta_data.json --dataset_name BeijingPM --pretrained_cae cae_BeijingPM_BeijingPM_03012024_cuda --pretrained_generator generator_BeijingPM_03042024_cuda --samples 10000 69 | python sampler.py --train_type cae_gan --data_path dataset_test/BikeSharing/final.csv --metadata_path dataset_test/BikeSharing/meta_data.json --dataset_name BikeSharing --pretrained_cae cae_BikeSharing_BikeSharing_03012024_cuda --pretrained_generator generator_BikeSharing_03042024_cuda --samples 10000 70 | python sampler.py --train_type cae_gan --data_path dataset_test/MetroPTDataset/MetroPT3_final.csv --metadata_path dataset_test/MetroPTDataset/meta_data.json --dataset_name MetroPT --pretrained_cae cae_MetroPT_MetroPT_03022024_cuda --pretrained_generator generator_MetroPT_03062024_cuda --samples 10000 71 | python sampler.py --train_type cae_gan --data_path dataset_test/MetroInterstateTraffic/Metro_Interstate_Traffic_Volume_Final.csv --metadata_path dataset_test/MetroInterstateTraffic/meta_data.json --dataset_name MetroTraffic --pretrained_cae cae_MetroTraffic_MetroTraffic_03012024_cuda --pretrained_generator generator_MetroTraffic_03042024_cuda --samples 10000 72 | python sampler.py --train_type cae_gan --data_path dataset_test/HouseholdPowerConsumption/household_power_consumption_final.csv --metadata_path dataset_test/HouseholdPowerConsumption/meta_data.json --dataset_name PowerConsumption --pretrained_cae cae_PowerConsumption_PowerConsumption_03042024_cuda --pretrained_generator generator_PowerConsumption_03062024_cuda --samples 10000 73 | python sampler.py --train_type gan --data_path dataset_test/adult/adult.csv --metadata_path dataset_test/adult/meta_data.json --dataset_name adult --pretrained_cae cae_adult_adult_03012024_cuda --pretrained_generator generator_adult_03022024_cuda --samples 20000 74 | python sampler.py --train_type gan --data_path dataset_test/AirQuality/AirQuality_final.csv --metadata_path dataset_test/AirQuality/meta_data.json --dataset_name AirQuality --pretrained_cae cae_AirQuality_AirQuality_03012024_cuda --pretrained_generator generator_AirQuality_03022024_cuda --samples 20000 75 | python sampler.py --train_type gan --data_path dataset_test/ApartmentRent/apartments_for_rent_final.csv --metadata_path dataset_test/ApartmentRent/meta_data.json --dataset_name ApartmentRent --pretrained_cae cae_ApartmentRent_ApartmentRent_03012024_cuda --pretrained_generator generator_ApartmentRent_03032024_cuda --samples 20000 76 | python sampler.py --train_type gan --data_path dataset_test/BankMarketing/bank-final.csv --metadata_path dataset_test/BankMarketing/meta_data.json --dataset_name BankMarketing --pretrained_cae cae_BankMarketing_BankMarketing_03012024_cuda --pretrained_generator generator_BankMarketing_03022024_cuda --samples 20000 77 | python sampler.py --train_type gan --data_path dataset_test/BeijingPM/PRSA_data_final.csv --metadata_path dataset_test/BeijingPM/meta_data.json --dataset_name BeijingPM --pretrained_cae cae_BeijingPM_BeijingPM_03012024_cuda --pretrained_generator generator_BeijingPM_03022024_cuda --samples 20000 78 | python sampler.py --train_type gan --data_path dataset_test/BikeSharing/final.csv --metadata_path dataset_test/BikeSharing/meta_data.json --dataset_name BikeSharing --pretrained_cae cae_BikeSharing_BikeSharing_03012024_cuda --pretrained_generator generator_BikeSharing_03022024_cuda --samples 20000 79 | python sampler.py --train_type gan --data_path dataset_test/MetroPTDataset/MetroPT3_final.csv --metadata_path dataset_test/MetroPTDataset/meta_data.json --dataset_name MetroPT --pretrained_cae cae_MetroPT_MetroPT_03022024_cuda --pretrained_generator generator_MetroPT_03052024_cuda --samples 20000 80 | python sampler.py --train_type gan --data_path dataset_test/MetroInterstateTraffic/Metro_Interstate_Traffic_Volume_Final.csv --metadata_path dataset_test/MetroInterstateTraffic/meta_data.json --dataset_name MetroTraffic --pretrained_cae cae_MetroTraffic_MetroTraffic_03012024_cuda --pretrained_generator generator_MetroTraffic_03022024_cuda --samples 20000 81 | python sampler.py --train_type gan --data_path dataset_test/HouseholdPowerConsumption/household_power_consumption_final.csv --metadata_path dataset_test/HouseholdPowerConsumption/meta_data.json --dataset_name PowerConsumption --pretrained_cae cae_PowerConsumption_PowerConsumption_03042024_cuda --pretrained_generator generator_PowerConsumption_03052024_cuda --samples 20000 82 | python sampler.py --train_type cae_gan --data_path dataset_test/adult/adult.csv --metadata_path dataset_test/adult/meta_data.json --dataset_name adult --pretrained_cae cae_adult_adult_03012024_cuda --pretrained_generator generator_adult_03042024_cuda --samples 20000 83 | python sampler.py --train_type cae_gan --data_path dataset_test/AirQuality/AirQuality_final.csv --metadata_path dataset_test/AirQuality/meta_data.json --dataset_name AirQuality --pretrained_cae cae_AirQuality_AirQuality_03012024_cuda --pretrained_generator generator_AirQuality_03032024_cuda --samples 20000 84 | python sampler.py --train_type cae_gan --data_path dataset_test/ApartmentRent/apartments_for_rent_final.csv --metadata_path dataset_test/ApartmentRent/meta_data.json --dataset_name ApartmentRent --pretrained_cae cae_ApartmentRent_ApartmentRent_03012024_cuda --pretrained_generator generator_ApartmentRent_03042024_cuda --samples 20000 85 | python sampler.py --train_type cae_gan --data_path dataset_test/BankMarketing/bank-final.csv --metadata_path dataset_test/BankMarketing/meta_data.json --dataset_name BankMarketing --pretrained_cae cae_BankMarketing_BankMarketing_03012024_cuda --pretrained_generator generator_BankMarketing_03042024_cuda --samples 20000 86 | python sampler.py --train_type cae_gan --data_path dataset_test/BeijingPM/PRSA_data_final.csv --metadata_path dataset_test/BeijingPM/meta_data.json --dataset_name BeijingPM --pretrained_cae cae_BeijingPM_BeijingPM_03012024_cuda --pretrained_generator generator_BeijingPM_03042024_cuda --samples 20000 87 | python sampler.py --train_type cae_gan --data_path dataset_test/BikeSharing/final.csv --metadata_path dataset_test/BikeSharing/meta_data.json --dataset_name BikeSharing --pretrained_cae cae_BikeSharing_BikeSharing_03012024_cuda --pretrained_generator generator_BikeSharing_03042024_cuda --samples 20000 88 | python sampler.py --train_type cae_gan --data_path dataset_test/MetroPTDataset/MetroPT3_final.csv --metadata_path dataset_test/MetroPTDataset/meta_data.json --dataset_name MetroPT --pretrained_cae cae_MetroPT_MetroPT_03022024_cuda --pretrained_generator generator_MetroPT_03062024_cuda --samples 20000 89 | python sampler.py --train_type cae_gan --data_path dataset_test/MetroInterstateTraffic/Metro_Interstate_Traffic_Volume_Final.csv --metadata_path dataset_test/MetroInterstateTraffic/meta_data.json --dataset_name MetroTraffic --pretrained_cae cae_MetroTraffic_MetroTraffic_03012024_cuda --pretrained_generator generator_MetroTraffic_03042024_cuda --samples 20000 90 | python sampler.py --train_type cae_gan --data_path dataset_test/HouseholdPowerConsumption/household_power_consumption_final.csv --metadata_path dataset_test/HouseholdPowerConsumption/meta_data.json --dataset_name PowerConsumption --pretrained_cae cae_PowerConsumption_PowerConsumption_03042024_cuda --pretrained_generator generator_PowerConsumption_03062024_cuda --samples 20000 91 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------