{
 "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",
    "\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": {
    "tags": [
     "remove_input"
    ]
   },
   "outputs": [],
   "source": [
    "baby = pd.read_csv(path_data + 'baby.csv')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "tags": [
     "remove_input"
    ]
   },
   "outputs": [],
   "source": [
    "\n",
    "def standard_units(any_numbers):\n",
    "    \"Convert any array of numbers to standard units.\"\n",
    "    return (any_numbers - np.mean(any_numbers))/np.std(any_numbers)  \n",
    "\n",
    "def correlation(t, x, y):\n",
    "    return np.mean(standard_units(t[x])*standard_units(t[y]))\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.column(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], table[y], color='blue', s=20)\n",
    "    \n",
    "    plt.plot(table[x], fit(table, x, y), lw=2, color='gold')\n",
    "    plt.xlabel(x)\n",
    "    plt.ylabel(y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Prediction Intervals\n",
    "One of the primary uses of regression is to make predictions for a new individual who was not part of our original sample but is similar to the sampled individuals. In the language of the model, we want to estimate $y$ for a new value of $x$.\n",
    "\n",
    "Our estimate is the height of the true line at $x$. Of course, we don't know the true line. What we have as a substitute is the regression line through our sample of points.\n",
    "\n",
    "The **fitted value** at a given value of $x$ is the regression estimate of $y$ based on that value of $x$. In other words, the fitted value at a given value of $x$ is the height of the regression line at that $x$."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Suppose we try to predict a baby's birth weight based on the number of gestational days. As we saw in the previous section, the data fit the regression model fairly well and a 95% confidence interval for the slope of the true line doesn't contain 0. So it seems reasonable to carry out our prediction."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The figure below shows where the prediction lies on the regression line. The red line is at $x = 300$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "tags": [
     "remove_input"
    ]
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 33376 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "\n",
    "scatter_fit(baby, 'Gestational Days', 'Birth Weight')\n",
    "s = slope(baby, 'Gestational Days', 'Birth Weight')\n",
    "i = intercept(baby, 'Gestational Days', 'Birth Weight')\n",
    "fit_300 = s*300 + i\n",
    "plt.scatter(300, fit_300, color='red', s=20)\n",
    "plt.plot([300,300], [0, fit_300], color='red', lw=2)\n",
    "plt.ylim([0, 200]);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The height of the point where the red line hits the regression line is the fitted value at 300 gestational days. \n",
    "\n",
    "The function `fitted_value` computes this height. Like the functions `correlation`, `slope`, and `intercept`, its arguments include the name of the table and the labels of the $x$ and $y$ columns. But it also requires a fourth argument, which is the value of $x$ at which the estimate will be made."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "def fitted_value(table, x, y, given_x):\n",
    "    a = slope(table, x, y)\n",
    "    b = intercept(table, x, y)\n",
    "    return a * given_x  + b"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The fitted value at 300 gestational days is about 129.2 ounces. In other words, for a pregnancy that has a duration of 300 gestational days, our estimate for the baby's weight is about 129.2 ounces."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "129.21292417031435"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "fit_300 = fitted_value(baby, 'Gestational Days', 'Birth Weight', 300)\n",
    "fit_300"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The Variability of the Prediction\n",
    "We have developed a method making one prediction of a new baby's birth weight based on the number of gestational days, using the data in our sample. But as data scientists, we know that the sample might have been different. Had the sample been different, the regression line would have been different too, and so would our prediction. To see how good our prediction is, we must get a sense of how variable the prediction can be.\n",
    "\n",
    "To do this, we must generate new samples. We can do that by bootstrapping the scatter plot as in the previous section. We will then fit the regression line to the scatter plot in each replication, and make a prediction based on each line. The figure below shows 10 such lines, and the corresponding predicted birth weight at 300 gestational days."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "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>slope</th>\n",
       "      <th>intercept</th>\n",
       "      <th>prediction at x = 300</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>0.471653</td>\n",
       "      <td>-12.537173</td>\n",
       "      <td>128.958602</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>0.441318</td>\n",
       "      <td>-3.246474</td>\n",
       "      <td>129.149006</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>0.427643</td>\n",
       "      <td>-0.639165</td>\n",
       "      <td>127.653674</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>0.528469</td>\n",
       "      <td>-27.520703</td>\n",
       "      <td>131.019992</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>0.488232</td>\n",
       "      <td>-16.368378</td>\n",
       "      <td>130.101243</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>0.509250</td>\n",
       "      <td>-23.132587</td>\n",
       "      <td>129.642469</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>0.491311</td>\n",
       "      <td>-17.413579</td>\n",
       "      <td>129.979797</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>0.415543</td>\n",
       "      <td>2.894067</td>\n",
       "      <td>127.556932</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>0.488195</td>\n",
       "      <td>-16.437820</td>\n",
       "      <td>130.020575</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>0.451464</td>\n",
       "      <td>-6.920024</td>\n",
       "      <td>128.519051</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "      slope  intercept  prediction at x = 300\n",
       "0  0.471653 -12.537173             128.958602\n",
       "1  0.441318  -3.246474             129.149006\n",
       "2  0.427643  -0.639165             127.653674\n",
       "3  0.528469 -27.520703             131.019992\n",
       "4  0.488232 -16.368378             130.101243\n",
       "5  0.509250 -23.132587             129.642469\n",
       "6  0.491311 -17.413579             129.979797\n",
       "7  0.415543   2.894067             127.556932\n",
       "8  0.488195 -16.437820             130.020575\n",
       "9  0.451464  -6.920024             128.519051"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x = 300\n",
    "\n",
    "lines = pd.DataFrame(columns=['slope', 'intercept'])\n",
    "\n",
    "\n",
    "for i in range(10):\n",
    "    rep = baby.sample(len(baby), replace=True)\n",
    "    a = slope(rep, 'Gestational Days', 'Birth Weight')\n",
    "    b = intercept(rep, 'Gestational Days', 'Birth Weight')\n",
    "    lines = lines.append({'slope':a, 'intercept': b}, ignore_index=True)\n",
    "\n",
    "lines['prediction at x = '+str(x)] = lines['slope']*x + lines['intercept']\n",
    "\n",
    "lines"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 46704 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# HIDDEN \n",
    "x = 300\n",
    "\n",
    "lines = pd.DataFrame(columns=['slope', 'intercept'])\n",
    "\n",
    "\n",
    "for i in range(10):\n",
    "    rep = baby.sample(len(baby), replace=True)\n",
    "    a = slope(rep, 'Gestational Days', 'Birth Weight')\n",
    "    b = intercept(rep, 'Gestational Days', 'Birth Weight')\n",
    "    lines = lines.append({'slope':a, 'intercept': b}, ignore_index=True)\n",
    "\n",
    "lines['prediction at x = '+str(x)] = lines['slope']*x + lines['intercept']\n",
    "\n",
    "xlims = np.array([291, 309])\n",
    "\n",
    "left = xlims[0]*lines.iloc[:,0] + lines.iloc[:,1]\n",
    "right = xlims[1]*lines.iloc[:,0] + lines.iloc[:,1]\n",
    "fit_x = x*lines['slope'] + lines['intercept']\n",
    "\n",
    "for i in range(10):\n",
    "    \n",
    "    plt.plot(xlims, np.array([left[i], right[i]]), lw=1)\n",
    "    \n",
    "    plt.scatter(x, fit_x[i], s=30)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The predictions vary from one line to the next. The table below shows the slope and intercept of each of the 10 lines, along with the prediction. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "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>slope</th>\n",
       "      <th>intercept</th>\n",
       "      <th>prediction at x = 300</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>0.510387</td>\n",
       "      <td>-22.786504</td>\n",
       "      <td>130.329684</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>0.421999</td>\n",
       "      <td>1.631657</td>\n",
       "      <td>128.231383</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>0.479922</td>\n",
       "      <td>-14.579319</td>\n",
       "      <td>129.397208</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>0.514294</td>\n",
       "      <td>-24.380318</td>\n",
       "      <td>129.907938</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>0.498741</td>\n",
       "      <td>-20.520979</td>\n",
       "      <td>129.101311</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>0.516581</td>\n",
       "      <td>-24.478420</td>\n",
       "      <td>130.495795</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>0.420951</td>\n",
       "      <td>2.657678</td>\n",
       "      <td>128.943073</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>0.445955</td>\n",
       "      <td>-5.322110</td>\n",
       "      <td>128.464306</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>0.421538</td>\n",
       "      <td>1.828003</td>\n",
       "      <td>128.289515</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>0.426793</td>\n",
       "      <td>0.280194</td>\n",
       "      <td>128.318088</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "      slope  intercept  prediction at x = 300\n",
       "0  0.510387 -22.786504             130.329684\n",
       "1  0.421999   1.631657             128.231383\n",
       "2  0.479922 -14.579319             129.397208\n",
       "3  0.514294 -24.380318             129.907938\n",
       "4  0.498741 -20.520979             129.101311\n",
       "5  0.516581 -24.478420             130.495795\n",
       "6  0.420951   2.657678             128.943073\n",
       "7  0.445955  -5.322110             128.464306\n",
       "8  0.421538   1.828003             128.289515\n",
       "9  0.426793   0.280194             128.318088"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "lines"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Bootstrap Prediction Interval\n",
    "If we increase the number of repetitions of the resampling process, we can generate an empirical histogram of the predictions. This will allow us to create an interval of predictions, using the same percentile method that we used create a bootstrap confidence interval for the slope."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let us define a function called ``bootstrap_prediction`` to do this. The function takes five arguments:\n",
    "- the name of the table\n",
    "- the column labels of the predictor and response variables, in that order\n",
    "- the value of $x$ at which to make the prediction\n",
    "- the desired number of bootstrap repetitions\n",
    "\n",
    "In each repetition, the function bootstraps the original scatter plot and finds the predicted value of $y$ based on the specified value of $x$. Specifically, it calls the function `fitted_value` that we defined earlier in this section to find the fitted value at the specified $x$.\n",
    "\n",
    "Finally, it draws the empirical histogram of all the predicted values, and prints the interval consisting of the \"middle 95%\" of the predicted values. It also prints the predicted value based on the regression line through the original scatter plot."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Bootstrap prediction of variable y at new_x\n",
    "# Data contained in table; prediction by regression of y based on x\n",
    "# repetitions = number of bootstrap replications of the original scatter plot\n",
    "\n",
    "def bootstrap_prediction(table, x, y, new_x, repetitions):\n",
    "    \n",
    "    # For each repetition:\n",
    "    # Bootstrap the scatter; \n",
    "    # get the regression prediction at new_x; \n",
    "    # augment the predictions list\n",
    "    predictions = np.array([])\n",
    "    for i in np.arange(repetitions):\n",
    "        bootstrap_sample = table.sample(len(table), replace=True)\n",
    "        bootstrap_prediction = fitted_value(bootstrap_sample, x, y, new_x)\n",
    "        predictions = np.append(predictions, bootstrap_prediction)\n",
    "        \n",
    "    # Find the ends of the approximate 95% prediction interval\n",
    "    left = np.percentile(predictions, 2.5)\n",
    "    right = np.percentile(predictions, 97.5)\n",
    "    \n",
    "    # Prediction based on original sample\n",
    "    original = fitted_value(table, x, y, new_x)\n",
    "    \n",
    "    # Display results\n",
    "    \n",
    "    #Table().with_column('Prediction', predictions).hist(bins=20)\n",
    "    pd.DataFrame({'Prediction':predictions}).hist(bins=20, ec='white');\n",
    "    \n",
    "    plt.xlabel('predictions at x='+str(new_x))\n",
    "    plt.plot(np.array([left, right]), np.array([0, 0]), color='yellow', lw=8);\n",
    "    print('Height of regression line at x='+str(new_x)+':', original)\n",
    "    print('Approximate 95%-confidence interval:')\n",
    "    print(left, right)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Height of regression line at x=300: 129.21292417031435\n",
      "Approximate 95%-confidence interval:\n",
      "127.27917987303 131.33090330196745\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 19384 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "bootstrap_prediction(baby, 'Gestational Days', 'Birth Weight', 300, 5000)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The figure above shows a bootstrap empirical histogram of the predicted birth weight of a baby at 300 gestational days, based on 5,000 repetitions of the bootstrap process. The empirical distribution is roughly normal. \n",
    "\n",
    "An approximate 95% prediction interval of scores has been constructed by taking the \"middle 95%\" of the predictions, that is, the interval from the 2.5th percentile to the 97.5th percentile of the predictions. The interval ranges from about 127 to about 131. The prediction based on the original sample was about 129, which is close to the center of the interval."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### The Effect of Changing the Value of the Predictor\n",
    "The figure below shows the histogram of 5,000 bootstrap predictions at 285 gestational days. The prediction based on the original sample is about 122 ounces, and the interval ranges from about 121 ounces to about 123 ounces. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Height of regression line at x=285: 122.2145710160761\n",
      "Approximate 95%-confidence interval:\n",
      "121.15453514561544 123.27634704011281\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 19104 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "bootstrap_prediction(baby, 'Gestational Days', 'Birth Weight', 285, 5000)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Notice that this interval is narrower than the prediction interval at 300 gestational days. Let us investigate the reason for this.\n",
    "\n",
    "The mean number of gestational days is about 279 days: "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "279.1013628620102"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.mean(baby['Gestational Days'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "So 285 is nearer to the center of the distribution than 300 is. Typically, the regression lines based on the bootstrap samples are closer to each other near the center of the distribution of the predictor variable. Therefore all of the predicted values are closer together as well. This explains the narrower width of the prediction interval. \n",
    "\n",
    "You can see this in the figure below, which shows predictions at $x = 285$ and $x = 300$ for each of ten bootstrap replications. Typically, the lines are farther apart at $x = 300$ than at $x = 285$, and therefore the predictions at $x = 300$ are more variable."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "tags": [
     "remove_input"
    ]
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 39916 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "\n",
    "x1 = 300\n",
    "x2 = 285\n",
    "\n",
    "lines = pd.DataFrame(columns=['slope', 'intercept'])\n",
    "\n",
    "for i in range(10):\n",
    "    rep = baby.sample(len(baby), replace=True)\n",
    "    a = slope(rep, 'Gestational Days', 'Birth Weight')\n",
    "    b = intercept(rep, 'Gestational Days', 'Birth Weight')\n",
    "    lines = lines.append({'slope':a, 'intercept': b}, ignore_index=True)\n",
    "\n",
    "\n",
    "xlims = np.array([260, 310])\n",
    "left = xlims[0]*lines.iloc[:,0] + lines.iloc[:,1]\n",
    "right = xlims[1]*lines.iloc[:,0] + lines.iloc[:,1]\n",
    "fit_x1 = x1*lines['slope'] + lines['intercept']\n",
    "fit_x2 = x2*lines['slope'] + lines['intercept']\n",
    "\n",
    "\n",
    "\n",
    "plt.xlim(xlims)\n",
    "for i in range(10):\n",
    "    plt.plot(xlims, np.array([left[i], right[i]]), lw=1)\n",
    "    plt.scatter(x1, fit_x1[i], s=30)\n",
    "    plt.scatter(x2, fit_x2[i], s=30)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Words of caution\n",
    "All of the predictions and tests that we have performed in this chapter assume that the regression model holds. Specifically, the methods assume that the scatter plot resembles points generated by starting with points that are on a straight line and then pushing them off the line by adding random normal noise.\n",
    "\n",
    "If the scatter plot does not look like that, then perhaps the model does not hold for the data. If the model does not hold, then calculations that assume the model to be true are not valid.\n",
    "\n",
    "Therefore, we must first decide whether the regression model holds for our data, before we start making predictions based on the model or testing hypotheses about parameters of the model. A simple way is to do what we did in this section, which is to draw the scatter diagram of the two variables and see whether it looks roughly linear and evenly spread out around a line. We should also run the diagnostics we developed in the previous section using the residual plot."
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "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": 1
}
