{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%matplotlib inline" ] }, { "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": [ "import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import svm, datasets\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\n# Plot the decision boundary. For that, we will assign a color to each\n# point in the mesh [x_min, x_max]x[y_min, y_max].\nx_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1\ny_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1\nxx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))\nZ = clf.predict(np.c_[xx.ravel(), yy.ravel()])\n\n# Put the result into a color plot\nZ = Z.reshape(xx.shape)\nplt.pcolormesh(xx, yy, Z, cmap=plt.cm.Paired)\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.12" } }, "nbformat": 4, "nbformat_minor": 0 }