{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "YVAZkjYZu7Tp"
      },
      "source": [
        "#### Загрузка данных"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "eqUQyj22pEUP",
        "outputId": "38936c5b-aaca-4131-e8e0-51dc39fe2345"
      },
      "outputs": [
        {
          "data": {
            "text/html": [
              "<div>\n",
              "<style scoped>\n",
              "    .dataframe tbody tr th:only-of-type {\n",
              "        vertical-align: middle;\n",
              "    }\n",
              "\n",
              "    .dataframe tbody tr th {\n",
              "        vertical-align: top;\n",
              "    }\n",
              "\n",
              "    .dataframe thead th {\n",
              "        text-align: right;\n",
              "    }\n",
              "</style>\n",
              "<table border=\"1\" class=\"dataframe\">\n",
              "  <thead>\n",
              "    <tr style=\"text-align: right;\">\n",
              "      <th></th>\n",
              "      <th>Height</th>\n",
              "      <th>Weight</th>\n",
              "    </tr>\n",
              "  </thead>\n",
              "  <tbody>\n",
              "    <tr>\n",
              "      <th>0</th>\n",
              "      <td>167.0812</td>\n",
              "      <td>51.242630</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>1</th>\n",
              "      <td>181.6608</td>\n",
              "      <td>61.900227</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>2</th>\n",
              "      <td>176.2760</td>\n",
              "      <td>69.401361</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>3</th>\n",
              "      <td>173.2788</td>\n",
              "      <td>64.553288</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>4</th>\n",
              "      <td>172.1866</td>\n",
              "      <td>65.442177</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>...</th>\n",
              "      <td>...</td>\n",
              "      <td>...</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>195</th>\n",
              "      <td>167.1320</td>\n",
              "      <td>54.802721</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>196</th>\n",
              "      <td>167.9194</td>\n",
              "      <td>52.507937</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>197</th>\n",
              "      <td>173.3296</td>\n",
              "      <td>58.185941</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>198</th>\n",
              "      <td>172.7708</td>\n",
              "      <td>57.809524</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>199</th>\n",
              "      <td>181.3306</td>\n",
              "      <td>57.995465</td>\n",
              "    </tr>\n",
              "  </tbody>\n",
              "</table>\n",
              "<p>200 rows × 2 columns</p>\n",
              "</div>"
            ],
            "text/plain": [
              "       Height     Weight\n",
              "0    167.0812  51.242630\n",
              "1    181.6608  61.900227\n",
              "2    176.2760  69.401361\n",
              "3    173.2788  64.553288\n",
              "4    172.1866  65.442177\n",
              "..        ...        ...\n",
              "195  167.1320  54.802721\n",
              "196  167.9194  52.507937\n",
              "197  173.3296  58.185941\n",
              "198  172.7708  57.809524\n",
              "199  181.3306  57.995465\n",
              "\n",
              "[200 rows x 2 columns]"
            ]
          },
          "execution_count": 2,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "import pandas as pd\n",
        "\n",
        "\n",
        "df = pd.read_csv(\"data/wh_data.csv\", index_col=0)\n",
        "df"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "HquD4-wzvz6-"
      },
      "source": [
        "#### Обучение модели линейной регрессии"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "4OYkFByZvHyD",
        "outputId": "1a76004f-fe0c-4490-e2b0-616a05ee9462"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "'weight = -48.08512764117069 + 0.6129012675686306 * height'"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "from sklearn import linear_model\n",
        "\n",
        "\n",
        "num_records = df.shape[0]\n",
        "X = df[\"Height\"].to_numpy().reshape(num_records, 1)\n",
        "y = df[\"Weight\"].to_numpy().reshape(num_records, 1)\n",
        "\n",
        "model = linear_model.LinearRegression().fit(X, y)\n",
        "display(f\"weight = {model.intercept_[0]} + {model.coef_.T[0][0]} * height\") # type: ignore"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "1B2CgY0Ev9ZD"
      },
      "source": [
        "В среднем на каждый килограмм приходится 0,6 см роста."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "3eJTKdzLykXV"
      },
      "source": [
        "#### Оценка ошибки работы модели"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "3p-VQkfPyVsB",
        "outputId": "4e6b99b2-fdfd-414b-d636-90d03554de8c"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "'MAE = 3.518701759813252'"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "from sklearn import metrics\n",
        "\n",
        "\n",
        "y_pred = model.predict(X)\n",
        "mae = metrics.mean_absolute_error(y, y_pred)\n",
        "display(f\"MAE = {mae}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "JrLR5nEmytq4"
      },
      "source": [
        "В среднем предсказание отстает от фактического значения на 3,5 кг."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "#### Визуализация результатов"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 5,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 466
        },
        "id": "r0TbhuiBy6KI",
        "outputId": "343af02b-1447-4186-fc4a-05c83ede1fd2"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "Text(0, 0.5, 'Вес, кг')"
            ]
          },
          "execution_count": 5,
          "metadata": {},
          "output_type": "execute_result"
        },
        {
          "data": {
            "image/png": "[encoded data, 38376 characters]",
            "text/plain": [
              "<Figure size 640x480 with 1 Axes>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "import matplotlib.pyplot as plt\n",
        "\n",
        "\n",
        "plt.scatter(X, y, color='black')\n",
        "plt.plot(X, y_pred, color='blue', linewidth=3)\n",
        "plt.plot(X, y_pred + mae, color='lightgray')\n",
        "plt.plot(X, y_pred - mae, color='lightgray')\n",
        "plt.xlabel('Рост, см')\n",
        "plt.ylabel('Вес, кг')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "bXhC75uRzSMV"
      },
      "source": [
        "#### Определение линейной зависимости (линейная корреляция)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 6,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "uF45zDJkzR-0",
        "outputId": "8a5a0ef5-e0bd-488c-ef45-e086b255bcd1"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "0.5568647346122992"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/plain": [
              "1.1029015151266403e-17"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/plain": [
              "'1.1029015151266403e-17 < 0.05'"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "from scipy import stats\n",
        "\n",
        "\n",
        "corr, pval = stats.pearsonr(X[:,0], y[:,0])\n",
        "\n",
        "display(corr)\n",
        "display(pval)\n",
        "display(f\"{pval} < 0.05\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "tVUen-uczxXq"
      },
      "source": [
        "corr > 0, значит обнаружена линейная зависимость между x и y\n",
        "\n",
        "corr -> 1, присутствует сильная корреляция\n",
        "\n",
        "pval < 5%, значит корреляция присутствует\n"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "authorship_tag": "ABX9TyM5PyQgrWDfgi5yGxN9RXFr",
      "provenance": []
    },
    "kernelspec": {
      "display_name": ".venv (3.11.12)",
      "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.11.12"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
