{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "tags": [
     "remove_input"
    ]
   },
   "outputs": [],
   "source": [
    "path_data = '../../data/'\n",
    "\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from scipy import stats\n",
    "\n",
    "%matplotlib inline\n",
    "import matplotlib.pyplot as plt\n",
    "plt.style.use('fivethirtyeight')\n",
    "\n",
    "import warnings\n",
    "warnings.filterwarnings('ignore')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# HIDDEN \n",
    "galton = pd.read_csv(path_data + 'galton.csv')\n",
    "\n",
    "heights = galton[['midparentHeight', 'childHeight']]\n",
    "\n",
    "heights = heights.rename(columns={'midparentHeight':'MidParent', 'childHeight':'Child'})\n",
    "\n",
    "dugong = pd.read_csv('http://www.statsci.org/data/oz/dugongs.txt')\n",
    "\n",
    "dugong[['Age','Length']] = dugong['Age\\tLength'].str.split('\\t',expand=True)\n",
    "\n",
    "dugong = dugong.drop(columns=['Age\\tLength'])\n",
    "\n",
    "length = dugong.pop('Length')\n",
    "\n",
    "dugong.insert(0, 'Length', length)\n",
    "\n",
    "dugong['Length'] = dugong['Length'].astype(float)\n",
    "\n",
    "dugong['Age'] = dugong['Age'].astype(float)\n",
    "\n",
    "hybrid = pd.read_csv(path_data + 'hybrid.csv')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "tags": [
     "remove_input"
    ]
   },
   "outputs": [],
   "source": [
    "def standard_units(x):\n",
    "    return (x - np.mean(x))/np.std(x)\n",
    "\n",
    "def correlation(table, x, y):\n",
    "    x_in_standard_units = standard_units(table[x])\n",
    "    y_in_standard_units = standard_units(table[y])\n",
    "    return np.mean(x_in_standard_units * y_in_standard_units)\n",
    "\n",
    "def slope(table, x, y):\n",
    "    r = correlation(table, x, y)\n",
    "    return r * np.std(table[y])/np.std(table[x])\n",
    "\n",
    "def intercept(table, x, y):\n",
    "    a = slope(table, x, y)\n",
    "    return np.mean(table[y]) -  a * np.mean(table[x])\n",
    "\n",
    "def fit(table, x, y):\n",
    "    a = slope(table, x, y)\n",
    "    b = intercept(table, x, y)\n",
    "    return a * table[x] + b\n",
    "\n",
    "def residual(table, x, y):\n",
    "    return table[y] - fit(table, x, y)\n",
    "\n",
    "def scatter_fit(table, x, y):\n",
    "    #fig, ax = plt.subplots(figsize=(7,6))\n",
    "    plt.scatter(table[x], \n",
    "               table[y],  \n",
    "               color='darkblue',\n",
    "               s=20)\n",
    "    \n",
    "    plt.plot(table[x], fit(table, x, y), lw=2, color='gold')\n",
    "    plt.xlabel(x)\n",
    "    plt.ylabel(y)\n",
    "    \n",
    "def residual_plot(table, x, y):\n",
    "    fig, ax = plt.subplots(figsize=(7,6))\n",
    "    x_array = table[x]\n",
    "    t = pd.DataFrame({x:x_array, 'residuals':residual(table, x, y)})\n",
    "    ax.scatter(t[x], t['residuals'], color='r')\n",
    "    xlims = np.array([min(x_array), max(x_array)])\n",
    "    ax.plot(xlims, np.array([0, 0]), color='darkblue', lw=4)\n",
    "    x_label = x\n",
    "    y_label = y\n",
    "    y_vals = ax.get_yticks()\n",
    "    plt.ylabel(y_label)\n",
    "    plt.xlabel(x_label)\n",
    "    plt.title('Residual Plot')\n",
    "    plt.show()\n",
    "\n",
    "def regression_diagnostic_plots(table, x, y):\n",
    "    scatter_fit(table, x, y)\n",
    "    residual_plot(table, x, y)   "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "tags": [
     "remove_input"
    ]
   },
   "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>MidParent</th>\n",
       "      <th>Child</th>\n",
       "      <th>Fitted Value</th>\n",
       "      <th>Residual</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>75.43</td>\n",
       "      <td>73.2</td>\n",
       "      <td>70.712373</td>\n",
       "      <td>2.487627</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>75.43</td>\n",
       "      <td>69.2</td>\n",
       "      <td>70.712373</td>\n",
       "      <td>-1.512373</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>75.43</td>\n",
       "      <td>69.0</td>\n",
       "      <td>70.712373</td>\n",
       "      <td>-1.712373</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>75.43</td>\n",
       "      <td>69.0</td>\n",
       "      <td>70.712373</td>\n",
       "      <td>-1.712373</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>73.66</td>\n",
       "      <td>73.5</td>\n",
       "      <td>69.584244</td>\n",
       "      <td>3.915756</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>73.66</td>\n",
       "      <td>72.5</td>\n",
       "      <td>69.584244</td>\n",
       "      <td>2.915756</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>73.66</td>\n",
       "      <td>65.5</td>\n",
       "      <td>69.584244</td>\n",
       "      <td>-4.084244</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>73.66</td>\n",
       "      <td>65.5</td>\n",
       "      <td>69.584244</td>\n",
       "      <td>-4.084244</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>72.06</td>\n",
       "      <td>71.0</td>\n",
       "      <td>68.564467</td>\n",
       "      <td>2.435533</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>72.06</td>\n",
       "      <td>68.0</td>\n",
       "      <td>68.564467</td>\n",
       "      <td>-0.564467</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   MidParent  Child  Fitted Value  Residual\n",
       "0      75.43   73.2     70.712373  2.487627\n",
       "1      75.43   69.2     70.712373 -1.512373\n",
       "2      75.43   69.0     70.712373 -1.712373\n",
       "3      75.43   69.0     70.712373 -1.712373\n",
       "4      73.66   73.5     69.584244  3.915756\n",
       "5      73.66   72.5     69.584244  2.915756\n",
       "6      73.66   65.5     69.584244 -4.084244\n",
       "7      73.66   65.5     69.584244 -4.084244\n",
       "8      72.06   71.0     68.564467  2.435533\n",
       "9      72.06   68.0     68.564467 -0.564467"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "heights['Fitted Value'] = fit(heights, 'MidParent', 'Child')\n",
    "\n",
    "heights['Residual'] = residual(heights, 'MidParent', 'Child')\n",
    "\n",
    "heights.head(10)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Numerical Diagnostics\n",
    "In addition to visualization, we can use numerical properties of residuals to assess the quality of regression. We will not prove these properties mathematically. Rather, we will observe them by computation and see what they tell us about the regression.\n",
    "\n",
    "All of the facts listed below hold for all shapes of scatter plots, whether or not they are linear."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Residual Plots Show No Trend\n",
    "**For every linear regression, whether good or bad, the residual plot shows no trend. Overall, it is flat. In other words, the residuals and the predictor variable are uncorrelated.** \n",
    "\n",
    "You can see this in all the residual plots above. We can also calculate the correlation between the predictor variable and the residuals in each case.\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3.090556599598937e-16"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "correlation(heights, 'MidParent', 'Residual')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "That doesn't look like zero, but it is a tiny number that is 0 apart from rounding error due to computation. Here it is again, correct to 10 decimal places. The minus sign is because of the rounding that above."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.0"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "round(correlation(heights, 'MidParent', 'Residual'), 10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.0"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dugong['Fitted Value'] = fit(dugong, 'Length', 'Age')\n",
    "\n",
    "dugong['Residual'] = residual(dugong, 'Length', 'Age')\n",
    "\n",
    "round(correlation(dugong, 'Length', 'Residual'), 10)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Average of Residuals\n",
    "**No matter what the shape of the scatter diagram, the average of the residuals is 0.**\n",
    "\n",
    "This is analogous to the fact that if you take any list of numbers and calculate the list of deviations from average, the average of the deviations is 0.\n",
    "\n",
    "In all the residual plots above, you have seen the horizontal line at 0 going through the center of the plot. That is a visualization of this fact.\n",
    "\n",
    "As a numerical example, here is the average of the residuals in the regression of children's heights based on parents' heights in Galton's dataset."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.0"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "round(np.mean(heights['Residual']), 10)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The same is true of the average of the residuals in the regression of the age of dugongs on their length. The mean of the residuals is 0, apart from rounding error. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "-0.0"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "round(np.mean(dugong['Residual']), 10)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## SD of the Residuals\n",
    "**No matter what the shape of the scatter plot, the SD of the residuals is a fraction of the SD of the response variable. The fraction is  $\\sqrt{1-r^2}$.**\n",
    "\n",
    "$$\n",
    "\\mbox{SD of residuals} ~=~ \\sqrt{1 - r^2} \\cdot \\mbox{SD of }y\n",
    "$$\n",
    "\n",
    "We will soon see how this measures the accuracy of the regression estimate. But first, let's confirm it by example. \n",
    "\n",
    "In the case of children's heights and midparent heights, the SD of the residuals is about 3.39 inches."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3.388079916395343"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.std(heights['Residual'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "That's the same as $\\sqrt{1-r^2}$ times the SD of response variable: "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3.388079916395342"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "r = correlation(heights, 'MidParent', 'Child')\n",
    "np.sqrt(1 - r**2) * np.std(heights['Child'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The same is true for the regression of mileage on acceleration of hybrid cars. The correlation $r$ is negative (about -0.5), but $r^2$ is positive and therefore $\\sqrt{1-r^2}$ is a fraction."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "-0.5060703843771185"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "r = correlation(hybrid, 'acceleration', 'mpg')\n",
    "r"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(9.43273683343029, 9.432736833430296)"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "hybrid['fitted mpg'] = fit(hybrid, 'acceleration', 'mpg')\n",
    "\n",
    "hybrid['residual'] = residual(hybrid, 'acceleration', 'mpg')\n",
    "\n",
    "np.std(hybrid['residual']), np.sqrt(1 - r**2)*np.std(hybrid['mpg'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now let us see how the SD of the residuals is a measure of how good the regression is. Remember that the average of the residuals is 0. Therefore the smaller the SD of the residuals is, the closer the residuals are to 0. In other words, if the SD of the residuals is small, the overall size of the errors in regression is small.\n",
    "\n",
    "The extreme cases are when $r=1$ or $r=-1$. In both cases, $\\sqrt{1-r^2} = 0$. Therefore the residuals have an average of 0 and an SD of 0 as well, and therefore the residuals are all equal to 0. The regression line does a perfect job of estimation. As we saw earlier in this chapter, if $r = \\pm 1$, the scatter plot is a perfect straight line and is the same as the regression line, so indeed there is no error in the regression estimate. \n",
    "\n",
    "But usually $r$ is not at the extremes. If $r$ is neither $\\pm 1$ nor 0, then $\\sqrt{1-r^2}$ is a proper fraction, and the rough overall size of the error of the regression estimate is somewhere between 0 and the SD of $y$.\n",
    "\n",
    "The worst case is when $r = 0$. Then $\\sqrt{1-r^2} =1$, and the SD of the residuals is equal to the SD of $y$. This is consistent with the observation that if $r=0$ then the regression line is a flat line at the average of $y$. In this situation, the root mean square error of regression is the root mean squared deviation from the average of $y$, which is the SD of $y$. In practical terms, if $r = 0$ then there is no linear association between the two variables, so there is no benefit in using linear regression."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Another Way to Interpret $r$\n",
    "We can rewrite the result above to say that no matter what the shape of the scatter plot,\n",
    "\n",
    "$$\n",
    "\\frac{\\mbox{SD of residuals}}{\\mbox{SD of }y} ~=~ \\sqrt{1-r^2}\n",
    "$$\n",
    "\n",
    "A complementary result is that no matter what the shape of the scatter plot, the SD of the fitted values is a fraction of the SD of the observed values of $y$. The fraction is $\\vert r \\vert$.\n",
    "\n",
    "$$\n",
    "\\frac{\\mbox{SD of fitted values}}{\\mbox{SD of }y} ~=~ \\vert r \\vert\n",
    "$$\n",
    "\n",
    "To see where the fraction comes in, notice that the fitted values are all on the regression line whereas the observed values of $y$ are the heights of all the points in the scatter plot and are more variable."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 32856 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "scatter_fit(heights, 'MidParent', 'Child')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The fitted values range from about 64 to about 71, whereas the heights of all the children are quite a bit more variable, ranging from about 55 to 80.\n",
    "\n",
    "To verify the result numerically, we just have to calculate both sides of the identity."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.320949896063959"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "correlation(heights, 'MidParent', 'Child')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here is ratio of the SD of the fitted values and the SD of the observed values of birth weight:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.32094989606395896"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.std(heights['Fitted Value'])/np.std(heights['Child'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The ratio is equal to $r$, confirming our result.\n",
    "\n",
    "Where does the absolute value come in? First note that as SDs can't be negative, nor can a ratio of SDs. So what happens when $r$ is negative? The example of fuel efficiency and acceleration will show us."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "-0.5060703843771185"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "correlation(hybrid, 'acceleration', 'mpg')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.5060703843771186"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.std(hybrid['fitted mpg'])/np.std(hybrid['mpg'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The ratio of the two SDs is $\\vert r \\vert$. \n",
    "\n",
    "A more standard way to express this result is to recall that \n",
    "\n",
    "$$\n",
    "\\mbox{variance} ~=~ \\mbox{mean squared deviation from average} ~=~ \\mbox{SD}^2\n",
    "$$\n",
    "\n",
    "and therefore, by squaring both sides of our result,\n",
    "\n",
    "$$\n",
    "\\frac{\\mbox{variance of fitted values}}{\\mbox{variance of }y} ~=~ r^2\n",
    "$$"
   ]
  }
 ],
 "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.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
