{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Подбор скорости обучения"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Скорость обучения - один из важных параметров, определяющий, на сколько сильно будут изменяться параметры модели на каждой итерации. Неправильный подбор скорости обучения ведет к некачественному обучению модели. В этом задании вам нужно подобрать скорость обучения так, чтобы обучить модель наилучшим образом."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "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": null,
   "metadata": {},
   "outputs": [],
   "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": 48,
   "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": 49,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch.optim as optim\n",
    "\n",
    "\"\"\"\n",
    "Оптимизатор - стохастический градиентный спуск\n",
    "epochs - число эпох обучения\n",
    "\n",
    "!!! в данном блоке можно настроить learning rate !!!\n",
    "\"\"\"\n",
    "learning_rate = 5.7\n",
    "optimizer = optim.SGD(model.parameters(), lr=learning_rate,\n",
    "                     momentum=0.9, nesterov=True)\n",
    "epochs = 50"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "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))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch.nn.functional as F\n",
    "\n",
    "print_every = 100 # как часто будем выводить loss\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",
    "    loss_arr=[]\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",
    "            if t % print_every == 0:\n",
    "                print('Iteration %d, loss = %.4f\\n' % (t, loss.item()))\n",
    "                check_accuracy(test_dataloader, model)\n",
    "        loss_arr.append(loss.item())\n",
    "    return loss_arr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "loss_arr = train_part34(model, optimizer, device, epochs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[<matplotlib.lines.Line2D at 0x2573d5b74a8>]"
      ]
     },
     "execution_count": 43,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 28544 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "epoch_arr = [i for i in range(len(loss_arr))]\n",
    "plt.title(\"Learning rate\")\n",
    "plt.xlabel(\"epoch\")\n",
    "plt.ylabel(\"loss\")\n",
    "plt.plot(epoch_arr, loss_arr)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "check_train_dataset, _ = D.random_split(train_dataset,\n",
    "                                                (1000, len(train_dataset) - 1000))\n",
    "check_train_dataloader = D.DataLoader(check_train_dataset, batch_size = 100)\n",
    "\n",
    "print('обучающая выборка')\n",
    "check_accuracy(check_train_dataloader, model) #проверка на части обучаюющей выборки\n",
    "print('тестовая выборка')\n",
    "check_accuracy(test_dataloader, model) # проверка на тестовой выборке"
   ]
  }
 ],
 "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
}
