{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "\n", "def calculate_slope_intercept(x_values, y_values):\n", " \"\"\"\n", " Calculate the slope and intercept of a regression line.\n", " @param x_values the independent x values.\n", " @param y_values the dependent y values.\n", " @return a list of the slope and y-intercept of the line.\n", " \"\"\"\n", " x = np.array(x_values)\n", " y = np.array(y_values)\n", " \n", " n = len(x)\n", " sum_x = np.sum(x)\n", " sum_y = np.sum(y)\n", " sum_xx = np.sum(x*x)\n", " sum_xy = np.sum(x*y)\n", " mean_x = np.mean(x)\n", " mean_y = np.mean(y)\n", " \n", " numerator = sum_xy - (sum_x*sum_y)/n\n", " denominator = sum_xx - ((sum_x*sum_x)/n)\n", " \n", " m = numerator/denominator\n", " b = mean_y - m*mean_x\n", " \n", " return m, b # slope and intercept" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "\n", "def show_least_squares_line(title, x_label, y_label, \n", " x_values, y_values):\n", " \"\"\"\n", " @param title the chart title.\n", " @param x_label the x-axis label.\n", " @param y_label the y-axis label.\n", " @param x_values the independent x values to plot.\n", " @param y_values the dependent y values to plot.\n", " \"\"\"\n", " # First show the scatter plot.\n", " plt.scatter(x_values, y_values)\n", " \n", " # Now show the least squares line.\n", " m, b = calculate_slope_intercept(x_values, y_values)\n", " reg_line = [m*x + b for x in x_values] # regression line\n", " plt.plot(xs, reg_line, color='red')\n", "\n", " plt.title(f'{title}, m = {m:.2f}, b = {b:.2f}')\n", " plt.ylabel(x_label)\n", " plt.xlabel(y_label)\n", "\n", " plt.show()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "xs = [32, 37, 38, 40, 45, 50, 50, 54, 54, 55, \n", " 61, 63, 63, 64, 64, 70, 70, 75, 76]\n", "ys = [18.3, 18.9, 19.0, 20.9, 21.4, 20.5, 20.1, 20.1, 20.8, 20.5, \n", " 19.9, 20.5, 20.6, 22.1, 21.9, 21.2, 20.5, 22.7, 22.8]\n", "\n", "show_least_squares_line('Linear Regression Line', 'Dependent variable', \n", " 'Independent variable', xs, ys)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "xs = range(2, 26)\n", "ys = [10,12,20,22,21,25,30,21,32,34,35,30,50,45,55,60,66,64,67,72,74,80,79,84]\n", "\n", "show_least_squares_line('Linear Regression Line', 'Dependent variable', \n", " 'Independent variable', xs, ys)" ] } ], "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.7.7" } }, "nbformat": 4, "nbformat_minor": 4 }