{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": [],
      "gpuType": "T4"
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    },
    "accelerator": "GPU"
  },
  "cells": [
    {
      "cell_type": "markdown",
      "source": [
        "**Пункт 1**"
      ],
      "metadata": {
        "id": "KR8uP1u_tFii"
      }
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "v8fjN3CMpmzp"
      },
      "outputs": [],
      "source": [
        "import os\n",
        "os.chdir('/content/drive/MyDrive/Colab Notebooks/IS_LR3')"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# импорт модулей\n",
        "from tensorflow import keras\n",
        "from tensorflow.keras import layers\n",
        "from tensorflow.keras.models import Sequential\n",
        "import matplotlib.pyplot as plt\n",
        "import numpy as np\n",
        "from sklearn.metrics import classification_report, confusion_matrix\n",
        "from sklearn.metrics import ConfusionMatrixDisplay"
      ],
      "metadata": {
        "id": "VMuk53SHqFE6"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "**Пункт 2**"
      ],
      "metadata": {
        "id": "bie8IdvhtMwI"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# загрузка датасета\n",
        "from keras.datasets import cifar10\n",
        "\n",
        "(X_train, y_train), (X_test, y_test) = cifar10.load_data()"
      ],
      "metadata": {
        "id": "zU_qTq3QpSaj"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "**Пункт 3**"
      ],
      "metadata": {
        "id": "EKz2pMH5tPgM"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# создание своего разбиения датасета\n",
        "from sklearn.model_selection import train_test_split\n",
        "\n",
        "# объединяем в один набор\n",
        "X = np.concatenate((X_train, X_test))\n",
        "y = np.concatenate((y_train, y_test))\n",
        "\n",
        "# разбиваем по вариантам\n",
        "X_train, X_test, y_train, y_test = train_test_split(X, y,\n",
        "                                                    test_size = 10000,\n",
        "                                                    train_size = 50000,\n",
        "                                                    random_state = 15)"
      ],
      "metadata": {
        "id": "Tj2SdIX6qjyS"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# вывод размерностей\n",
        "print('Shape of X train:', X_train.shape)\n",
        "print('Shape of y train:', y_train.shape)\n",
        "\n",
        "print('Shape of X test:', X_test.shape)\n",
        "print('Shape of y test:', y_test.shape)"
      ],
      "metadata": {
        "id": "rxfIoGknpVr2"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# вывод 25 изображений из обучающей выборки с подписями классов\n",
        "class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer',\n",
        "               'dog', 'frog', 'horse', 'ship', 'truck']\n",
        "\n",
        "plt.figure(figsize=(10,10))\n",
        "for i in range(25):\n",
        "    plt.subplot(5,5,i+1)\n",
        "    plt.xticks([])\n",
        "    plt.yticks([])\n",
        "    plt.grid(False)\n",
        "    plt.imshow(X_train[i])\n",
        "    plt.xlabel(class_names[y_train[i][0]])\n",
        "plt.show()"
      ],
      "metadata": {
        "id": "ELkzGpxQpYss"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "**Пункт 4**"
      ],
      "metadata": {
        "id": "R8UnsPwFtcT6"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# Зададим параметры данных и модели\n",
        "num_classes = 10\n",
        "input_shape = (32, 32, 3)\n",
        "\n",
        "# Приведение входных данных к диапазону [0, 1]\n",
        "X_train = X_train / 255\n",
        "X_test = X_test / 255\n",
        "\n",
        "# Расширяем размерность входных данных, чтобы каждое изображение имело\n",
        "# размерность (высота, ширина, количество каналов)\n",
        "\n",
        "\n",
        "print('Shape of transformed X train:', X_train.shape)\n",
        "print('Shape of transformed X test:', X_test.shape)\n",
        "\n",
        "# переведем метки в one-hot\n",
        "y_train = keras.utils.to_categorical(y_train, num_classes)\n",
        "y_test = keras.utils.to_categorical(y_test, num_classes)\n",
        "print('Shape of transformed y train:', y_train.shape)\n",
        "print('Shape of transformed y test:', y_test.shape)"
      ],
      "metadata": {
        "id": "tLtI_dWgpb5Q"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "**Пункт 5**"
      ],
      "metadata": {
        "id": "OQTGDyuytpyz"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# создаем модель\n",
        "model = Sequential()\n",
        "model.add(layers.Conv2D(32, kernel_size=(3, 3), activation=\"relu\", input_shape=input_shape))\n",
        "model.add(layers.MaxPooling2D(pool_size=(2, 2)))\n",
        "model.add(layers.Conv2D(64, kernel_size=(3, 3), activation=\"relu\"))\n",
        "model.add(layers.MaxPooling2D(pool_size=(2, 2)))\n",
        "model.add(layers.Conv2D(128, kernel_size=(3, 3), activation=\"relu\"))\n",
        "model.add(layers.MaxPooling2D(pool_size=(2, 2)))\n",
        "model.add(layers.Flatten())\n",
        "model.add(layers.Dense(128, activation='relu'))\n",
        "model.add(layers.Dropout(0.5))\n",
        "model.add(layers.Dense(num_classes, activation=\"softmax\"))\n",
        "\n",
        "model.summary()"
      ],
      "metadata": {
        "id": "fchBhH0mpffb"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "batch_size = 512\n",
        "epochs = 15\n",
        "model.compile(loss=\"categorical_crossentropy\", optimizer=\"adam\", metrics=[\"accuracy\"])\n",
        "model.fit(X_train, y_train, batch_size=batch_size, epochs=epochs, validation_split=0.1)"
      ],
      "metadata": {
        "id": "pt4hPpfLpiAR"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "**Пункт 6**"
      ],
      "metadata": {
        "id": "CyI5uGgetwim"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# Оценка качества работы модели на тестовых данных\n",
        "scores = model.evaluate(X_test, y_test)\n",
        "print('Loss on test data:', scores[0])\n",
        "print('Accuracy on test data:', scores[1])"
      ],
      "metadata": {
        "id": "niQVFBRnpklL"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "**Пункт 7**"
      ],
      "metadata": {
        "id": "-Os4bCnAtzCP"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# ПРАВИЛЬНО распознанное изображение\n",
        "n = 10\n",
        "result = model.predict(X_test[n:n+1])\n",
        "print('NN output:', result)\n",
        "\n",
        "plt.imshow(X_test[n])\n",
        "plt.show()\n",
        "\n",
        "print('Real class: ', np.argmax(y_test[n]), '->', class_names[np.argmax(y_test[n])])\n",
        "print('NN answer:', np.argmax(result), '->', class_names[np.argmax(result)])"
      ],
      "metadata": {
        "id": "oLC2nN-MpnVD"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# НЕВЕРНО распознанное изображение\n",
        "n = 0\n",
        "result = model.predict(X_test[n:n+1])\n",
        "print('NN output:', result)\n",
        "\n",
        "plt.imshow(X_test[n])\n",
        "plt.show()\n",
        "\n",
        "print('Real class: ', np.argmax(y_test[n]), '->', class_names[np.argmax(y_test[n])])\n",
        "print('NN answer:', np.argmax(result), '->', class_names[np.argmax(result)])"
      ],
      "metadata": {
        "id": "qMkBgHiqppyZ"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "**Пункт 8**"
      ],
      "metadata": {
        "id": "RVk_bSDct3Km"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# истинные метки классов\n",
        "true_labels = np.argmax(y_test, axis=1)\n",
        "\n",
        "# предсказанные метки классов\n",
        "predicted_labels = np.argmax(model.predict(X_test), axis=1)\n",
        "\n",
        "# отчет о качестве классификации\n",
        "print(classification_report(true_labels, predicted_labels, target_names=class_names))\n",
        "\n",
        "# вычисление матрицы ошибок\n",
        "conf_matrix = confusion_matrix(true_labels, predicted_labels)\n",
        "\n",
        "# отрисовка матрицы ошибок в виде \"тепловой карты\"\n",
        "display = ConfusionMatrixDisplay(confusion_matrix=conf_matrix,\n",
        "                                 display_labels=class_names)\n",
        "display.plot(xticks_rotation=45)\n",
        "plt.show()"
      ],
      "metadata": {
        "id": "isaoRHSXpLSA"
      },
      "execution_count": null,
      "outputs": []
    }
  ]
}