Skip to content

Commit

Permalink
feat(cgan): Jupyter Notebook conditional example.
Browse files Browse the repository at this point in the history
  • Loading branch information
fabclmnt committed Sep 14, 2020
1 parent f91c815 commit 7e7018d
Showing 1 changed file with 206 additions and 0 deletions.
206 changes: 206 additions & 0 deletions examples/cgan_example.py.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,206 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"source": [
"# The credit fraud dataset - Synthesizing the minority class\n",
"In this notebook it's presented a practical exercise of how to use the avilable library GANs to synthesize tabular data.\n",
"For the purpose of this exercise it has been used the Credit Fraud dataset from Kaggle, that you can find here:https: //www.kaggle.com/mlg-ulb/creditcardfraud"
],
"metadata": {
"collapsed": false
}
},
{
"cell_type": "code",
"execution_count": null,
"outputs": [],
"source": [
"import importlib\n",
"import sys \n",
"\n",
"import pandas as pd\n",
"import numpy as np\n",
"import sklearn.cluster as cluster\n",
"import matplotlib.pyplot as plt\n",
"\n",
"from models import CGAN\n",
"from preprocessing.credit_fraud import *\n",
"\n",
"model = CGAN"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": null,
"outputs": [],
"source": [
"#Read the original data and have it preprocessed\n",
"data = pd.read_csv('data/creditcard.csv', index_col=[0])"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": null,
"outputs": [],
"source": [
"data_cols = list(data.columns[ data.columns != 'Class' ])\n",
"label_cols = ['Class']\n",
"\n",
"print('Dataset columns: {}'.format(data_cols))\n",
"sorted_cols = ['V14', 'V4', 'V10', 'V17', 'V12', 'V26', 'Amount', 'V21', 'V8', 'V11', 'V7', 'V28', 'V19', 'V3', 'V22', 'V6', 'V20', 'V27', 'V16', 'V13', 'V25', 'V24', 'V18', 'V2', 'V1', 'V5', 'V15', 'V9', 'V23', 'Class']\n",
"processed_data = data[ sorted_cols ].copy()"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": null,
"outputs": [],
"source": [
"#Before training the GAN do not forget to apply the required data transformations\n",
"#To ease here we've applied a PowerTransformation\n",
"data = transformations(data)\n",
"\n",
"#For the purpose of this example we will only synthesize the minority class\n",
"train_data = data.loc[ data['Class']==1 ].copy()\n",
"\n",
"print(\"Dataset info: Number of records - {} Number of varibles - {}\".format(train_data.shape[0], train_data.shape[1]))\n",
"\n",
"algorithm = cluster.KMeans\n",
"args, kwds = (), {'n_clusters':2, 'random_state':0}\n",
"labels = algorithm(*args, **kwds).fit_predict(train_data[ data_cols ])\n",
"\n",
"print( pd.DataFrame( [ [np.sum(labels==i)] for i in np.unique(labels) ], columns=['count'], index=np.unique(labels) ) )\n",
"\n",
"fraud_w_classes = train_data.copy()\n",
"fraud_w_classes['Class'] = labels"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "markdown",
"source": [
"# GAN training\n",
"\n",
"Below you can try to train your own generators using the available GANs architectures. You can train it either with labels (created using KMeans) or with no labels at all. \n",
"\n",
"Remeber that for this exercise in particular we've decided to synthesize only the minority class from the Credit Fraud dataset."
],
"metadata": {
"collapsed": false
}
},
{
"cell_type": "code",
"execution_count": null,
"outputs": [],
"source": [
"#Define the Conditional GAN and training parameters\n",
"noise_dim = 32\n",
"dim = 128\n",
"batch_size = 128\n",
"\n",
"log_step = 100\n",
"epochs = 200+1\n",
"learning_rate = 5e-4\n",
"models_dir = './cache'\n",
"\n",
"train_sample = fraud_w_classes.copy().reset_index(drop=True)\n",
"train_sample = pd.get_dummies(train_sample, columns=['Class'], prefix='Class', drop_first=True)\n",
"label_cols = [train_sample.column.index(i) for i in train_sample.columns if 'Class' in i ]\n",
"data_cols = [ i for i in train_sample.columns if i not in label_cols ]\n",
"train_sample[ data_cols ] = train_sample[ data_cols ] / 10 # scale to random noise size, one less thing to learn\n",
"train_no_label = train_sample[ data_cols ]"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": null,
"outputs": [],
"source": [
"gan_args = [batch_size, learning_rate, noise_dim, train_sample.shape[1], 2, (0, 1), dim]\n",
"train_args = ['', label_cols[0], epochs, log_step, '']\n",
"\n",
"synthesizer = model(gan_args)\n",
"synthesizer.train(train_sample, train_args)"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "markdown",
"source": [
"# Checking the conditional results"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%% md\n"
}
}
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.6"
}
},
"nbformat": 4,
"nbformat_minor": 0
}

0 comments on commit 7e7018d

Please sign in to comment.