{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Cost function" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import numpy as np" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "def costFunction(X, y, theta):\n", " m = len(y)\n", " hypothesis = X @ theta\n", " err = hypothesis - y\n", " return ((1 / (2 * m)) * (np.transpose(err) @ err).item((0, 0)))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's run it against some fake housing data:" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "With bad theta values - cost: 2184583333333.3333\n", "With good theta values - cost: 0.0\n" ] } ], "source": [ "X = np.array([\n", " [1, 3000],\n", " [1, 4000],\n", " [1, 5000],\n", "])\n", "\n", "y = np.array([\n", " [1550000],\n", " [2050000],\n", " [2550000],\n", "])\n", "\n", "bad_theta = np.array([\n", " [0],\n", " [0],\n", "])\n", "\n", "good_theta = np.array([\n", " [50000],\n", " [500],\n", "])\n", "\n", "print(\"With bad theta values - cost:\", costFunction(X, y, bad_theta))\n", "\n", "print(\"With good theta values - cost:\", costFunction(X, y, good_theta))" ] } ], "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 }