{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Linear regression" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "array([[ 5.09353825e-05],\n", " [ 2.12425850e-01],\n", " [ 2.27277367e+01],\n", " [ 1.07168045e-01],\n", " [-6.53624164e+01],\n", " [-5.79337497e+00]])" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import numpy as np\n", "from numpy.linalg import pinv\n", "\n", "X = np.array([\n", " [1, 2104, 5, 2104, 1, 45],\n", " [1, 1416, 3, 2104, 2, 40],\n", " [1, 1534, 3, 2104, 2, 30],\n", " [1, 852, 2, 2104, 1, 36],\n", "])\n", "\n", "y = np.array([\n", " [460],\n", " [232],\n", " [315],\n", " [178],\n", "])\n", "\n", "XT = np.transpose(X)\n", "\n", "pinv(XT @ X) @ XT @ y" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Noninvertibility\n", "\n", "Q: How do we calculate the inverse of $X^TX$ if it is non-invertible (singular/degenerate)?\n", "\n", "A: `pinv` will do it for you (pseudo-inverse)" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "array([[0., 0.],\n", " [0., 0.]])" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "A = np.zeros((2, 2))\n", "\n", "Inverse = pinv(A)\n", "Inverse" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Q: When would it be non-invertible?\n", "\n", "A: A few causes:\n", "\n", "1. Redundant features (linearly dependent)\n", " - Example: $x_1$ = size in feet squared and $x_2$ = size in meters squared\n", "1. Too many features (example: $m \\leq n$)\n", " - Example: $m=10$ (10 training set items) but $n=100$ (100 features)\n", " - To solve: delete some features or use **regularization**" ] } ], "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.3" } }, "nbformat": 4, "nbformat_minor": 4 }