{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Переобучение сети"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Один из возможных тестов работоспособности сети - это переобучение сети на небольшом объеме данных. Если сеть способна научиться решать задачу на этих данных, то на небольшой выборке в результате обучения мы должны получить значение функции ошибки, близкое к 0. В этом задании вам необходимо ознакомиться с кодом и, запустив ноутбук, убедиться в том, что сеть переобучается"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Подключение CUDA"
   ]
  },
  {
   "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": "markdown",
   "metadata": {},
   "source": [
    "# Загрузка данных"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "import torchvision\n",
    "import torchvision.transforms as transforms\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "\n",
    "transform = transforms.Compose(\n",
    "    [transforms.ToTensor(),\n",
    "     transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\n",
    "batch_size = 1000\n",
    "\n",
    "train_dataset = torchvision.datasets.CIFAR10(root='./data', train=True,\n",
    "                                        download=True, transform=transform)\n",
    "train_dataloader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size,\n",
    "                                          shuffle=True, num_workers=2)\n",
    "\n",
    "\n",
    "classes = ('plane', 'car', 'bird', 'cat',\n",
    "           'deer', 'dog', 'frog', 'horse', 'ship', 'truck')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Посмотрим на данные"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, axs = plt.subplots(10,1)\n",
    "fig.set_figwidth(16)\n",
    "fig.set_figheight(32)\n",
    "def imshow(img, idx, title):\n",
    "    img = img / 2 + 0.5     # unnormalize\n",
    "    npimg = img.numpy()\n",
    "    #plt.imshow(np.transpose(npimg, (1, 2, 0)))\n",
    "    axs[idx].imshow(np.transpose(npimg, (1, 2, 0)))\n",
    "    axs[idx].set_title(title)\n",
    "    axs[idx].set_xticks([])\n",
    "    axs[idx].set_yticks([])\n",
    "\n",
    "    #plt.show()\n",
    "\n",
    "dataiter = iter(train_dataloader)\n",
    "images, labels = dataiter.next()\n",
    "\n",
    "counts = {classes[i]: 4 for i in range(10)}\n",
    "imgs_and_labels = {classes[i]: [] for i in range(10)}\n",
    "\n",
    "for j in range(batch_size):\n",
    "    if counts[classes[labels[j]]] > 0:\n",
    "        imgs_and_labels[classes[labels[j]]].append(images[j])\n",
    "        counts[classes[labels[j]]]-=1\n",
    "\n",
    "class_id =0\n",
    "for key in imgs_and_labels.keys():\n",
    "    imshow(torchvision.utils.make_grid(imgs_and_labels[key]),class_id, classes[class_id])\n",
    "    class_id+=1\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "повторная загрузка данных для обучения сети\n",
    "\"\"\"\n",
    "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 = 50\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, (train_len, len(master_dataset)-train_len))\n",
    "train_dataloader = D.DataLoader(train_dataset, batch_size = 25)\n",
    "test_dataloader = D.DataLoader(test_dataset, batch_size = 25)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Параметы сети"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import convnet\n",
    "\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": "markdown",
   "metadata": {},
   "source": [
    "# Параметры обучения"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch.optim as optim\n",
    "\n",
    "\"\"\"\n",
    "Оптимизатор - стохастический градиентный спуск\n",
    "epochs - число эпох обучения\n",
    "\"\"\"\n",
    "learning_rate = 1e-2\n",
    "optimizer = optim.SGD(model.parameters(), lr=learning_rate,\n",
    "                     momentum=0.9, nesterov=True)\n",
    "epochs = 5"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Обучение сети"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "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": null,
   "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": [
    "loss_arr = train_part34(model, optimizer, device, epochs)"
   ]
  }
 ],
 "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
}
