{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# SGD: convex loss functions\n\nA plot that compares the various convex loss functions supported by\n:class:`~sklearn.linear_model.SGDClassifier` .\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Authors: The scikit-learn developers\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef modified_huber_loss(y_true, y_pred):\n z = y_pred * y_true\n loss = -4 * z\n loss[z >= -1] = (1 - z[z >= -1]) ** 2\n loss[z >= 1.0] = 0\n return loss\n\n\nxmin, xmax = -4, 4\nxx = np.linspace(xmin, xmax, 100)\nlw = 2\nplt.plot([xmin, 0, 0, xmax], [1, 1, 0, 0], color=\"gold\", lw=lw, label=\"Zero-one loss\")\nplt.plot(xx, np.where(xx < 1, 1 - xx, 0), color=\"teal\", lw=lw, label=\"Hinge loss\")\nplt.plot(xx, -np.minimum(xx, 0), color=\"yellowgreen\", lw=lw, label=\"Perceptron loss\")\nplt.plot(xx, np.log2(1 + np.exp(-xx)), color=\"cornflowerblue\", lw=lw, label=\"Log loss\")\nplt.plot(\n xx,\n np.where(xx < 1, 1 - xx, 0) ** 2,\n color=\"orange\",\n lw=lw,\n label=\"Squared hinge loss\",\n)\nplt.plot(\n xx,\n modified_huber_loss(xx, 1),\n color=\"darkorchid\",\n lw=lw,\n linestyle=\"--\",\n label=\"Modified Huber loss\",\n)\nplt.ylim((0, 8))\nplt.legend(loc=\"upper right\")\nplt.xlabel(r\"Decision function $f(x)$\")\nplt.ylabel(\"$L(y=1, f(x))$\")\nplt.show()" ] } ], "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.9.21" } }, "nbformat": 4, "nbformat_minor": 0 }