{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Поиск баланса"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Еще один фактор, позволяющий определить качество обучения - это разница в точности модели на тренировочной и тестовой выборках. В этом задании вам необходимо подобрать параметры модели таким образом, чтобы эта разница была минимальной"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "вычисляем на: cuda\n"
     ]
    }
   ],
   "source": [
    "\"\"\"\n",
    "Включаем CUDA, ессли доступна. Это позволит производить вычисления на GPU.\n",
    "Если CUDA не установлена, вычисления будут проходить на cpu\n",
    "\"\"\"\n",
    "import torch\n",
    "\n",
    "dtype = torch.float32\n",
    "USE_GPU = True\n",
    "device = 0\n",
    "if USE_GPU and torch.cuda.is_available():\n",
    "    device = torch.device('cuda')\n",
    "else:\n",
    "    device = torch.device('cpu')\n",
    "print('вычисляем на:', device)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Files already downloaded and verified\n"
     ]
    }
   ],
   "source": [
    "import torch\n",
    "import torchvision\n",
    "import torchvision.transforms as transforms\n",
    "from torch.utils import data as D\n",
    "\n",
    "transform = transforms.Compose(\n",
    "    [transforms.ToTensor(),\n",
    "     transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\n",
    "train_len = 20000\n",
    "test_len = train_len//10\n",
    "master_dataset = torchvision.datasets.CIFAR10(root='./data', train=True,\n",
    "                                        download=True, transform=transform)\n",
    "\n",
    "train_dataset, test_dataset, _ = D.random_split(master_dataset,\n",
    "                                                (train_len, test_len, len(master_dataset) - train_len - test_len))\n",
    "train_dataloader = D.DataLoader(train_dataset, batch_size = 100)\n",
    "test_dataloader = D.DataLoader(test_dataset, batch_size = 100)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "import convnet\n",
    "# Размер изображений для работы с сетью\n",
    "width = 32\n",
    "height = 32\n",
    "chanels = 3\n",
    "im_size = (width, height, chanels)\n",
    "\n",
    "\"\"\"\n",
    "Параметры светрочного блока обёрнуты в виде кортежа\n",
    "num_filters - число сверточных фильтров\n",
    "conv_kernel - размер сверточного ядра\n",
    "pooling_kernel - размер пулинг ядра\n",
    "\"\"\"\n",
    "num_filters = 9 # depth\n",
    "conv_kernel = 3 # 3*3\n",
    "pooling_kernel = 2 #2*2\n",
    "conv_tuple =  (num_filters, conv_kernel, pooling_kernel)\n",
    "\n",
    "\"\"\"\n",
    "conv_params - последовательность из трех сверточных блоков в сети\n",
    "\"\"\"\n",
    "conv_params = [conv_tuple, conv_tuple, conv_tuple]\n",
    "\n",
    "\"\"\"\n",
    "полносвязный блок\n",
    "\"\"\"\n",
    "linear1 = 20\n",
    "linear2 = 10 # число классов\n",
    "linear_params = [linear1, linear2]\n",
    "\n",
    "\"\"\"\n",
    "создаем сеть с указанными выше параметрами для блоков\n",
    "\"\"\"\n",
    "model = convnet.ConvNet(im_size, conv_params, linear_params)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "Здесь будем проверять точность модели в ходе обучения\n",
    "\"\"\"\n",
    "def check_accuracy(loader, model):  \n",
    "    num_correct = 0\n",
    "    num_samples = 0\n",
    "    model.eval()\n",
    "    with torch.no_grad():\n",
    "        for x, y in loader:\n",
    "            x = x.to(device=device, dtype=dtype)\n",
    "            y = y.to(device=device, dtype=torch.long)\n",
    "            scores = model(x)\n",
    "            _, preds = scores.max(1)\n",
    "            num_correct += (preds == y).sum()\n",
    "            num_samples += preds.size(0)\n",
    "        acc = float(num_correct) / num_samples\n",
    "        print('Got %d / %d correct (%.2f)\\n\\n' % (num_correct, num_samples, 100 * acc))\n",
    "        return 100 * acc"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch.nn.functional as F\n",
    "\n",
    "\"\"\"\n",
    "Метод обучения сети\n",
    "\"\"\"\n",
    "def train_part34(model, optimizer, device, epochs):\n",
    "    \"\"\"    \n",
    "    Inputs:\n",
    "    - model: A PyTorch Module giving the model to train.\n",
    "    - optimizer: An Optimizer object we will use to train the model\n",
    "    - device: cuda/cpu\n",
    "    - epochs: (Optional) A Python integer giving the number of epochs to train for\n",
    "    \"\"\"\n",
    "    train_accuracy = []\n",
    "    test_accuracy = []\n",
    "    model = model.to(device=device)\n",
    "    for e in range(epochs):\n",
    "        for t, (x, y) in enumerate(train_dataloader):\n",
    "            model.train()\n",
    "            x = x.to(device=device, dtype=dtype)\n",
    "            y = y.to(device=device, dtype=torch.long)\n",
    "            scores = model(x)\n",
    "            loss = F.cross_entropy(scores, y)\n",
    "            optimizer.zero_grad()\n",
    "            loss.backward()\n",
    "            optimizer.step()\n",
    "        train_accuracy.append(check_accuracy(train_dataloader, model))\n",
    "        test_accuracy.append(check_accuracy(test_dataloader, model))\n",
    "    return (train_accuracy, test_accuracy)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Случай 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch.optim as optim\n",
    "\n",
    "\"\"\"\n",
    "Оптимизатор - стохастический градиентный спуск\n",
    "epochs - число эпох обучения\n",
    "\"\"\"\n",
    "# !!! здесь подбирайте параметры\n",
    "learning_rate = 1.2\n",
    "optimizer = optim.SGD(model.parameters(), lr=learning_rate,\n",
    "                     momentum=0.9, nesterov=True, weight_decay=0.85)\n",
    "epochs = 10"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "train_acc, test_acc = train_part34(model, optimizer, device, epochs)\n",
    "epoch_list = [i for i in range(epochs)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 7568 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "fig, ax = plt.subplots()\n",
    "ax.plot(epoch_list, train_acc, epoch_list, test_acc)\n",
    "lgnd = ax.legend(['train', 'test'], loc='lower right')\n",
    "plt.xlabel(\"epoch\")\n",
    "plt.ylabel(\"accuracy\")\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Случай 2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch.optim as optim\n",
    "\n",
    "\"\"\"\n",
    "Оптимизатор - стохастический градиентный спуск\n",
    "epochs - число эпох обучения\n",
    "\"\"\"\n",
    "# !!! здесь подбирайте параметры\n",
    "\n",
    "model = convnet.ConvNet(im_size, conv_params, linear_params)\n",
    "learning_rate = 1.6\n",
    "optimizer = optim.SGD(model.parameters(), lr=learning_rate,\n",
    "                     momentum=0.09, nesterov=True, weight_decay=0)\n",
    "epochs = 50"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Got 9049 / 20000 correct (45.25)\n",
      "\n",
      "\n",
      "Got 904 / 2000 correct (45.20)\n",
      "\n",
      "\n",
      "Got 9982 / 20000 correct (49.91)\n",
      "\n",
      "\n",
      "Got 988 / 2000 correct (49.40)\n",
      "\n",
      "\n",
      "Got 11068 / 20000 correct (55.34)\n",
      "\n",
      "\n",
      "Got 1064 / 2000 correct (53.20)\n",
      "\n",
      "\n",
      "Got 11101 / 20000 correct (55.51)\n",
      "\n",
      "\n",
      "Got 1056 / 2000 correct (52.80)\n",
      "\n",
      "\n",
      "Got 12173 / 20000 correct (60.87)\n",
      "\n",
      "\n",
      "Got 1150 / 2000 correct (57.50)\n",
      "\n",
      "\n",
      "Got 11640 / 20000 correct (58.20)\n",
      "\n",
      "\n",
      "Got 1119 / 2000 correct (55.95)\n",
      "\n",
      "\n",
      "Got 12134 / 20000 correct (60.67)\n",
      "\n",
      "\n",
      "Got 1160 / 2000 correct (58.00)\n",
      "\n",
      "\n",
      "Got 12282 / 20000 correct (61.41)\n",
      "\n",
      "\n",
      "Got 1169 / 2000 correct (58.45)\n",
      "\n",
      "\n",
      "Got 12162 / 20000 correct (60.81)\n",
      "\n",
      "\n",
      "Got 1155 / 2000 correct (57.75)\n",
      "\n",
      "\n",
      "Got 12261 / 20000 correct (61.30)\n",
      "\n",
      "\n",
      "Got 1148 / 2000 correct (57.40)\n",
      "\n",
      "\n",
      "Got 11747 / 20000 correct (58.74)\n",
      "\n",
      "\n",
      "Got 1089 / 2000 correct (54.45)\n",
      "\n",
      "\n",
      "Got 12031 / 20000 correct (60.16)\n",
      "\n",
      "\n",
      "Got 1126 / 2000 correct (56.30)\n",
      "\n",
      "\n",
      "Got 12700 / 20000 correct (63.50)\n",
      "\n",
      "\n",
      "Got 1153 / 2000 correct (57.65)\n",
      "\n",
      "\n",
      "Got 13369 / 20000 correct (66.84)\n",
      "\n",
      "\n",
      "Got 1207 / 2000 correct (60.35)\n",
      "\n",
      "\n",
      "Got 13299 / 20000 correct (66.50)\n",
      "\n",
      "\n",
      "Got 1214 / 2000 correct (60.70)\n",
      "\n",
      "\n",
      "Got 13197 / 20000 correct (65.98)\n",
      "\n",
      "\n",
      "Got 1181 / 2000 correct (59.05)\n",
      "\n",
      "\n",
      "Got 13432 / 20000 correct (67.16)\n",
      "\n",
      "\n",
      "Got 1213 / 2000 correct (60.65)\n",
      "\n",
      "\n",
      "Got 13639 / 20000 correct (68.19)\n",
      "\n",
      "\n",
      "Got 1224 / 2000 correct (61.20)\n",
      "\n",
      "\n",
      "Got 13937 / 20000 correct (69.69)\n",
      "\n",
      "\n",
      "Got 1265 / 2000 correct (63.25)\n",
      "\n",
      "\n",
      "Got 13718 / 20000 correct (68.59)\n",
      "\n",
      "\n",
      "Got 1232 / 2000 correct (61.60)\n",
      "\n",
      "\n",
      "Got 13910 / 20000 correct (69.55)\n",
      "\n",
      "\n",
      "Got 1217 / 2000 correct (60.85)\n",
      "\n",
      "\n",
      "Got 13698 / 20000 correct (68.49)\n",
      "\n",
      "\n",
      "Got 1221 / 2000 correct (61.05)\n",
      "\n",
      "\n",
      "Got 13548 / 20000 correct (67.74)\n",
      "\n",
      "\n",
      "Got 1201 / 2000 correct (60.05)\n",
      "\n",
      "\n",
      "Got 13665 / 20000 correct (68.33)\n",
      "\n",
      "\n",
      "Got 1212 / 2000 correct (60.60)\n",
      "\n",
      "\n",
      "Got 13747 / 20000 correct (68.73)\n",
      "\n",
      "\n",
      "Got 1207 / 2000 correct (60.35)\n",
      "\n",
      "\n",
      "Got 13725 / 20000 correct (68.62)\n",
      "\n",
      "\n",
      "Got 1211 / 2000 correct (60.55)\n",
      "\n",
      "\n",
      "Got 13771 / 20000 correct (68.86)\n",
      "\n",
      "\n",
      "Got 1196 / 2000 correct (59.80)\n",
      "\n",
      "\n",
      "Got 13806 / 20000 correct (69.03)\n",
      "\n",
      "\n",
      "Got 1214 / 2000 correct (60.70)\n",
      "\n",
      "\n",
      "Got 13655 / 20000 correct (68.27)\n",
      "\n",
      "\n",
      "Got 1188 / 2000 correct (59.40)\n",
      "\n",
      "\n",
      "Got 13789 / 20000 correct (68.95)\n",
      "\n",
      "\n",
      "Got 1205 / 2000 correct (60.25)\n",
      "\n",
      "\n",
      "Got 14124 / 20000 correct (70.62)\n",
      "\n",
      "\n",
      "Got 1246 / 2000 correct (62.30)\n",
      "\n",
      "\n",
      "Got 14110 / 20000 correct (70.55)\n",
      "\n",
      "\n",
      "Got 1233 / 2000 correct (61.65)\n",
      "\n",
      "\n",
      "Got 14081 / 20000 correct (70.41)\n",
      "\n",
      "\n",
      "Got 1211 / 2000 correct (60.55)\n",
      "\n",
      "\n",
      "Got 13806 / 20000 correct (69.03)\n",
      "\n",
      "\n",
      "Got 1196 / 2000 correct (59.80)\n",
      "\n",
      "\n",
      "Got 13883 / 20000 correct (69.42)\n",
      "\n",
      "\n",
      "Got 1193 / 2000 correct (59.65)\n",
      "\n",
      "\n",
      "Got 13923 / 20000 correct (69.62)\n",
      "\n",
      "\n",
      "Got 1197 / 2000 correct (59.85)\n",
      "\n",
      "\n",
      "Got 13954 / 20000 correct (69.77)\n",
      "\n",
      "\n",
      "Got 1208 / 2000 correct (60.40)\n",
      "\n",
      "\n",
      "Got 14277 / 20000 correct (71.39)\n",
      "\n",
      "\n",
      "Got 1235 / 2000 correct (61.75)\n",
      "\n",
      "\n",
      "Got 13916 / 20000 correct (69.58)\n",
      "\n",
      "\n",
      "Got 1201 / 2000 correct (60.05)\n",
      "\n",
      "\n",
      "Got 14256 / 20000 correct (71.28)\n",
      "\n",
      "\n",
      "Got 1237 / 2000 correct (61.85)\n",
      "\n",
      "\n",
      "Got 13844 / 20000 correct (69.22)\n",
      "\n",
      "\n",
      "Got 1183 / 2000 correct (59.15)\n",
      "\n",
      "\n",
      "Got 14197 / 20000 correct (70.98)\n",
      "\n",
      "\n",
      "Got 1238 / 2000 correct (61.90)\n",
      "\n",
      "\n",
      "Got 14105 / 20000 correct (70.53)\n",
      "\n",
      "\n",
      "Got 1224 / 2000 correct (61.20)\n",
      "\n",
      "\n",
      "Got 14216 / 20000 correct (71.08)\n",
      "\n",
      "\n",
      "Got 1214 / 2000 correct (60.70)\n",
      "\n",
      "\n",
      "Got 14218 / 20000 correct (71.09)\n",
      "\n",
      "\n",
      "Got 1223 / 2000 correct (61.15)\n",
      "\n",
      "\n",
      "Got 14415 / 20000 correct (72.08)\n",
      "\n",
      "\n",
      "Got 1232 / 2000 correct (61.60)\n",
      "\n",
      "\n",
      "Got 14559 / 20000 correct (72.80)\n",
      "\n",
      "\n",
      "Got 1255 / 2000 correct (62.75)\n",
      "\n",
      "\n",
      "Got 14294 / 20000 correct (71.47)\n",
      "\n",
      "\n",
      "Got 1214 / 2000 correct (60.70)\n",
      "\n",
      "\n",
      "Got 14625 / 20000 correct (73.12)\n",
      "\n",
      "\n",
      "Got 1260 / 2000 correct (63.00)\n",
      "\n",
      "\n",
      "Got 14549 / 20000 correct (72.75)\n",
      "\n",
      "\n",
      "Got 1255 / 2000 correct (62.75)\n",
      "\n",
      "\n"
     ]
    }
   ],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "train_acc, test_acc = train_part34(model, optimizer, device, epochs)\n",
    "epoch_list = [i for i in range(epochs)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 24072 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "fig, ax = plt.subplots()\n",
    "ax.plot(epoch_list, train_acc, epoch_list, test_acc)\n",
    "lgnd = ax.legend(['train', 'test'], loc='lower right')\n",
    "plt.xlabel(\"epoch\")\n",
    "plt.ylabel(\"accuracy\")\n",
    "plt.show()"
   ]
  }
 ],
 "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.6.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
