【Python学习系列九】Python机器学习库scikit-learn实现SVM案例
生活随笔
收集整理的這篇文章主要介紹了
【Python学习系列九】Python机器学习库scikit-learn实现SVM案例
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
學習網址:http://scikit-learn.org/stable/modules/svm.html
SVM案例代碼:
# -*- coding: utf-8 -*- __author__ = 'Jason.F'#http://scikit-learn.org/stable/modules/svm.htmlimport numpy as np import matplotlib.pyplot as plt from sklearn import svm, datasets# import some data to play with iris = datasets.load_iris() X = iris.data[:, :2] # we only take the first two features. We could# avoid this ugly slicing by using a two-dim dataset y = iris.targeth = .02 # step size in the mesh# we create an instance of SVM and fit out data. We do not scale our # data since we want to plot the support vectors C = 1.0 # SVM regularization parameter svc = svm.SVC(kernel='linear', C=C).fit(X, y) rbf_svc = svm.SVC(kernel='rbf', gamma=0.7, C=C).fit(X, y) poly_svc = svm.SVC(kernel='poly', degree=3, C=C).fit(X, y) lin_svc = svm.LinearSVC(C=C).fit(X, y)# create a mesh to plot in x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, h),np.arange(y_min, y_max, h))# title for the plots titles = ['SVC with linear kernel','LinearSVC (linear kernel)','SVC with RBF kernel','SVC with polynomial (degree 3) kernel']for i, clf in enumerate((svc, lin_svc, rbf_svc, poly_svc)):# Plot the decision boundary. For that, we will assign a color to each# point in the mesh [x_min, x_max]x[y_min, y_max].plt.subplot(2, 2, i + 1)plt.subplots_adjust(wspace=0.4, hspace=0.4)Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])# Put the result into a color plotZ = Z.reshape(xx.shape)plt.contourf(xx, yy, Z, cmap=plt.cm.coolwarm, alpha=0.8)# Plot also the training pointsplt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.coolwarm)plt.xlabel('Sepal length')plt.ylabel('Sepal width')plt.xlim(xx.min(), xx.max())plt.ylim(yy.min(), yy.max())plt.xticks(())plt.yticks(())plt.title(titles[i])plt.show()結果:
總結
以上是生活随笔為你收集整理的【Python学习系列九】Python机器学习库scikit-learn实现SVM案例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Python学习系列八】Python实
- 下一篇: 【Python学习系列十】Python机