Plot the maximum margin separating hyperplane within a two-class separable dataset using a Support Vector Machine classifier with linear kernel.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | print (__doc__) import numpy as np import matplotlib.pyplot as plt from sklearn import svm # we create 40 separable points np.random.seed( 0 ) X = np.r_[np.random.randn( 20 , 2 ) - [ 2 , 2 ], np.random.randn( 20 , 2 ) + [ 2 , 2 ]] Y = [ 0 ] * 20 + [ 1 ] * 20 # fit the model clf = svm.SVC(kernel = 'linear' ) clf.fit(X, Y) # get the separating hyperplane w = clf.coef_[ 0 ] a = - w[ 0 ] / w[ 1 ] xx = np.linspace( - 5 , 5 ) yy = a * xx - (clf.intercept_[ 0 ]) / w[ 1 ] # plot the parallels to the separating hyperplane that pass through the # support vectors b = clf.support_vectors_[ 0 ] yy_down = a * xx + (b[ 1 ] - a * b[ 0 ]) b = clf.support_vectors_[ - 1 ] yy_up = a * xx + (b[ 1 ] - a * b[ 0 ]) # plot the line, the points, and the nearest vectors to the plane plt.plot(xx, yy, 'k-' ) plt.plot(xx, yy_down, 'k--' ) plt.plot(xx, yy_up, 'k--' ) plt.scatter(clf.support_vectors_[:, 0 ], clf.support_vectors_[:, 1 ], s = 80 , facecolors = 'none' ) plt.scatter(X[:, 0 ], X[:, 1 ], c = Y, cmap = plt.cm.Paired) plt.axis( 'tight' ) plt.show() |
Total running time of the script: (0 minutes 0.060 seconds)
Download Python source code:
plot_separating_hyperplane.py
Download IPython notebook:
plot_separating_hyperplane.ipynb
Please login to continue.