{
 "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 resnet18\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 = resnet18()\n",
    "model = nn.DataParallel(model)\n",
    "model = model.to(device)\n",
    "\n",
    "model_dir = 'runs/models/cifar10-stepsize0.1-lr0.0005-optimizersgd-cifar10-resnet18-tiny-earlystop'\n",
    "generation_result_dir = 'results/generation/CIFAR-10-resnet18'\n",
    "ood_result_dir = 'results/OOD/CIFAR-10-resnet18'\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": "markdown",
   "metadata": {},
   "source": [
    "## Out-of-distribution detection evaluation"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### $K=5$, with perturbation of 0.01 ($L^\\infty$)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "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",
      "{'norm': 'Linf', 'eps': 0.01, 'steps': 100, 'step_size': 0.002}\n",
      "Files already downloaded and verified\n",
      "Using downloaded and verified file: ./datasets/test_32x32.mat\n",
      "Files already downloaded and verified\n",
      "{'norm': 'Linf', 'eps': 0.01, 'steps': 500, 'step_size': 0.002}\n",
      "Files already downloaded and verified\n",
      "Using downloaded and verified file: ./datasets/test_32x32.mat\n",
      "Files already downloaded and verified\n",
      "{'norm': 'Linf', 'eps': 0.01, 'steps': 500, 'step_size': 0.005}\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "\n",
    "ood_det_results = {}\n",
    "ood_datasets = ['Gaussian noise', 'Uniform noise', 'SVHN', 'CIFAR100']\n",
    "\n",
    "for (steps, step_size) in [(100, 0.002), (500, 0.002), (500, 0.005), (500, 0.01), (1000, 0.001)]:\n",
    "    for K in [5]:\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",
    "                                                     norm='Linf', test_samples=1000,\n",
    "                                                     ood_datasets=ood_datasets, \n",
    "                                                     steps=steps, step_size=step_size)\n",
    "                                  for eps in [0.01]])\n",
    "        ood_det_results['steps{}step-size{}K={:05d}'.format(steps, step_size, K)] = model_result\n",
    "for k, v in ood_det_results.items():\n",
    "    print(k)\n",
    "    display(v)\n",
    "pickle.dump(ood_det_results, open(os.path.join(ood_result_dir, \"ood_robustness_linf.pkl\"), \"wb\" ) )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "steps100step-size0.002K=00005\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>SVHN</th>\n",
       "      <th>CIFAR100</th>\n",
       "      <th>mean</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <td>0.0</td>\n",
       "      <td>0.993186</td>\n",
       "      <td>0.986939</td>\n",
       "      <td>0.914752</td>\n",
       "      <td>0.824144</td>\n",
       "      <td>0.929755</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "     Gaussian noise  Uniform noise      SVHN  CIFAR100      mean\n",
       "0.0        0.993186       0.986939  0.914752  0.824144  0.929755"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "steps500step-size0.002K=00005\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>SVHN</th>\n",
       "      <th>CIFAR100</th>\n",
       "      <th>mean</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <td>0.0</td>\n",
       "      <td>0.993118</td>\n",
       "      <td>0.986935</td>\n",
       "      <td>0.914685</td>\n",
       "      <td>0.823989</td>\n",
       "      <td>0.929682</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "     Gaussian noise  Uniform noise      SVHN  CIFAR100      mean\n",
       "0.0        0.993118       0.986935  0.914685  0.823989  0.929682"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "steps500step-size0.005K=00005\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>SVHN</th>\n",
       "      <th>CIFAR100</th>\n",
       "      <th>mean</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <td>0.0</td>\n",
       "      <td>0.993242</td>\n",
       "      <td>0.986969</td>\n",
       "      <td>0.914775</td>\n",
       "      <td>0.8243</td>\n",
       "      <td>0.929822</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "     Gaussian noise  Uniform noise      SVHN  CIFAR100      mean\n",
       "0.0        0.993242       0.986969  0.914775    0.8243  0.929822"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "steps500step-size0.01K=00005\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>SVHN</th>\n",
       "      <th>CIFAR100</th>\n",
       "      <th>mean</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <td>0.0</td>\n",
       "      <td>0.993915</td>\n",
       "      <td>0.987054</td>\n",
       "      <td>0.915729</td>\n",
       "      <td>0.826115</td>\n",
       "      <td>0.930703</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "     Gaussian noise  Uniform noise      SVHN  CIFAR100      mean\n",
       "0.0        0.993915       0.987054  0.915729  0.826115  0.930703"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "steps1000step-size0.001K=00005\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>SVHN</th>\n",
       "      <th>CIFAR100</th>\n",
       "      <th>mean</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <td>0.0</td>\n",
       "      <td>0.993114</td>\n",
       "      <td>0.986932</td>\n",
       "      <td>0.914695</td>\n",
       "      <td>0.824031</td>\n",
       "      <td>0.929693</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "     Gaussian noise  Uniform noise      SVHN  CIFAR100      mean\n",
       "0.0        0.993114       0.986932  0.914695  0.824031  0.929693"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "ood_det_results = pickle.load(open(os.path.join(ood_result_dir, \"ood_robustness_linf.pkl\"), \"rb\" ))\n",
    "for k, v in ood_det_results.items():\n",
    "    print(k)\n",
    "    display(v)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ood_det_results = {}\n",
    "ood_datasets = ['Gaussian noise', 'Uniform noise', 'SVHN', 'CIFAR100']\n",
    "\n",
    "for K in [5]:\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",
    "                                                 norm='Linf', test_samples=1000,\n",
    "                                                 ood_datasets=ood_datasets, num_random_restarts=5)\n",
    "                              for eps in [0.01]])\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",
    "pickle.dump(ood_det_results, open(os.path.join(ood_result_dir, \"ood_perturbed_randomrestart.pkl\"), \"wb\" ) )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "K=00005\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>SVHN</th>\n",
       "      <th>CIFAR100</th>\n",
       "      <th>mean</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <td>0.0</td>\n",
       "      <td>0.993063</td>\n",
       "      <td>0.986933</td>\n",
       "      <td>0.914477</td>\n",
       "      <td>0.823855</td>\n",
       "      <td>0.929582</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "     Gaussian noise  Uniform noise      SVHN  CIFAR100      mean\n",
       "0.0        0.993063       0.986933  0.914477  0.823855  0.929582"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "ood_det_results = pickle.load(open(os.path.join(ood_result_dir, \"ood_perturbed_randomrestart.pkl\"), \"rb\" ))\n",
    "for k, v in ood_det_results.items():\n",
    "    print(k)\n",
    "    display(v)"
   ]
  },
  {
   "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
}
