{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "%load_ext autoreload\n",
    "%autoreload 2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-03-28T01:44:30.747471Z",
     "start_time": "2020-03-28T01:44:30.082778Z"
    },
    "run_control": {
     "frozen": false,
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "import torch\n",
    "from models import *\n",
    "import torchvision.datasets\n",
    "import torchvision.transforms as transforms\n",
    "import numpy as np\n",
    "import os\n",
    "import torch.nn as nn\n",
    "import matplotlib.pyplot as plt\n",
    "from pgd_attack import forward, perturb\n",
    "from sklearn.metrics import roc_curve, auc as auc_fn\n",
    "from dataset import *\n",
    "from utils import set_eval, set_train\n",
    "import seaborn as sns\n",
    "import torchvision\n",
    "from torchvision.utils import make_grid\n",
    "import pandas as pd\n",
    "from eval_utils import *\n",
    "import pickle\n",
    "import pathlib\n",
    "from IPython.display import display"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "device = 'cuda:0'\n",
    "datadir = './datasets'\n",
    "\n",
    "model = ResNet3BN(10)\n",
    "model = nn.DataParallel(model)\n",
    "model = model.to(device)\n",
    "\n",
    "# model_dir = './experiments/cifar10-class0-ood-uniform'\n",
    "model_dir = './runs/models/cifar10-class0-stepsize0.1-lr0.0005-optimizersgd-release-cifar10-ood-uniform//'\n",
    "generation_result_dir = 'results/generation/CIFAR-10-class0-ood-uniform'\n",
    "ood_result_dir = 'results/OOD/CIFAR-10-class0-ood-uniform'\n",
    "\n",
    "for path in [model_dir, generation_result_dir, ood_result_dir]:\n",
    "    pathlib.Path(path).mkdir(parents=True, exist_ok=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "os.environ['cifar10_class'] = '0' # Remember to set this"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Out-of-distribution detection evaluation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Files already downloaded and verified\n",
      "Using downloaded and verified file: ./datasets/test_32x32.mat\n",
      "Files already downloaded and verified\n",
      "Files already downloaded and verified\n",
      "Using downloaded and verified file: ./datasets/test_32x32.mat\n",
      "Files already downloaded and verified\n",
      "Files already downloaded and verified\n",
      "Using downloaded and verified file: ./datasets/test_32x32.mat\n",
      "Files already downloaded and verified\n",
      "Files already downloaded and verified\n",
      "Using downloaded and verified file: ./datasets/test_32x32.mat\n",
      "Files already downloaded and verified\n",
      "K=00000\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Gaussian noise</th>\n",
       "      <th>Uniform noise</th>\n",
       "      <th>ImageNet</th>\n",
       "      <th>Bedroom</th>\n",
       "      <th>SVHN</th>\n",
       "      <th>CelebAHQ</th>\n",
       "      <th>CIFAR100</th>\n",
       "      <th>mean</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <td>0.0</td>\n",
       "      <td>1.0</td>\n",
       "      <td>1.0</td>\n",
       "      <td>0.585884</td>\n",
       "      <td>0.579132</td>\n",
       "      <td>0.580141</td>\n",
       "      <td>0.523488</td>\n",
       "      <td>0.549857</td>\n",
       "      <td>0.688357</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>1.0</td>\n",
       "      <td>1.0</td>\n",
       "      <td>1.0</td>\n",
       "      <td>0.516145</td>\n",
       "      <td>0.502755</td>\n",
       "      <td>0.514102</td>\n",
       "      <td>0.451028</td>\n",
       "      <td>0.481569</td>\n",
       "      <td>0.637943</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "     Gaussian noise  Uniform noise  ImageNet   Bedroom      SVHN  CelebAHQ  \\\n",
       "0.0             1.0            1.0  0.585884  0.579132  0.580141  0.523488   \n",
       "1.0             1.0            1.0  0.516145  0.502755  0.514102  0.451028   \n",
       "\n",
       "     CIFAR100      mean  \n",
       "0.0  0.549857  0.688357  \n",
       "1.0  0.481569  0.637943  "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "K=00015\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Gaussian noise</th>\n",
       "      <th>Uniform noise</th>\n",
       "      <th>ImageNet</th>\n",
       "      <th>Bedroom</th>\n",
       "      <th>SVHN</th>\n",
       "      <th>CelebAHQ</th>\n",
       "      <th>CIFAR100</th>\n",
       "      <th>mean</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <td>0.0</td>\n",
       "      <td>1.0</td>\n",
       "      <td>1.0</td>\n",
       "      <td>0.577152</td>\n",
       "      <td>0.576022</td>\n",
       "      <td>0.571070</td>\n",
       "      <td>0.513907</td>\n",
       "      <td>0.543464</td>\n",
       "      <td>0.683088</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>1.0</td>\n",
       "      <td>1.0</td>\n",
       "      <td>1.0</td>\n",
       "      <td>0.506323</td>\n",
       "      <td>0.498396</td>\n",
       "      <td>0.504257</td>\n",
       "      <td>0.440582</td>\n",
       "      <td>0.473839</td>\n",
       "      <td>0.631914</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "     Gaussian noise  Uniform noise  ImageNet   Bedroom      SVHN  CelebAHQ  \\\n",
       "0.0             1.0            1.0  0.577152  0.576022  0.571070  0.513907   \n",
       "1.0             1.0            1.0  0.506323  0.498396  0.504257  0.440582   \n",
       "\n",
       "     CIFAR100      mean  \n",
       "0.0  0.543464  0.683088  \n",
       "1.0  0.473839  0.631914  "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "ood_datasets = ['Gaussian noise', 'Uniform noise', 'ImageNet', \n",
    "                'Bedroom', 'SVHN', 'CelebAHQ', 'CIFAR100']\n",
    "ood_det_results = {}\n",
    "for K in [0, 15]:\n",
    "    cached_model = os.path.join(model_dir, 'steps{:05d}/model.pth'.format(K))\n",
    "    model.load_state_dict(torch.load(cached_model))\n",
    "    set_eval(model)\n",
    "    model_result = pd.concat([eval_ood_detection(model, 'CIFAR10', epsilon=eps, \n",
    "                                                 test_samples=1000, ood_datasets=ood_datasets) \n",
    "                              for eps in [0.0, 1.0]])\n",
    "    ood_det_results['K={:05d}'.format(K)] = model_result\n",
    "for k, v in ood_det_results.items():\n",
    "    print(k)\n",
    "    display(v)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "pickle.dump(ood_det_results, open(os.path.join(ood_result_dir, \"ood.pkl\"), \"wb\" ) )\n",
    "# ood_det_results = pickle.load(open(os.path.join(ood_result_dir, \"ood.pkl\"), \"rb\" ))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "# # Uncomment to print the latex code for the above tables\n",
    "# for k, v in ood_det_results.items():\n",
    "#     print(k)\n",
    "#     print(v.to_latex(escape=False, float_format=lambda x: '%10.4f' % x))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "hide_input": false,
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  },
  "toc": {
   "colors": {
    "hover_highlight": "#DAA520",
    "running_highlight": "#FF0000",
    "selected_highlight": "#FFD700"
   },
   "moveMenuLeft": true,
   "nav_menu": {
    "height": "11.1px",
    "width": "251.1px"
   },
   "navigate_menu": true,
   "number_sections": true,
   "sideBar": true,
   "threshold": 4,
   "toc_cell": false,
   "toc_section_display": "block",
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
