{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Plot the support vectors in LinearSVC\n\nUnlike SVC (based on LIBSVM), LinearSVC (based on LIBLINEAR) does not provide\nthe support vectors. This example demonstrates how to obtain the support\nvectors in LinearSVC.\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\nfrom sklearn.datasets import make_blobs\nfrom sklearn.inspection import DecisionBoundaryDisplay\nfrom sklearn.svm import LinearSVC\n\nX, y = make_blobs(n_samples=40, centers=2, random_state=0)\n\nplt.figure(figsize=(10, 5))\nfor i, C in enumerate([1, 100]):\n    # \"hinge\" is the standard SVM loss\n    clf = LinearSVC(C=C, loss=\"hinge\", random_state=42).fit(X, y)\n    # obtain the support vectors through the decision function\n    decision_function = clf.decision_function(X)\n    # we can also calculate the decision function manually\n    # decision_function = np.dot(X, clf.coef_[0]) + clf.intercept_[0]\n    # The support vectors are the samples that lie within the margin\n    # boundaries, whose size is conventionally constrained to 1\n    support_vector_indices = (np.abs(decision_function) <= 1 + 1e-15).nonzero()[0]\n    support_vectors = X[support_vector_indices]\n\n    plt.subplot(1, 2, i + 1)\n    plt.scatter(X[:, 0], X[:, 1], c=y, s=30, cmap=plt.cm.Paired)\n    ax = plt.gca()\n    DecisionBoundaryDisplay.from_estimator(\n        clf,\n        X,\n        ax=ax,\n        grid_resolution=50,\n        plot_method=\"contour\",\n        colors=\"k\",\n        levels=[-1, 0, 1],\n        alpha=0.5,\n        linestyles=[\"--\", \"-\", \"--\"],\n    )\n    plt.scatter(\n        support_vectors[:, 0],\n        support_vectors[:, 1],\n        s=100,\n        linewidth=1,\n        facecolors=\"none\",\n        edgecolors=\"k\",\n    )\n    plt.title(\"C=\" + str(C))\nplt.tight_layout()\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.11.14"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}