2024-11-22 18:03:41 +04:00
{
"cells": [
{
"cell_type": "code",
2024-11-22 20:35:31 +04:00
"execution_count": 45,
2024-11-22 18:03:41 +04:00
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
" ID Price Levy Manufacturer Model Prod. year Category \\\n",
"0 45654403 13328 1399 LEXUS RX 450 2010 Jeep \n",
"1 44731507 16621 1018 CHEVROLET Equinox 2011 Jeep \n",
"2 45774419 8467 - HONDA FIT 2006 Hatchback \n",
"3 45769185 3607 862 FORD Escape 2011 Jeep \n",
"4 45809263 11726 446 HONDA FIT 2014 Hatchback \n",
"\n",
" Leather interior Fuel type Engine volume Mileage Cylinders \\\n",
"0 Yes Hybrid 3.5 186005 km 6.0 \n",
"1 No Petrol 3 192000 km 6.0 \n",
"2 No Petrol 1.3 200000 km 4.0 \n",
"3 Yes Hybrid 2.5 168966 km 4.0 \n",
"4 Yes Petrol 1.3 91901 km 4.0 \n",
"\n",
" Gear box type Drive wheels Doors Wheel Color Airbags \n",
"0 Automatic 4x4 04-May Left wheel Silver 12 \n",
"1 Tiptronic 4x4 04-May Left wheel Black 8 \n",
"2 Variator Front 04-May Right-hand drive Black 2 \n",
"3 Automatic 4x4 04-May Left wheel White 0 \n",
"4 Automatic Front 04-May Left wheel Silver 4 \n",
"Index(['ID', 'Price', 'Levy', 'Manufacturer', 'Model', 'Prod. year',\n",
" 'Category', 'Leather interior', 'Fuel type', 'Engine volume', 'Mileage',\n",
" 'Cylinders', 'Gear box type', 'Drive wheels', 'Doors', 'Wheel', 'Color',\n",
" 'Airbags'],\n",
" dtype='object')\n"
]
}
],
"source": [
"import pandas as pd\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"import seaborn as sns\n",
"import sklearn\n",
"from sklearn.model_selection import train_test_split, GridSearchCV, cross_val_score\n",
"from sklearn.preprocessing import StandardScaler, OneHotEncoder\n",
"from sklearn.compose import ColumnTransformer\n",
"from sklearn.pipeline import Pipeline\n",
"from sklearn.linear_model import LinearRegression, LogisticRegression\n",
"from sklearn.tree import DecisionTreeRegressor, DecisionTreeClassifier\n",
"from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier\n",
"from sklearn.metrics import mean_squared_error, f1_score, accuracy_score, roc_auc_score, confusion_matrix, classification_report\n",
"df = pd.read_csv(\"./static/csv/car_price_prediction.csv\")\n",
"print(df.head())\n",
"print(df.columns)"
]
2024-11-22 20:35:31 +04:00
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Предварительная обработка данных\n",
"Обработка пропущенных значений"
]
},
{
"cell_type": "code",
"execution_count": 46,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"object\n",
"Пропущенные значения после заполнения:\n",
"ID 0\n",
"Price 0\n",
"Levy 0\n",
"Manufacturer 0\n",
"Model 0\n",
"Prod. year 0\n",
"Category 0\n",
"Leather interior 0\n",
"Fuel type 0\n",
"Engine volume 0\n",
"Mileage 0\n",
"Cylinders 0\n",
"Gear box type 0\n",
"Drive wheels 0\n",
"Doors 0\n",
"Wheel 0\n",
"Color 0\n",
"Airbags 0\n",
"dtype: int64\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"C:\\Users\\Egor\\AppData\\Local\\Temp\\ipykernel_21864\\90121908.py:3: FutureWarning: A value is trying to be set on a copy of a DataFrame or Series through chained assignment using an inplace method.\n",
"The behavior will change in pandas 3.0. This inplace method will never work because the intermediate object on which we are setting values always behaves as a copy.\n",
"\n",
"For example, when doing 'df[col].method(value, inplace=True)', try using 'df.method({col: value}, inplace=True)' or df[col] = df[col].method(value) instead, to perform the operation inplace on the original object.\n",
"\n",
"\n",
" df['Levy'].fillna(df['Levy'].median(), inplace=True)\n",
"C:\\Users\\Egor\\AppData\\Local\\Temp\\ipykernel_21864\\90121908.py:21: FutureWarning: A value is trying to be set on a copy of a DataFrame or Series through chained assignment using an inplace method.\n",
"The behavior will change in pandas 3.0. This inplace method will never work because the intermediate object on which we are setting values always behaves as a copy.\n",
"\n",
"For example, when doing 'df[col].method(value, inplace=True)', try using 'df.method({col: value}, inplace=True)' or df[col] = df[col].method(value) instead, to perform the operation inplace on the original object.\n",
"\n",
"\n",
" df['Mileage'].fillna(df['Mileage'].median(), inplace=True)\n",
"C:\\Users\\Egor\\AppData\\Local\\Temp\\ipykernel_21864\\90121908.py:22: FutureWarning: A value is trying to be set on a copy of a DataFrame or Series through chained assignment using an inplace method.\n",
"The behavior will change in pandas 3.0. This inplace method will never work because the intermediate object on which we are setting values always behaves as a copy.\n",
"\n",
"For example, when doing 'df[col].method(value, inplace=True)', try using 'df.method({col: value}, inplace=True)' or df[col] = df[col].method(value) instead, to perform the operation inplace on the original object.\n",
"\n",
"\n",
" df['Engine volume'].fillna(df['Engine volume'].median(), inplace=True)\n",
"C:\\Users\\Egor\\AppData\\Local\\Temp\\ipykernel_21864\\90121908.py:24: FutureWarning: A value is trying to be set on a copy of a DataFrame or Series through chained assignment using an inplace method.\n",
"The behavior will change in pandas 3.0. This inplace method will never work because the intermediate object on which we are setting values always behaves as a copy.\n",
"\n",
"For example, when doing 'df[col].method(value, inplace=True)', try using 'df.method({col: value}, inplace=True)' or df[col] = df[col].method(value) instead, to perform the operation inplace on the original object.\n",
"\n",
"\n",
" df['Mileage'].fillna(df['Mileage'].mean(), inplace=True)\n"
]
}
],
"source": [
"# Очистка столбца 'Levy' от нечисловых значений\n",
"df['Levy'] = pd.to_numeric(df['Levy'], errors='coerce')\n",
"df['Levy'].fillna(df['Levy'].median(), inplace=True)\n",
"\n",
"\n",
"# Очистка столбца 'Mileage' от нечисловых значений\n",
"df['Mileage'] = df['Mileage'].str.replace(' km', '').astype(float)\n",
"df['Mileage'] = pd.to_numeric(df['Mileage'], errors='coerce')\n",
"\n",
"# Проверка типа данных в столбце 'Engine volume'\n",
"print(df['Engine volume'].dtype)\n",
"\n",
"# Если столбец 'Engine volume' не является строковым, преобразуем е г о в строку\n",
"if df['Engine volume'].dtype != 'object':\n",
" df['Engine volume'] = df['Engine volume'].astype(str)\n",
"\n",
"# Очистка столбца 'Engine volume' от нечисловых значений\n",
"df['Engine volume'] = df['Engine volume'].str.replace(r'[^0-9.]', '', regex=True).astype(float)\n",
"\n",
"# Заполнение пропущенных значений\n",
"df['Mileage'].fillna(df['Mileage'].median(), inplace=True)\n",
"df['Engine volume'].fillna(df['Engine volume'].median(), inplace=True)\n",
"\n",
"df['Mileage'].fillna(df['Mileage'].mean(), inplace=True)\n",
"\n",
"# Проверка на наличие NaN после заполнения\n",
"print(\"Пропущенные значения после заполнения:\")\n",
"print(df.isnull().sum())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Кодирование категориальных переменных"
]
},
{
"cell_type": "code",
"execution_count": 47,
"metadata": {},
"outputs": [],
"source": [
"from sklearn.calibration import LabelEncoder\n",
"\n",
"le = LabelEncoder()\n",
"categorical_cols = ['Manufacturer', 'Model', 'Category', 'Leather interior',\n",
" 'Fuel type', 'Gear box type', 'Drive wheels', 'Doors',\n",
" 'Wheel', 'Color']\n",
"for col in categorical_cols:\n",
" df[col] = le.fit_transform(df[col].astype(str))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Масштабирование признаков\n",
"#### Понижение размерности - PCA\n",
"#### Визуализация PCA\n",
"\n",
"Данные распределены вдоль оси X (Главный компонент 1) с некоторым разбросом вдоль оси Y (Главный компонент 2).\n",
"\n",
"Большая часть дисперсии в данных объясняется первой главной компонентой.\n",
"\n",
"Возможно, данные содержат несколько кластеров, которые можно идентифицировать с помощью кластерного анализа."
]
},
{
"cell_type": "code",
"execution_count": 48,
"metadata": {},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAj4AAAHHCAYAAAC/R1LgAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjkuMiwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8hTgPZAAAACXBIWXMAAA9hAAAPYQGoP6dpAAB4w0lEQVR4nO3deVhUZfsH8O+wD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q2hoKLp27YoGDRrgxx9/VHt89erVaNy4MTw9PVGlShUEBwdj27ZtWttnjO+//x7nzp3TOWQXGxuLn3/+GZs2bUJaWhru37+PvLw80cdXBhn+/v4G95VyrlOnTlVdUJU/Fy5c0HrcoUOHauz76NEjrft27doVwcHB8PPzQ+XKlfHOO+/o3Fdp3rx5CAwMxKlTp/DFF18gJCTE4LlKcf36ddSpU0fjJqBBgwaqxwHg6tWrqFatGgIDAw0eUzn9W9/3+fLly9ixY4fGe9e1a1cApXlHhtSqVQu7d+/Gnj17cPjwYaSnp+O3335TDa/5+fkBgOhAEyidzRUREQG5XI4rV67gypUrqF27Nry9vTlhwoEwx4cchouLCzp37oyFCxfi8uXLaNiwodrju3btwp49e1QJyNp4eHhg9+7dyMvLw6FDhzB79myEh4fjrbfeUu0zePBgjBkzBjdv3kRBQQGOHTuGxYsXqx3npZdewtGjRzF+/Hg0bdoUvr6+UCgU6N69u0byZmZmJgoLC1XTZw25f/8
"text/plain": [
"<Figure size 640x480 with 1 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"from pyexpat import features\n",
"from sklearn.decomposition import PCA\n",
"\n",
"features = df.drop(['ID', 'Price'], axis=1)\n",
"\n",
"# Масштабирование признаков\n",
"scaler = StandardScaler()\n",
"X_scaled = scaler.fit_transform(features)\n",
"\n",
"# Проверка на наличие NaN после масштабирования\n",
"if np.isnan(X_scaled).any():\n",
" raise ValueError(\"В масштабированных данных все еще присутствуют NaN.\")\n",
"\n",
"# Понижение размерности - PCA\n",
"pca = PCA(n_components=2)\n",
"X_pca = pca.fit_transform(X_scaled)\n",
"\n",
"# Визуализация PCA\n",
"plt.scatter(X_pca[:, 0], X_pca[:, 1])\n",
"plt.xlabel('Главный компонент 1')\n",
"plt.ylabel('Главный компонент 2')\n",
"plt.title('Визуализация данных после PCA')\n",
"plt.show()\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Выбор количества кластеров\n",
"\n",
"#### График локтя"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAlYAAAHHCAYAAAB9dxZkAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjkuMiwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8hTgPZAAAACXBIWXMAAA9hAAAPYQGoP6dpAAByzklEQVR4nO3deVhUZf8G8HtmgAEEBpFdVsUNccUNzUxFUcncSnPLJcsULZdMrdzqV6QtVmq2Y1mupaZmKm6YhuKGiihuKKgsIjLs6zy/P3yZHAEFGjgD3J/rOtf7zjnPnPmeAzS3z3nOc2RCCAEiIiIi+s/kUhdAREREVFswWBERERHpCYMVERERkZ4wWBERERHpCYMVERERkZ4wWBERERHpCYMVERERkZ4wWBERERHpCYMVERERkZ4wWBERERHpCYMVERFRNVqzZg1kMhlOnjwpdSlUBRisiPDvf+hkMhmOHDlSYrsQAq6urpDJZHj22WclqJCIiGoCBiuih5iammLdunUl1oeFheHWrVtQKpUSVEVERDUFgxXRQwYMGIDNmzejsLBQZ/26devg6+sLR0dHiSojIqKagMGK6CEjR47EvXv3EBoaql2Xn5+P3377DaNGjSr1PRqNBp9//jlatmwJU1NTODg4YPLkybh//762jYeHh/ZSY2mLh4eHtm1WVhZmz54NV1dXKJVKNGvWDJ988gmEECU++9ChQ2Xus7zGjx9f6vsXL16s0+7AgQPo3r076tWrB2trawwaNAgXL17UabN48eISn33w4EEolUq89tprOm0etxw6dEj7/tWrV8PHxwfm5uY6bX777bdyHd8zzzxTruMDdC8JP7w888wzOu3OnDmDfv36wc7OTqddeS4Tl/fnW57flxs3bjzxXI4fP17n2G7cuKH9DI1Gg9atW0Mmk2HNmjXa9cW/E23bti1Rf3BwMGQyGSwsLHTWh4SEoFevXrC3t4dSqYS3tzdWr15d6jko6/f24b+D4jZP+jkX/z6lpKTorD958mSJ4wIq9nv86GJkZKTTbvPmzfD19YWZmRlsbW0xZswY3L59+7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ypcuXcJff/2F4cOHY/bs2QgJCanUfmbOnImYmBi8//77WLJkSYXfn5+fj4SEBPTp06dc7RMTE2FhYYF69eqV2cbd3R0hISF444030L59e51trVu3rnCNUli6dCnkcjnmzJmDe/fuldnO2NgYY8aMQUhICLKzs9GgQQP06tVLZwwXAFy7dg29e/dG8+bN8dlnn8HV1RUmJibYtWsXli9fXiJ0JiYmAkC57rJduHAhunfvjoKCApw6dQrvvfce0tLSSvQw/f7777CystK+vnz5cpljuwzF0KFD8fPPP+OLL77QjgGkmo/BiqgUQ4YMweTJk3Hs2DFs3LixzHaNGzfGvn370K1bN51LIZXl7u6Offv2ISMjQ6dX49KlS9rtDzt58iQcHR3h4uJSqc8rKCjA1atX0a9fv8fWBKDUO5UuXboEW1vbEkFk+/bt6N69O4KDgzFt2jSMGTMGvXv3rnB9ZmZm+O6773DmzBmoVCosWrQIZ8+exZtvvlmu9589exYFBQXo0KFDudpHR0dre48eZ/To0YiLi8OSJUuwdu1a1K9fH2PGjHni+yr6860Kd+7c0X6RW1paPjZYAQ96jNq0aYP4+HiMGzeu1DtOd+zYgby8PGzfvh1ubm7a9WVdCo+OjoadnV25Lqe2atVK2/vUv39/xMXF4aeffkJhYaHOXXpPP/209oYDACX+MVSZ3+OyPLyvXr166WyLiYkp989x+vTp8PLywsKFC6FSqTBv3rxyvY8MGy8FEpXCwsICq1evxuLFizFw4MAy2w0fPhx
"text/plain": [
"<Figure size 640x480 with 1 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"\n",
"from sklearn.cluster import KMeans\n",
"from sklearn.metrics import silhouette_score\n",
"\n",
"\n",
"inertia = []\n",
"silhouette = []\n",
"for k in range(2, 11):\n",
" kmeans = KMeans(n_clusters=k, random_state=42)\n",
" kmeans.fit(X_scaled)\n",
" inertia.append(kmeans.inertia_)\n",
" silhouette.append(silhouette_score(X_scaled, kmeans.labels_))\n",
"\n",
"plt.plot(range(2, 11), inertia, marker='o')\n",
"plt.xlabel('Количество кластеров (k)')\n",
"plt.ylabel('Инерция')\n",
"plt.title('Метод локтя для оптимального k')\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### График силуэта"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAkAAAAHHCAYAAABXx+fLAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjkuMiwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8hTgPZAAAACXBIWXMAAA9hAAAPYQGoP6dpAABxeUlEQVR4nO3deVxU5f4H8M8wrDLDviMKyCaiuC951VJMTU3T0szdm3VLU/PWLfWmab+y1MxMM23BFivT0tRKU3Mpr4ob7qIiirIjAgPINvP8/sCZGNlmcOAA83m/XvMSzjlz5nsOOPPleb7P88iEEAJEREREZsRC6gCIiIiI6hsTICIiIjI7TICIiIjI7DABIiIiIrPDBIiIiIjMDhMgIiIiMjtMgIiIiMjsMAEiIiIis8MEiIiIiMwOEyAiIqJG7s0334RMJkNmZqbUoTQaTIAI69evh0wmw/Hjxyvs+/TTTyGTyTB8+HCo1ep6iWfIkCHw9/c3+nnTp0+HTCYzfUBERNTkMAGiKm3ZsgUvvPACevXqhe+//x5yuVzqkIiIiEyCCRBVav/+/RgzZgzCw8Oxfft22NraSh0SERGRyTABogpiY2MxbNgweHt7Y9euXXB0dKxwzKZNm9CpUyfY2dnBzc0N48aNQ1JSkm5/UlISxowZA19fX9jY2CAwMBD/+c9/oFKpKpzr66+/hp+fH5ycnLB48WLd9o0bN8LHxwdubm547733Kjxv165dCAkJgUKhwIwZMyCEAFCWvLVq1QoODg6YPXu2Xtfd/v37IZPJsH//fr1zDR48GDKZDG+++aZuW1V96sePH4dMJsP69et1265fv15hGwBMmzYNMpkMkyZN0tuenZ2NWbNmwc/PDzY2NggKCsJ7770HjUZT4ZzLli2rcO0RERF4+OGH9a6pukf566pMYWEh3nzzTYSEhMDW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+ZMvePHjBmDxx57TG9b+f8fD/r79P7771f5YWtra4tffvkF6enp8PDw0MW/cePGSluZP/zwQzz++OMYO3YsiouL8f333+Opp57Cjh07MHjw4Epf44MPPoCbmxsA4O23364yTlMx5P1Qy8bGBp999pne85VKpe7rN998EwsXLkRUVBReeOEFxMXFYc2aNTh27BgOHToEKysrg+OKj49H37594eLigt27d+vuCZUjyOxFR0cLAGLHjh2iVatWAoB49NFHKz22uLhYeHh4iIiICHH37l3d9h07dggAYv78+VW+zu7duwUAsWjRIt22xx9/XAQEBIjCwkIhhBAqlUoEBASIZs2aiWvXrgkhhNBoNKJnz54iMjJS97wZM2YIpVIpMjMzhRBClJSUiO7duwsA4ujRo7rjxowZIzw8PHTn37dvnwAg9u3bpzumW7duYtCgQQKAWLBggW77ggULBACRkZGhdx3Hjh0TAER0dLRuW0JCQoVto0aNEhEREcLPz09MnDhRt/2tt94S9vb24vLly3rnff3114VcLheJiYl651y6dGmFe9mmTRvRp0+fCtuFEGLixImiZcuWle6rzBdffCEAiOXLl1fYp9FojL4+rZ49e4pHHnlE931l5+jRo4fo1q2b3vN++umnCj+j+82bN08AEAcPHqywr7LXKa+goKDCtgEDBojAwMAqX+9+Pj4+YsiQIbrvK/udKB+rTCbT29ayZUu9e7Z27VoBQBw+fFjvOABi2rRp1cayYsUKAUB88803um3FxcWiR48eQqFQiNzcXCFE3fw+af+PaKWnpwulUqn7/1T+Z9inTx/Rpk0b0a5dO7Fs2TLd9q+//lo0b95c9OrVS7Rp00bv/Pf/rIqLi0VERITo27dvhVg+/fRTAUDcuHFD7zXLX5f2ve7YsWOVXk/5a7a3t6+wfdOmTXrXZcz7YVXn1EpPTxfW1tbi0UcfFWq1Wrd91apVAoD44osvqo25/PvVxYsXhY+Pj+jSpYvIysqq9nnmjF1gpDNp0iTcvHkTzzzzDH7//Xds2rSpwjHHjx9Heno6XnzxRb2/2AYPHoywsDD88ssvum0lJSXIzMzUPdq3b4/OnTvrnXfv3r147LHHYGNjAwBQKBQIDw+Hu7s7AgICAEDXbH769Gncvn1b97zevXvD1dUVAGBpaYlOnToBALp27ao7/4gRI5Ceno5z585Ves0//fQTjh07hnfffbdW96wqJ06cwKZNm7B48WJYWOj/N9u0aZOuq6P8/YmKioJarcbBgwf1ji8oKNA7LjMz06Qj8n788Ue4ubnhpZdeqrCvqlF11V2fVnFxse7nWpUJEybg6NGjuq42ANiwYQP8/PzQp08f3bb778HUqVNhZWVV6e9oTbStjwCQk5ODzMxM9OnTB9euXUNOTo5B5ygsLDS4Ls6Q+6DtGtb+Phvj119/hZeXl651FACsrKwwY8YM5OXl4cCBA0afs7beeustODo6YsaMGVUeM3nyZERHR+u+j46OxsSJEyv9PSr/s7pz5w5ycnLQq1cvnDx5ssKxxcXFAFDjvQb+/rlX1iVf3v3/7+4/3pj3w5rs2bMHxcXFmDVrlt69mDp1KhwcHAw+17lz59CnTx/4+/tjz549cHZ2NjgGc8MEiHSysrLwzTff4Msvv0T79u0xc+bMCh8IN27cAACEhoZWeH5YWJhuP1DWveXu7q73OH78OK5evQqg7A0tPz8fvr6+NcamPebmzZu6f2vzvPLUajXmzp2LsWPHVtukXxuvv/46evXqhSFDhlTYd+XKFezcubPCvYmKigJQVs9R3oIFCyoce+nSJZPFGh8fj9DQUFhaGt4jXt31aWVnZ1daR1He6NGjYWNjgw0bNgAo+2DasWMHxo4dq5d8LVmyRO/6/f39UVJSovtdMsahQ4cQFRUFe3t7ODk5wd3dHXPnztW9fk3UajWys7MrrY2rjCH3oUePHgCAV199FRcvXtR94Brixo0bCA4OrpBAtG7dWre/PiQkJGDt2rVYuHBhtcnh2LF
"text/plain": [
"<Figure size 640x480 with 1 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"\n",
"plt.plot(range(2, 11), silhouette, marker='o')\n",
"plt.xlabel('Количество кластеров (k)')\n",
"plt.ylabel('Коэффициент силуэта')\n",
"plt.title('Коэффициент силуэта для оптимального k')\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Предположим, что оптимальное k равно 3 на основе графиков\n",
"\n",
"#### Иерархическая кластеризация\n",
"\n",
"\n",
"#### K-Means кластеризация\n",
"\n",
"#### Оценка качества кластеризации"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Коэффициент силуэта (Agg): 0.13306117230156736\n",
"Индекс Дэвиса-Болдина (Agg): 2.5089898754817166\n",
"Коэффициент силуэта (KMeans): 0.17159548190302554\n",
"Индекс Дэвиса-Болдина (KMeans): 2.23429912220393\n"
]
}
],
"source": [
"\n",
"from sklearn.cluster import AgglomerativeClustering\n",
"from sklearn.metrics import davies_bouldin_score\n",
"\n",
"\n",
"agg_clustering = AgglomerativeClustering(n_clusters=3, linkage='ward')\n",
"labels_agg = agg_clustering.fit_predict(X_scaled)\n",
"\n",
"kmeans = KMeans(n_clusters=3, random_state=42)\n",
"labels_kmeans = kmeans.fit_predict(X_scaled)\n",
"\n",
"\n",
"silhouette_agg = silhouette_score(X_scaled, labels_agg)\n",
"davies_bouldin_agg = davies_bouldin_score(X_scaled, labels_agg)\n",
"\n",
"silhouette_kmeans = silhouette_score(X_scaled, labels_kmeans)\n",
"davies_bouldin_kmeans = davies_bouldin_score(X_scaled, labels_kmeans)\n",
"\n",
"print(f\"Коэффициент силуэта (Agg): {silhouette_agg}\")\n",
"print(f\"Индекс Дэвиса-Болдина (Agg): {davies_bouldin_agg}\")\n",
"print(f\"Коэффициент силуэта (KMeans): {silhouette_kmeans}\")\n",
"print(f\"Индекс Дэвиса-Болдина (KMeans): {davies_bouldin_kmeans}\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Визуализация кластеров"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAj4AAAHHCAYAAAC/R1LgAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZl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ZWXx6KOP0rx5c0wmU7HXnZSU5PZ98nafV199FU3TmDFjhtvX4O6jqLfeeovevXsTHR1NYGAg3bp189ilMm3aNHr06EFQUBCRkZH069ePX375BfD8tSz8KPq10nWd9957j/bt2xMQEEB8fDx33nknqampxe7XtGlTLr30Un755Rc6d+5MQEAA7dq1Y968eSVi27dvH9dccw1RUVEEBQXRq1cvFi1aVOyYVatWFYvJYrFwzjnnMHHiRJ8ezgsWLGDQoEEl3sOi1q5dyyWXXELLli1ZtmwZ0dHRpV4XYNSoUcyaNQtd113bfvjhB3Jycrj22mvdnnP06FFuueUW4uPjsVgstG/fnq+++qrYMWX5nv/ss89o0aIFFouF7t27s2HDhmLHnjhxgnHjxtGoUSMsFgv169fniiuu4MCBA8WOu/DCCzl48CCbNm3y6T1Qqp+x9EMUpeqlp6eTlJSElJJTp07xwQcfkJWVxY033uj1vD179vD555+X2J6RkUHPnj25+eabMZlMLFmyhPHjx2M0Gnn00UcZMGAACQkJTJ8+nZEjRxY7d/r06bRo0YLzzz8fcI5H2LdvH+PGjaNevXps27aNzz77jG3btvHHH3+4fWD07duXO+64A4AdO3bw2muveX0ddrudZ555psT27OxsGjVqxGWXXUZYWBhbt27lo48+4ujRo/zwww+u1/rFF18watQobr/9djIzM/nyyy8ZOnQof/75J507d/Z6b388+eSTbrc//vjj/O9//+PWW2+lT58+mEwm5s2b5zaxLM3kyZN59tlnefvttxk9erTbY+644w769u0L4PY+77//Ppdffjk33HADeXl5fPvtt1xzzTX8+OOPxVoaJkyYwIsvvkjv3r156aWXMJvNrF+/nhUrVnDRRRfx3nvvkZWVBZz+Oj799NO0bdsWgJCQENe17rzzTqZMmcK4ceN44IEH2L9/Px9++CH//PMPv/32GyaTyXXs7t27ue6667jrrru4+eabmTx5Mtdccw1LlizhwgsvBODkyZP07t2bnJwcHnjgAaKjo/n666+5/PLLmTNnTonv28K4cnNzmTVrFk8//TRxcXHceuutHt/ro0ePcujQIbp27erxmN9++43hw4fTrFkzli9fTkxMjMd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MzPS5+8OTP//8k2uvvZarrrqKN9980+0xeXl5AKW+v0W/ZqmpqaSnp9O3b99i78eCBQvQdZ3nn3++xPePt24fd2bPnk14eDgXXnghSUlJro9u3boREhJSogumQYMGxVpswsLCGDNmDP/8849rxtDixYvp0aMHF1xwgeu4kJAQ7rjjDg4cOMD27duLXbOw1fTQoUNMmjQJXdddrSyeFHbXRkZGut2fnZ1NZmYm8fHxhIWF+f6GFDF69GjmzZtHXl4ec+bMwWAwlGitAuf32Ny5c7nsssuQUhZ7H4cOHUp6errr6+fv9/x1111X7DUWthbu27cPcH6/mM1mVq1aVaJr0p3IyMhSu3CVmkMlPkqN1KNHD4YMGcKQIUO44YYbWLRoEe3ateO+++5zPezONH78ePr27cull17qdr/VaiU2NpaEhARuueUWHn/8cR5//HHX/jZt2tC9e3emT5/u2jZ9+nR69epFy5YtXdtSUlJ48MEHiY+PJzAwkNjYWJo1awY4HzZnSk9PL9YFUpp33nkHq9XK008/7fGYoUOHUq9ePYYMGULbtm2ZNWtWsf1ff/01nTp1IiAggOjoaGJjY1m0aJHb+Mpi+vTpbNu2zWOX3fnnn8/8+fO
"text/plain": [
"<Figure size 640x480 with 1 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"\n",
"plt.scatter(X_pca[:, 0], X_pca[:, 1], c=labels_kmeans)\n",
"plt.xlabel('Главный компонент 1')\n",
"plt.ylabel('Главный компонент 2')\n",
"plt.title('Визуализация кластеров (K-Means)')\n",
"plt.show()"
]
2024-11-22 18:03:41 +04:00
}
],
"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.12.5"
}
},
"nbformat": 4,
"nbformat_minor": 2
}