{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\nimport matplotlib.pyplot as plt\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.linear_model import LogisticRegression\n\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n        \nimport gc        \n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pip install ganify==1.0.10","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Load data\n\nWe are going to load the data from files into dataframes using Pandas.\n","execution_count":null},{"metadata":{"_cell_guid":"","_uuid":"","trusted":true},"cell_type":"code","source":"import pandas as pd\nsample_submission = pd.read_csv(\"../input/digit-recognizer/sample_submission.csv\")\ntest = pd.read_csv(\"../input/digit-recognizer/test.csv\")\ntrain = pd.read_csv(\"../input/digit-recognizer/train.csv\")\n\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Take a look at the data.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"The first columns is the label of the data indicating the actual digit. Pixel0 to pixel783 are the values of the flattened 784 pixels.","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"# Train/validation splitting\n\nIn Machine Learning, it's extremely important to validate the trained model against a dataset that has never been \"seen\" by the model. Here we will randomly split the train dataset into two sets: one for training and one for validation using a 80:20 ratio.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"x_test = test.values.astype(np.int32)\nx_train, x_val, y_train, y_val = train_test_split(\n    train.values[:,1:].astype(np.int32), train.values[:,0].astype(np.int32), test_size=0.2)\n\ndel train, test\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Visualize some images","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"fig, ax = plt.subplots(4, 4, figsize=(8,8))\nfor i in range(4):\n    for j in range(4):\n        ax[i, j].imshow(x_train[i*4+j*4].reshape(28,28), cmap='gray')\n        ax[i, j].set_title('label = %s' % (y_train[i*4 + j*4]))\n        ax[i, j].set_xticks([])\n        ax[i, j].set_yticks([])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Create a Logistic Regression model","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"lr = LogisticRegression(solver='lbfgs', C=30)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Train it and validate it","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"lr.fit(x_train, y_train)\nfrom sklearn.metrics import accuracy_score\ny_val_pred = lr.predict(x_val)\nprint(\"Model accuracy is %0.3f\" % (accuracy_score(y_val, y_val_pred)))\nprint(\"Confusion Matrix:\")\nprint(confusion_matrix(y_val, y_val_pred))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Data augmentation using GANify","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"from ganify import Ganify\n\ndef gan_mnist_class(X, y, digit, n_samples):\n    mask = y==digit\n    x_real = X[mask]\n    y_real = y[mask]\n    print(digit,x_real.shape[0])\n    gan = Ganify()\n    gan.fit_data(x_real, y_real, batch_size=256, epochs=3)\n    x_fake = gan.create_bulk(n_samples)\n    y_fake = np.full(n_samples, digit).astype(int) \n    print(f\"{n_samples} samples generated\", x_fake.shape, y_fake.shape)\n    print(x_fake[:5], y_fake[:5])\n    return x_fake.astype(np.int32), y_fake.astype(np.int32)\n\ndef gan_mnist(X, y, n_samples):\n    x_gan_list = []\n    y_gan_list = []\n    for i in range(10):\n        print(f\"Generating fake images for digit {i}\")\n        x_gan, y_gan = gan_mnist_class(x_train, y_train, i, n_samples)\n        x_gan_list.append(x_gan)\n        y_gan_list.append(y_gan)\n    return np.vstack(x_gan_list), np.hstack(y_gan_list)\n\nx_fake, y_fake = gan_mnist(x_train, y_train, n_samples=1000)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"## Visualize synthetic images\nfig, ax = plt.subplots(10, 10, figsize=(12,12))\nfor i in range(10):\n    for j in range(10):\n        ax[i, j].imshow(x_fake[i*1000+j*10].reshape(28,28), cmap='gray')\n        ax[i, j].set_xticks([])\n        ax[i, j].set_title('label = %s' % (y_fake[i*1000+j*10]))\n        ax[i, j].set_yticks([])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"lr_gan = LogisticRegression(solver='lbfgs', C=30)\nlr_gan.fit(np.vstack((x_train, x_fake)), np.hstack((y_train, \n                                               y_fake)))\nfrom sklearn.metrics import accuracy_score\ny_val_pred = lr_gan.predict(x_val)\nprint(\"Model accuracy is %0.3f\" % (accuracy_score(y_val, y_val_pred)))\nprint(\"Confusion Matrix:\")\nprint(confusion_matrix(y_val, y_val_pred))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_fake.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pd.Series(y_fake).value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.metrics import accuracy_score\npreds = lr.predict(x_test)\npreds_gan = lr_gan.predict(x_test)\n\nsample_submission['Label'] = preds\nsample_submission.to_csv('submission.csv', index=False)\n\nsample_submission['Label'] = preds_gan\nsample_submission.to_csv('submission_gan.csv', index=False)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":4}