{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Обработка исходных данных"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Предварительная обработка изображений также влияет на точность результата. При этом, может наблюдаться как улучшение точности, так и ухудшение. Рассмотрим пример, в котором показано, как точность модели изменяется при выделении на изображении скелетов людей."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# CUDA"
   ]
  },
  {
   "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": "markdown",
   "metadata": {},
   "source": [
    "# Исходные данные"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "повторная загрузка данных для обучения сети\n",
    "\"\"\"\n",
    "import torch\n",
    "import torchvision\n",
    "from torch.utils import data as D\n",
    "import MPII\n",
    "import convnet\n",
    "\n",
    "root = r'.\\imgs1' # !!!укажите путь до папки с картинками\n",
    "csv_path = r'.\\run_and_walk.csv' # !!!укажите путь до csv разметки\n",
    "\n",
    "batch_size = 15\n",
    "master_dataset = MPII.MPII(root, csv_path)\n",
    "master_len = len(master_dataset)\n",
    "test_len = int(0.1*master_len)\n",
    "train_len = master_len - test_len\n",
    "\n",
    "train_dataset, test_dataset = D.random_split(master_dataset, (train_len, test_len))\n",
    "train_dataloader = D.DataLoader(train_dataset, batch_size = 15)\n",
    "test_dataloader = D.DataLoader(test_dataset, batch_size = 15)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "\n",
    "classes = ('run','walk')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 690972 characters]\n",
      "text/plain": [
       "<Figure size 1152x2304 with 2 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "fig, axs = plt.subplots(2,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",
    "    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",
    "dataiter = iter(train_dataloader)\n",
    "images, labels = dataiter.next()\n",
    "\n",
    "counts = {classes[i]: 4 for i in range(2)}\n",
    "imgs_and_labels = {classes[i]: [] for i in range(2)}\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": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# !!! укажите размер изображений для работы с сетью\n",
    "width = 600\n",
    "height = 480\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\n",
    "conv_kernel = 3\n",
    "pooling_kernel = 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",
    "num_classes = 5 # !!! укажите число классов\n",
    "\n",
    "linear1 = num_classes*2\n",
    "linear2 = num_classes\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": [
    "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 = 10"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "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": 6,
   "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",
    "    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)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Iteration 0, loss = 1.9828\n",
      "\n",
      "Got 2 / 92 correct (2.17)\n",
      "\n",
      "\n",
      "Iteration 0, loss = 0.4871\n",
      "\n",
      "Got 63 / 92 correct (68.48)\n",
      "\n",
      "\n",
      "Iteration 0, loss = 0.3616\n",
      "\n",
      "Got 59 / 92 correct (64.13)\n",
      "\n",
      "\n",
      "Iteration 0, loss = 0.2829\n",
      "\n",
      "Got 61 / 92 correct (66.30)\n",
      "\n",
      "\n",
      "Iteration 0, loss = 0.1550\n",
      "\n",
      "Got 62 / 92 correct (67.39)\n",
      "\n",
      "\n",
      "Iteration 0, loss = 0.1870\n",
      "\n",
      "Got 63 / 92 correct (68.48)\n",
      "\n",
      "\n",
      "Iteration 0, loss = 0.0858\n",
      "\n",
      "Got 66 / 92 correct (71.74)\n",
      "\n",
      "\n",
      "Iteration 0, loss = 0.0478\n",
      "\n",
      "Got 66 / 92 correct (71.74)\n",
      "\n",
      "\n",
      "Iteration 0, loss = 0.0483\n",
      "\n",
      "Got 62 / 92 correct (67.39)\n",
      "\n",
      "\n",
      "Iteration 0, loss = 0.0347\n",
      "\n",
      "Got 66 / 92 correct (71.74)\n",
      "\n",
      "\n"
     ]
    }
   ],
   "source": [
    "train_part34(model, optimizer, device, epochs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [],
   "source": [
    "true_labels =[]\n",
    "predicted_labels =[]\n",
    "\n",
    "with torch.no_grad():\n",
    "    for data in test_dataloader:\n",
    "        images, labels = data\n",
    "        images = images.to(device = device, dtype = dtype)\n",
    "        labels = labels.to(device = device, dtype = torch.long)\n",
    "        outputs = model(images)\n",
    "        _, predicted = torch.max(outputs, 1)        \n",
    "        for label in labels:\n",
    "            true_labels.append(label.item())\n",
    "        for pred in predicted:\n",
    "            predicted_labels.append(pred.item())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 4584 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "\n",
    "d = {'label': true_labels, 'classifier': predicted_labels}\n",
    "sequenceDT = pd.DataFrame(data=d)\n",
    "\n",
    "n=2\n",
    "LoseMatrix = np.zeros((n,n))\n",
    "LoseCount = np.zeros((n))\n",
    "for i in range(1, len(sequenceDT)):\n",
    "  LoseMatrix[sequenceDT['label'][i]][sequenceDT['classifier'][i]]+=1\n",
    "  LoseCount[sequenceDT['label'][i]]+= 1\n",
    "LoseMatrix = LoseMatrix / LoseCount\n",
    "\n",
    "fig, ax = plt.subplots()\n",
    "im = ax.imshow(LoseMatrix)\n",
    "columns = [0,1]\n",
    "ax.set_xticks(np.arange(len(columns)))\n",
    "ax.set_yticks(np.arange(len(columns)))\n",
    "ax.set_xticklabels(columns)\n",
    "ax.set_yticklabels(columns)\n",
    "\n",
    "plt.setp(ax.get_xticklabels(), rotation=45, ha=\"right\",\n",
    "         rotation_mode=\"anchor\")\n",
    "\n",
    "for i in range(len(columns)):\n",
    "    for j in range(len(columns)):\n",
    "        text = ax.text(j, i, round(LoseMatrix[i][j],3),\n",
    "                       ha=\"center\", va=\"baseline\", color=\"k\")\n",
    "fig.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Обработанные данные\n",
    "## Изображения скелетов"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "повторная загрузка данных для обучения сети\n",
    "\"\"\"\n",
    "import torch\n",
    "import torchvision\n",
    "from torch.utils import data as D\n",
    "import MPII\n",
    "import convnet\n",
    "\n",
    "root = r'.\\imgs3' # !!!укажите путь до папки с картинками\n",
    "csv_path = r'.\\run_and_walk.csv' # !!!укажите путь до csv разметки\n",
    "\n",
    "batch_size = 15\n",
    "master_dataset = MPII.MPII(root, csv_path)\n",
    "master_len = len(master_dataset)\n",
    "test_len = int(0.1*master_len)\n",
    "train_len = master_len - test_len\n",
    "\n",
    "train_dataset, test_dataset = D.random_split(master_dataset, (train_len, test_len))\n",
    "train_dataloader = D.DataLoader(train_dataset, batch_size = 15)\n",
    "test_dataloader = D.DataLoader(test_dataset, batch_size = 15)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "\n",
    "classes = ('run','walk')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 50888 characters]\n",
      "text/plain": [
       "<Figure size 1152x1152 with 2 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "fig, axs = plt.subplots(2,1)\n",
    "fig.set_figwidth(16)\n",
    "fig.set_figheight(16)\n",
    "def imshow(img, idx, title):\n",
    "    img = img / 2 + 0.5     # unnormalize\n",
    "    npimg = img.numpy()\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",
    "dataiter = iter(train_dataloader)\n",
    "images, labels = dataiter.next()\n",
    "\n",
    "counts = {classes[i]: 4 for i in range(2)}\n",
    "imgs_and_labels = {classes[i]: [] for i in range(2)}\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": 42,
   "metadata": {},
   "outputs": [],
   "source": [
    "# !!! укажите размер изображений для работы с сетью\n",
    "width = 600\n",
    "height = 480\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\n",
    "conv_kernel = 3\n",
    "pooling_kernel = 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",
    "num_classes = 5 # !!! укажите число классов\n",
    "\n",
    "linear1 = num_classes*2\n",
    "linear2 = num_classes\n",
    "linear_params = [linear1, linear2]\n",
    "\n",
    "\"\"\"\n",
    "создаем сеть с указанными выше параметрами для блоков\n",
    "\"\"\"\n",
    "model = convnet.ConvNet(im_size, conv_params, linear_params)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "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 = 10"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Iteration 0, loss = 2.0374\n",
      "\n",
      "Got 3 / 66 correct (4.55)\n",
      "\n",
      "\n",
      "Iteration 0, loss = 0.9005\n",
      "\n",
      "Got 37 / 66 correct (56.06)\n",
      "\n",
      "\n",
      "Iteration 0, loss = 0.7239\n",
      "\n",
      "Got 37 / 66 correct (56.06)\n",
      "\n",
      "\n",
      "Iteration 0, loss = 0.6636\n",
      "\n",
      "Got 37 / 66 correct (56.06)\n",
      "\n",
      "\n",
      "Iteration 0, loss = 0.6301\n",
      "\n",
      "Got 37 / 66 correct (56.06)\n",
      "\n",
      "\n",
      "Iteration 0, loss = 0.6123\n",
      "\n",
      "Got 37 / 66 correct (56.06)\n",
      "\n",
      "\n",
      "Iteration 0, loss = 0.5983\n",
      "\n",
      "Got 37 / 66 correct (56.06)\n",
      "\n",
      "\n",
      "Iteration 0, loss = 0.5508\n",
      "\n",
      "Got 35 / 66 correct (53.03)\n",
      "\n",
      "\n",
      "Iteration 0, loss = 0.3455\n",
      "\n",
      "Got 35 / 66 correct (53.03)\n",
      "\n",
      "\n",
      "Iteration 0, loss = 0.1887\n",
      "\n",
      "Got 35 / 66 correct (53.03)\n",
      "\n",
      "\n"
     ]
    }
   ],
   "source": [
    "train_part34(model, optimizer, device, epochs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {},
   "outputs": [],
   "source": [
    "true_labels =[]\n",
    "predicted_labels =[]\n",
    "model.eval()\n",
    "with torch.no_grad():\n",
    "    for data in test_dataloader:\n",
    "        images, labels = data\n",
    "        images = images.to(device = device, dtype = dtype)\n",
    "        labels = labels.to(device = device, dtype = torch.long)\n",
    "        outputs = model(images)\n",
    "        _, predicted = torch.max(outputs, 1)        \n",
    "        for label in labels:\n",
    "            true_labels.append(label.item())\n",
    "        for pred in predicted:\n",
    "            predicted_labels.append(pred.item())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 4764 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "\n",
    "d = {'label': true_labels, 'classifier': predicted_labels}\n",
    "sequenceDT = pd.DataFrame(data=d)\n",
    "\n",
    "n=2\n",
    "LoseMatrix = np.zeros((n,n))\n",
    "LoseCount = np.zeros((n))\n",
    "for i in range(1, len(sequenceDT)):\n",
    "  LoseMatrix[sequenceDT['label'][i]][sequenceDT['classifier'][i]]+=1\n",
    "  LoseCount[sequenceDT['label'][i]]+= 1\n",
    "LoseMatrix = LoseMatrix / LoseCount\n",
    "\n",
    "fig, ax = plt.subplots()\n",
    "im = ax.imshow(LoseMatrix)\n",
    "columns = [0,1]\n",
    "ax.set_xticks(np.arange(len(columns)))\n",
    "ax.set_yticks(np.arange(len(columns)))\n",
    "ax.set_xticklabels(columns)\n",
    "ax.set_yticklabels(columns)\n",
    "\n",
    "plt.setp(ax.get_xticklabels(), rotation=45, ha=\"right\",\n",
    "         rotation_mode=\"anchor\")\n",
    "\n",
    "for i in range(len(columns)):\n",
    "    for j in range(len(columns)):\n",
    "        text = ax.text(j, i, round(LoseMatrix[i][j],3),\n",
    "                       ha=\"center\", va=\"baseline\", color=\"k\")\n",
    "fig.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Задание"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Теперь ваша задача — обучить модель на своих данных так, чтобы получить максимальную точность на тестовой выборке. Помните, что вы можете экспериментировать не только с параметрами модели, но и с обработкой исходных данных."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "повторная загрузка данных для обучения сети\n",
    "\"\"\"\n",
    "import torch\n",
    "import torchvision\n",
    "from torch.utils import data as D\n",
    "import MPII\n",
    "import convnet\n",
    "\n",
    "root = r'D:\\data_folder' # !!!укажите путь до папки с картинками\n",
    "csv_path = r'D:\\data.csv' # !!!укажите путь до csv разметки\n",
    "\n",
    "batch_size = 15\n",
    "master_dataset = MPII.MPII(root, csv_path)\n",
    "master_len = len(master_dataset)\n",
    "test_len = int(0.1*master_len)\n",
    "train_len = master_len - test_len\n",
    "\n",
    "train_dataset, test_dataset = D.random_split(master_dataset, (train_len, test_len))\n",
    "train_dataloader = D.DataLoader(train_dataset, batch_size = batch_size)\n",
    "test_dataloader = D.DataLoader(test_dataset, batch_size = batch_size)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# !!! блок построения сети, обязательно укажите свои размеры изображений\n",
    "width = 600\n",
    "height = 480\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\n",
    "conv_kernel = 3\n",
    "pooling_kernel = 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",
    "num_classes = 5 # !!! укажите число классов\n",
    "\n",
    "linear1 = num_classes*2\n",
    "linear2 = num_classes\n",
    "linear_params = [linear1, linear2]\n",
    "\n",
    "\"\"\"\n",
    "создаем сеть с указанными выше параметрами для блоков\n",
    "\"\"\"\n",
    "model = convnet.ConvNet(im_size, conv_params, linear_params)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch.optim as optim\n",
    "#!!! здесь можно задать параметры обучения сети\n",
    "\"\"\"\n",
    "Оптимизатор - стохастический градиентный спуск\n",
    "epochs - число эпох обучения\n",
    "\"\"\"\n",
    "learning_rate = 3.2\n",
    "optimizer = optim.SGD(model.parameters(), lr=learning_rate,\n",
    "                     momentum=0.9, nesterov=True)\n",
    "epochs =2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_part34(model, optimizer, device, epochs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# построение матрицы ошибок\n",
    "true_labels =[]\n",
    "predicted_labels =[]\n",
    "model.eval()\n",
    "with torch.no_grad():\n",
    "    for data in test_dataloader:\n",
    "        images, labels = data\n",
    "        images = images.to(device = device, dtype = dtype)\n",
    "        labels = labels.to(device = device, dtype = torch.long)\n",
    "        outputs = model(images)\n",
    "        _, predicted = torch.max(outputs, 1)        \n",
    "        for label in labels:\n",
    "            true_labels.append(label.item())\n",
    "        for pred in predicted:\n",
    "            predicted_labels.append(pred.item())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "d = {'label': true_labels, 'classifier': predicted_labels}\n",
    "sequenceDT = pd.DataFrame(data=d)\n",
    "\n",
    "n=2\n",
    "LoseMatrix = np.zeros((n,n))\n",
    "LoseCount = np.zeros((n))\n",
    "for i in range(1, len(sequenceDT)):\n",
    "  LoseMatrix[sequenceDT['label'][i]][sequenceDT['classifier'][i]]+=1\n",
    "  LoseCount[sequenceDT['label'][i]]+= 1\n",
    "LoseMatrix = LoseMatrix / LoseCount\n",
    "\n",
    "fig, ax = plt.subplots()\n",
    "im = ax.imshow(LoseMatrix)\n",
    "columns = [0,1]\n",
    "ax.set_xticks(np.arange(len(columns)))\n",
    "ax.set_yticks(np.arange(len(columns)))\n",
    "ax.set_xticklabels(columns)\n",
    "ax.set_yticklabels(columns)\n",
    "\n",
    "plt.setp(ax.get_xticklabels(), rotation=45, ha=\"right\",\n",
    "         rotation_mode=\"anchor\")\n",
    "\n",
    "for i in range(len(columns)):\n",
    "    for j in range(len(columns)):\n",
    "        text = ax.text(j, i, round(LoseMatrix[i][j],3),\n",
    "                       ha=\"center\", va=\"baseline\", color=\"k\")\n",
    "fig.tight_layout()\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
}
