{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-02-06T09:24:32.236796Z",
     "start_time": "2021-02-06T09:24:32.221796Z"
    }
   },
   "outputs": [],
   "source": [
    "import ast\n",
    "import sys\n",
    "\n",
    "import cv2\n",
    "import matplotlib.pyplot as plt\n",
    "import pandas as pd\n",
    "import PIL.Image\n",
    "import torch\n",
    "import torch.nn.functional as F\n",
    "\n",
    "sys.path.insert(0, '..')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-02-06T09:24:32.319065Z",
     "start_time": "2021-02-06T09:24:32.238003Z"
    }
   },
   "outputs": [],
   "source": [
    "from pytorch_image_classification import (\n",
    "    get_default_config,\n",
    "    create_model,\n",
    "    create_transform,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-02-06T09:24:32.343282Z",
     "start_time": "2021-02-06T09:24:32.320340Z"
    }
   },
   "outputs": [],
   "source": [
    "config = get_default_config()\n",
    "config.merge_from_file('../configs/imagenet/resnet18.yaml')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-02-06T09:24:34.097658Z",
     "start_time": "2021-02-06T09:24:32.344294Z"
    },
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "device = torch.device(config.device)\n",
    "\n",
    "model = create_model(config)\n",
    "checkpoint = torch.load(\n",
    "    '../experiments/imagenet/resnet18/exp00/checkpoint_00090.pth')\n",
    "\n",
    "model.load_state_dict(checkpoint['model'])\n",
    "model.to(device)\n",
    "_ = model.eval()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-02-06T09:24:34.113155Z",
     "start_time": "2021-02-06T09:24:34.098735Z"
    }
   },
   "outputs": [],
   "source": [
    "transform = create_transform(config, is_train=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-02-06T09:24:34.557530Z",
     "start_time": "2021-02-06T09:24:34.114175Z"
    },
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "%%capture\n",
    "!wget https://gist.githubusercontent.com/yrevar/942d3a0ac09ec9e5eb3a/raw/238f720ff059c1f82f368259d1ca4ffa5dd8f9f5/imagenet1000_clsidx_to_labels.txt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-02-06T09:24:34.587135Z",
     "start_time": "2021-02-06T09:24:34.563884Z"
    }
   },
   "outputs": [],
   "source": [
    "with open('imagenet1000_clsidx_to_labels.txt') as f:\n",
    "    index2label = ast.literal_eval(f.read())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-02-06T09:24:34.837761Z",
     "start_time": "2021-02-06T09:24:34.588778Z"
    },
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "%%capture\n",
    "!wget https://images.pexels.com/photos/2071873/pexels-photo-2071873.jpeg"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-02-06T09:24:35.469123Z",
     "start_time": "2021-02-06T09:24:34.844437Z"
    }
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 73572 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "image = cv2.imread('pexels-photo-2071873.jpeg')\n",
    "plt.imshow(image[:, :, ::-1])\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-02-06T09:24:35.533131Z",
     "start_time": "2021-02-06T09:24:35.470198Z"
    }
   },
   "outputs": [
    {
     "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>label</th>\n",
       "      <th>score</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>Egyptian cat</td>\n",
       "      <td>0.836771</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>lynx, catamount</td>\n",
       "      <td>0.022285</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>tabby, tabby cat</td>\n",
       "      <td>0.020165</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>Siamese cat, Siamese</td>\n",
       "      <td>0.017015</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>tiger cat</td>\n",
       "      <td>0.007150</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                  label     score\n",
       "0          Egyptian cat  0.836771\n",
       "1       lynx, catamount  0.022285\n",
       "2      tabby, tabby cat  0.020165\n",
       "3  Siamese cat, Siamese  0.017015\n",
       "4             tiger cat  0.007150"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data = transform(PIL.Image.fromarray(image))\n",
    "with torch.no_grad():\n",
    "    pred = model(data.unsqueeze(0).to(device))\n",
    "prob = F.softmax(pred, dim=1).cpu()\n",
    "\n",
    "scores, indices = prob.topk(k=5)\n",
    "scores = scores.numpy().ravel()\n",
    "\n",
    "indices = indices.numpy().ravel()\n",
    "names = [index2label[index] for index in indices]\n",
    "pd.DataFrame({'label': names, 'score': scores})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "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.8.2"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
