{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Accuracy: 93.33333333333333%\n"
     ]
    }
   ],
   "source": [
    "# ВСР 2.2 Классификация цветов Ирисов\n",
    "\n",
    "using RDatasets, StatsBase, Random\n",
    "\n",
    "Random.seed!(123) # Определение последующих случайных чисел\n",
    "\n",
    "df = dataset(\"datasets\", \"iris\") # Загрузка набора данных\n",
    "\n",
    "x = Matrix(df[:, 1:4])\n",
    "species = df[:, :Species]\n",
    "\n",
    "species_map = Dict(\"setosa\" => 0, \"versicolor\" => 1, \"virginica\" => 2) # Создание словаря для перевода названий в числа\n",
    "\n",
    "y_numeric = [species_map[s] for s in species]\n",
    "\n",
    "x_len = size(df, 1) # Количество строк в матрице x\n",
    "train_size = floor(Int, x_len * 0.7) # Размер обучающей выборки\n",
    "\n",
    "shuffle_def = shuffle(1:x_len)\n",
    "\n",
    "x_train = x[shuffle_def[1:train_size], :] # Разделение данных на обучающую и тестовую выборки\n",
    "x_test = x[shuffle_def[train_size+1:end], :]\n",
    "y_train = y_numeric[shuffle_def[1:train_size]]\n",
    "y_test = y_numeric[shuffle_def[train_size+1:end]]\n",
    "\n",
    "\n",
    "k = 4  # k ближайщих соседей\n",
    "\n",
    "y_pred = []\n",
    "\n",
    "for x in eachrow(x_test)\n",
    "    distances = [sum((x_train[i, :] .- x).^2) for i in 1:size(x_train, 1)] # Вычисление расстояние между x и каждым элементом x_train\n",
    "    sorted_indices = sortperm(distances)[1:k] # Сортировка по возрастанию ближайщих k соседей\n",
    "    nearest_labels = y_train[sorted_indices]\n",
    "    predicted_label = mode(nearest_labels) # Выбираем самый часто встречающийся вид среди k соседей\n",
    "    push!(y_pred, predicted_label)\n",
    "end\n",
    "\n",
    "accuracy = mean(y_test .== y_pred)\n",
    "println(\"Accuracy: \", accuracy * 100, \"%\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Julia 1.10.5",
   "language": "julia",
   "name": "julia-1.10"
  },
  "language_info": {
   "file_extension": ".jl",
   "mimetype": "application/julia",
   "name": "julia",
   "version": "1.10.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
