{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "WvMflodMjQKe"
   },
   "source": [
    "# <font color=green size=10>CURSO DE ESTATÍSTICA - PARTE 4</font>\n",
    "***\n",
    "\n",
    "## Trabalho sobre correlação e regressão\n",
    "\n",
    "Utilizando os conhecimentos adquiridos em nosso treinamento realize a análise de regressão proposta abaixo.\n",
    "\n",
    "Siga o roteiro proposto e vá completando as células vazias."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "cVgsZ_E3jQKg"
   },
   "source": [
    "# <font color=green>DATASET DO PROJETO</font>\n",
    "***"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "I4293oHyZTNh"
   },
   "source": [
    "### Fonte: https://www.kaggle.com/dongeorge/beer-consumption-sao-paulo\n",
    "\n",
    "### Descrição:\n",
    "A cerveja é uma das bebidas mais democráticas e consumidas no mundo. Não sem razão, é perfeito para quase todas as situações, desde o happy hour até grandes festas de casamento.\n",
    "\n",
    "Os dados (amostra) foram coletados em São Paulo - Brasil, em uma área universitária, onde existem algumas festas com grupos de alunos de 18 a 28 anos de idade (média).\n",
    "\n",
    "### Dados:\n",
    "- **temp_media** - Temperatura Média (°C)\n",
    "- **consumo** - Consumo de Cerveja (litros)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "ZIqLOffNTg1Y"
   },
   "source": [
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "_mFnZ15pcmu1"
   },
   "source": [
    "### Solução do problema com dependência do statsmodels"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 217
    },
    "colab_type": "code",
    "id": "m5QYUoH4cnp1",
    "outputId": "f20c7fba-f54c-4450-c484-11e5081bfdb4"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Requirement already up-to-date: scipy==1.2 in c:\\users\\rnand\\anaconda3\\lib\\site-packages (1.2.0)\n",
      "Requirement not upgraded as not directly required: numpy>=1.8.2 in c:\\users\\rnand\\anaconda3\\lib\\site-packages (from scipy==1.2) (1.14.3)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "distributed 1.21.8 requires msgpack, which is not installed.\n",
      "You are using pip version 10.0.1, however version 19.1.1 is available.\n",
      "You should consider upgrading via the 'python -m pip install --upgrade pip' command.\n"
     ]
    }
   ],
   "source": [
    "!pip install scipy==1.2 --upgrade"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "8Rw70V6ojQKk"
   },
   "source": [
    "### Utilize a célula abaixo para importar as biblioteca que precisar para executar as tarefas\n",
    "#### <font color='red'>Sugestões: pandas, numpy, scipy, statsmodels</font>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "fcTgimHBybMz"
   },
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import seaborn as sns\n",
    "import statsmodels.api as sm\n",
    "from scipy.stats import probplot\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "Blpb0v-6ZTNv"
   },
   "source": [
    "### Importe o dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "vrf8BOm7ZTNw"
   },
   "outputs": [],
   "source": [
    "dataset = pd.read_csv('dados_projeto.csv', sep=';')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "Oq3CKHCmTg1j"
   },
   "source": [
    "### Visualize o conteúdo do DataFrame"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "bpj9gwIbZTNz",
    "outputId": "a5e43384-57db-4daf-91dc-172b17e93683"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(365, 2)"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dataset.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 195
    },
    "colab_type": "code",
    "id": "GsC_WhLFjQKq",
    "outputId": "911c1540-fbb1-405e-9bd5-56c601488890",
    "scrolled": true
   },
   "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>Y</th>\n",
       "      <th>X</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>25461</td>\n",
       "      <td>27.30</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>28972</td>\n",
       "      <td>27.02</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>30814</td>\n",
       "      <td>24.82</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>29799</td>\n",
       "      <td>23.98</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>28900</td>\n",
       "      <td>23.82</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "       Y      X\n",
       "0  25461  27.30\n",
       "1  28972  27.02\n",
       "2  30814  24.82\n",
       "3  29799  23.98\n",
       "4  28900  23.82"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dataset.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "xzGuwM4xpslc"
   },
   "source": [
    "### Obtenha e avalie as estatísticas descritivas dos dados"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "nuNSrzfYpsld",
    "outputId": "d7e3627c-0894-4e69-c031-6fe4965ccf6e",
    "scrolled": true
   },
   "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>Y</th>\n",
       "      <th>X</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>count</th>\n",
       "      <td>365.000000</td>\n",
       "      <td>365.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>mean</th>\n",
       "      <td>25401.367123</td>\n",
       "      <td>21.226356</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>std</th>\n",
       "      <td>4399.142703</td>\n",
       "      <td>3.180108</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>min</th>\n",
       "      <td>14343.000000</td>\n",
       "      <td>12.900000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>25%</th>\n",
       "      <td>22008.000000</td>\n",
       "      <td>19.020000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>50%</th>\n",
       "      <td>24867.000000</td>\n",
       "      <td>21.380000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>75%</th>\n",
       "      <td>28631.000000</td>\n",
       "      <td>23.280000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>max</th>\n",
       "      <td>37937.000000</td>\n",
       "      <td>28.860000</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                  Y           X\n",
       "count    365.000000  365.000000\n",
       "mean   25401.367123   21.226356\n",
       "std     4399.142703    3.180108\n",
       "min    14343.000000   12.900000\n",
       "25%    22008.000000   19.020000\n",
       "50%    24867.000000   21.380000\n",
       "75%    28631.000000   23.280000\n",
       "max    37937.000000   28.860000"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dataset.describe()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "SM6EQrsdZTN8"
   },
   "source": [
    "### Análise gráfica\n",
    "### Construa um box plot para cada variável do dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "olHVJwyWZTN9",
    "outputId": "2d1ee441-e105-4e4f-c2c2-51eef261c0b1"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<matplotlib.axes._subplots.AxesSubplot at 0x2dd366c9240>"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 10816 characters]\n",
      "text/plain": [
       "<Figure size 864x432 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "ax = sns.boxplot(data=dataset, x='Y', orient='h', width=0.5)\n",
    "ax.figure.set_size_inches(12, 6)\n",
    "ax.set_title('Box plot', fontsize=20)\n",
    "ax.set_xlabel('Consumo de cerveja (litros)', fontsize=16)\n",
    "ax"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "W-W9IOs1psle",
    "outputId": "83445d63-24a2-4a95-d42a-9ed55e2d81f5",
    "scrolled": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<matplotlib.axes._subplots.AxesSubplot at 0x2dd36b85278>"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 9292 characters]\n",
      "text/plain": [
       "<Figure size 864x432 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "ax = sns.boxplot(data=dataset, x = 'X', orient='h', width=0.5)\n",
    "ax.figure.set_size_inches(12, 6)\n",
    "ax.set_title('Box plot', fontsize=20)\n",
    "ax.set_xlabel('Temperatura média', fontsize=16)\n",
    "ax"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "kcdTQNDtZTOC"
   },
   "source": [
    "### Identifique se existe uma relação linear entre as variáveis $Y$ e $X$\n",
    "### <font color='red'>Utilizando o método gráfico</font>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "bQ2tLs6OZTOD",
    "outputId": "d9e7b772-49c1-4b4f-9ac7-edc52113320b"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<seaborn.axisgrid.FacetGrid at 0x2dd36a0d0f0>"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 56008 characters]\n",
      "text/plain": [
       "<Figure size 864x432 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "ax = sns.lmplot(x=\"X\", y=\"Y\", data=dataset)\n",
    "ax.fig.set_size_inches(12, 6)\n",
    "ax.fig.suptitle('Reta de Regressão - Gasto X Renda', fontsize=16, y=1.02)\n",
    "ax.set_xlabels(\"Renda das Famílias\", fontsize=14)\n",
    "ax.set_ylabels(\"Gasto das Famílias\", fontsize=14)\n",
    "ax"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "V3pRHkxrZTOG"
   },
   "source": [
    "### <font color='red'>Utilizando a matriz de correlação</font>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "szUKCsdNZTOG",
    "outputId": "10715ce6-2940-4375-f7cb-242dd913a87a"
   },
   "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>Y</th>\n",
       "      <th>X</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Y</th>\n",
       "      <td>1.000000</td>\n",
       "      <td>0.574615</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>X</th>\n",
       "      <td>0.574615</td>\n",
       "      <td>1.000000</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "          Y         X\n",
       "Y  1.000000  0.574615\n",
       "X  0.574615  1.000000"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dataset.corr()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "FqjloX9CZTOJ"
   },
   "source": [
    "### Avalie os resultados acima:\n",
    "\n",
    "É possível afirmar que existe uma relação linear entre as variáveis?\n",
    "\n",
    "Resp.: Sim.\n",
    "\n",
    "É possível quantificar a intensidade dessa relação?\n",
    "\n",
    "Resp.: Sim. A partir do coeficiente de correlação\n",
    "\n",
    "É possível afirmar que existe uma relação de causalidade entre $Y$ e $X$ a partir dos resultados da matriz de correlação?\n",
    "\n",
    "Resp.: Não"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "eQD2gqJ4ZTOK"
   },
   "source": [
    "### Prepare os dados para estimar um modelo de regressão linear simples"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "KHiDwWVcZTOL"
   },
   "outputs": [],
   "source": [
    "Y = dataset.Y\n",
    "X = sm.add_constant(dataset.X)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "atGXG2cbZTON"
   },
   "source": [
    "### Estime o modelo de regressão linear simples"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "RZj-LLWJZTOO"
   },
   "outputs": [],
   "source": [
    "resultado_regressao = sm.OLS(Y, X).fit()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "brIOPkVsZTOT"
   },
   "source": [
    "### Visualize o resultado da regressão"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "TEdY4WLIZTOU",
    "outputId": "f1af9367-0e65-451f-e81b-f99ee4c82d99"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "                            OLS Regression Results                            \n",
      "==============================================================================\n",
      "Dep. Variable:                      Y   R-squared:                       0.330\n",
      "Model:                            OLS   Adj. R-squared:                  0.328\n",
      "Method:                 Least Squares   F-statistic:                     178.9\n",
      "Date:                Mon, 29 Jul 2019   Prob (F-statistic):           1.87e-33\n",
      "Time:                        19:45:00   Log-Likelihood:                -3506.3\n",
      "No. Observations:                 365   AIC:                             7017.\n",
      "Df Residuals:                     363   BIC:                             7024.\n",
      "Df Model:                           1                                         \n",
      "Covariance Type:            nonrobust                                         \n",
      "==============================================================================\n",
      "                 coef    std err          t      P>|t|      [0.025      0.975]\n",
      "------------------------------------------------------------------------------\n",
      "const       8528.9073   1275.363      6.687      0.000    6020.880     1.1e+04\n",
      "X            794.8825     59.423     13.377      0.000     678.027     911.738\n",
      "==============================================================================\n",
      "Omnibus:                       11.300   Durbin-Watson:                   1.623\n",
      "Prob(Omnibus):                  0.004   Jarque-Bera (JB):                9.673\n",
      "Skew:                           0.324   Prob(JB):                      0.00793\n",
      "Kurtosis:                       2.534   Cond. No.                         145.\n",
      "==============================================================================\n",
      "\n",
      "Warnings:\n",
      "[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n"
     ]
    }
   ],
   "source": [
    "print(resultado_regressao.summary())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "qRYMfNCTZTOX"
   },
   "source": [
    "### Obtenha o $Y$ previsto"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "5EvF5aPQZTOY",
    "outputId": "06886495-0362-4a81-b226-166023b629f1",
    "scrolled": true
   },
   "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>Y</th>\n",
       "      <th>X</th>\n",
       "      <th>Y_previsto</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>25461</td>\n",
       "      <td>27.30</td>\n",
       "      <td>30229.200544</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>28972</td>\n",
       "      <td>27.02</td>\n",
       "      <td>30006.633434</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>30814</td>\n",
       "      <td>24.82</td>\n",
       "      <td>28257.891852</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>29799</td>\n",
       "      <td>23.98</td>\n",
       "      <td>27590.190521</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>28900</td>\n",
       "      <td>23.82</td>\n",
       "      <td>27463.009315</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "       Y      X    Y_previsto\n",
       "0  25461  27.30  30229.200544\n",
       "1  28972  27.02  30006.633434\n",
       "2  30814  24.82  28257.891852\n",
       "3  29799  23.98  27590.190521\n",
       "4  28900  23.82  27463.009315"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dataset['Y_previsto'] = resultado_regressao.predict()\n",
    "dataset.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "nIpYDmr6ZTOb"
   },
   "source": [
    "### Utilizando nosso modelo estimado para fazer previsões.\n",
    "### Qual seria o consumo de cerveja para um dia com temperatura média de 42° C?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "Th2Akn3ZZTOb",
    "outputId": "b63ddd21-b33d-416d-f5a0-95f04f4f7ec7"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "41913.973838166276"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "resultado_regressao.predict([1, 42])[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "cRNbxk8EZTOd"
   },
   "source": [
    "### Obtenha os resíduos da regressão"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "wBzSywQ-ZTOe",
    "outputId": "7f874a3e-efab-4e7f-a5a0-3a8c826f8ce8"
   },
   "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>Y</th>\n",
       "      <th>X</th>\n",
       "      <th>Y_previsto</th>\n",
       "      <th>Residuos</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>25461</td>\n",
       "      <td>27.30</td>\n",
       "      <td>30229.200544</td>\n",
       "      <td>-4768.200544</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>28972</td>\n",
       "      <td>27.02</td>\n",
       "      <td>30006.633434</td>\n",
       "      <td>-1034.633434</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>30814</td>\n",
       "      <td>24.82</td>\n",
       "      <td>28257.891852</td>\n",
       "      <td>2556.108148</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>29799</td>\n",
       "      <td>23.98</td>\n",
       "      <td>27590.190521</td>\n",
       "      <td>2208.809479</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>28900</td>\n",
       "      <td>23.82</td>\n",
       "      <td>27463.009315</td>\n",
       "      <td>1436.990685</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "       Y      X    Y_previsto     Residuos\n",
       "0  25461  27.30  30229.200544 -4768.200544\n",
       "1  28972  27.02  30006.633434 -1034.633434\n",
       "2  30814  24.82  28257.891852  2556.108148\n",
       "3  29799  23.98  27590.190521  2208.809479\n",
       "4  28900  23.82  27463.009315  1436.990685"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dataset['Residuos'] = resultado_regressao.resid\n",
    "dataset.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "v1uM1N_UZTOg"
   },
   "source": [
    "### Plote um gráfico de dispersão dos resíduos da regressão contra o $Y$ previsto"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "gyF8kMnzZTOh",
    "outputId": "7dfa3151-edfb-40b1-dfed-6b00f92752c7"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<matplotlib.axes._subplots.AxesSubplot at 0x2dd3704ac88>"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 34592 characters]\n",
      "text/plain": [
       "<Figure size 864x432 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "ax = sns.scatterplot(x=dataset.Y_previsto, y=dataset.Residuos)\n",
    "ax.figure.set_size_inches(12, 6)\n",
    "ax.set_title('Resíduos vs Y_Previsto', fontsize=18)\n",
    "ax.set_xlabel('Y_Previsto', fontsize=14)\n",
    "ax.set_ylabel('Resíduos', fontsize=14)\n",
    "ax"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "IwdoUMoOZTOj"
   },
   "source": [
    "### Obtenha o QQPlot dos resíduos"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "f48gEJ_PZTOj",
    "outputId": "4796edb3-76dd-44fd-ab1c-56957871860b"
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 17636 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "(_, (_, _, _)) = probplot(dataset.Residuos, plot=plt)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "83Q7JaaIZTOl"
   },
   "source": [
    "### <font color='red'>A partir dos outputs acima, qual conclusão podemos tirar sobre o comportamento dos resíduos?</font>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "XFr505IvZcR2"
   },
   "source": [
    "### Obtenha o R² da regressão pelo método da soma dos quadrados\n",
    "\n",
    "# $$R^2 = \\frac{SQR}{SQT}$$\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "GxX3EpMfZTOn",
    "outputId": "7ede76b5-f570-4d31-bc15-c3f1e11803a9"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "4718394688.067691"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "SQE = resultado_regressao.ssr\n",
    "SQE"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "5iSFXLvyZTOq",
    "outputId": "b3ff4b3e-1165-448f-ea33-5bc18a89a0e2"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2325899486.737788"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "SQR = resultado_regressao.ess\n",
    "SQR"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "mNm5V2r8ZTOs",
    "outputId": "e40e384a-3402-4491-bf37-11b84096c569"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "7044294174.805479"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "SQT = SQR + SQE\n",
    "SQT"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "4wnz--cwZTOu",
    "outputId": "05b2f206-1322-46bc-eadd-37139d9a0d9f"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.3301820493324323"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "R2 = SQR / SQT\n",
    "R2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "JgBLHvclZTOw",
    "outputId": "87ba7851-4a9d-41d7-ed2d-1f3b1f870071"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.33018204933243234"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "resultado_regressao.rsquared"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "yJkBIZEIZTOy"
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "colab": {
   "name": "Correlação_e_Regressão-Respostas.ipynb",
   "provenance": [],
   "toc_visible": true,
   "version": "0.3.2"
  },
  "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.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
