{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# SVM with custom kernel\n\nSimple usage of Support Vector Machines to classify a sample. It will\nplot the decision surface and the support vectors.\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 import datasets, svm\nfrom sklearn.inspection import DecisionBoundaryDisplay\n\n# import some data to play with\niris = datasets.load_iris()\nX = iris.data[:, :2] # we only take the first two features. We could\n# avoid this ugly slicing by using a two-dim dataset\nY = iris.target\n\n\ndef my_kernel(X, Y):\n \"\"\"\n We create a custom kernel:\n\n (2 0)\n k(X, Y) = X ( ) Y.T\n (0 1)\n \"\"\"\n M = np.array([[2, 0], [0, 1.0]])\n return np.dot(np.dot(X, M), Y.T)\n\n\nh = 0.02 # step size in the mesh\n\n# we create an instance of SVM and fit out data.\nclf = svm.SVC(kernel=my_kernel)\nclf.fit(X, Y)\n\nax = plt.gca()\nDecisionBoundaryDisplay.from_estimator(\n clf,\n X,\n cmap=plt.cm.Paired,\n ax=ax,\n response_method=\"predict\",\n plot_method=\"pcolormesh\",\n shading=\"auto\",\n)\n\n# Plot also the training points\nplt.scatter(X[:, 0], X[:, 1], c=Y, cmap=plt.cm.Paired, edgecolors=\"k\")\nplt.title(\"3-Class classification using Support Vector Machine with custom kernel\")\nplt.axis(\"tight\")\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 }