支持向量機,英文全稱為support vecto machines,簡稱svm。它是一種非常優(yōu)秀的分類模型,特別在小樣本、非線性以及高維模式識別中有很好的表現(xiàn)。svm是由vapnik團隊在1992年提出,最初被用來解決二分類問題,后來逐漸發(fā)展成為可以處理多分類問題的算法。
Python是一種簡潔而強大的編程語言,它實現(xiàn)了眾多機器學(xué)習(xí)算法的包,其中包括SVM。本文將介紹通過Python實現(xiàn)支持向量機算法的步驟。
一、準備數(shù)據(jù)
我們來構(gòu)造一組簡單的訓(xùn)練數(shù)據(jù)。創(chuàng)建一個示例數(shù)據(jù)集,其中x1表示身高,x2表示體重,y為類別標簽(0或1)。
import numpy as np import matplotlib.pyplot as plt np.random.seed(7) X_train = np.array([[167, 75], [182, 80], [176, 85], [156, 50], [173, 70], [183, 90], [178, 75], [156, 45], [162, 55], [163, 50], [159, 45], [180, 85]]) y_train = np.array([0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1]) plt.scatter(X_train[y_train == 0][:, 0], X_train[y_train == 0][:, 1], c='r', s=40, label='Male') plt.scatter(X_train[y_train == 1][:, 0], X_train[y_train == 1][:, 1], c='b', s=40, label='Female') plt.legend() plt.xlabel('Height') plt.ylabel('Weight') plt.show()
在這個數(shù)據(jù)集中,我們將人群分類為男性或女性。
立即學(xué)習(xí)“Python免費學(xué)習(xí)筆記(深入)”;
二、選擇分類器
接下來,我們要選擇適用于這個問題的分類器,即SVM。SVM有許多變種,但是在這里,我們使用的是線性SVM。
我們來構(gòu)造一個SVM模型:
from sklearn.svm import SVC svm = SVC(kernel='linear') svm.fit(X_train, y_train)
在這里,我們使用的是SVC
類,指定kernel
參數(shù)為linear
,表明我們使用線性核。
三、繪制決策邊界
我們想要知道模型的性能如何,因此我們可以在繪制出分類器的決策邊界:
def plot_decision_boundary(model, ax=None): if ax is None: ax = plt.gca() x_min, x_max = ax.get_xlim() y_min, y_max = ax.get_ylim() xx, yy = np.meshgrid(np.linspace(x_min, x_max, 100), np.linspace(y_min, y_max, 100)) Z = model.predict(np.c_[xx.ravel(), yy.ravel()]).reshape(xx.shape) ax.contourf(xx, yy, Z, alpha=0.2) ax.contour(xx, yy, Z, colors='black', linewidths=0.5) ax.set_xlim([x_min, x_max]) ax.set_ylim([y_min, y_max]) plt.scatter(X_train[y_train == 0][:, 0], X_train[y_train == 0][:, 1], c='r', s=40, label='Male') plt.scatter(X_train[y_train == 1][:, 0], X_train[y_train == 1][:, 1], c='b', s=40, label='Female') plot_decision_boundary(svm) plt.legend() plt.xlabel('Height') plt.ylabel('Weight') plt.show()
運行結(jié)束后,可以看到繪制出了分類器的決策邊界。
四、預(yù)測新數(shù)據(jù)
我們可以用訓(xùn)練好的模型對新的數(shù)據(jù)進行預(yù)測。
X_test = np.array([[166, 70], [185, 90], [170, 75]]) y_test = svm.predict(X_test) print(y_test)
在這里,我們使用predict
函數(shù)對三個新數(shù)據(jù)樣本進行預(yù)測。它將返回它們的類別。
結(jié)論
在這篇文章中,我們介紹了如何使用Python中的支持向量機算法。我們通過創(chuàng)建一個簡單的訓(xùn)練數(shù)據(jù)集,并使用線性SVM構(gòu)建了一個分類器。我們還繪制了分類器的決策邊界,并使用模型來預(yù)測了新的數(shù)據(jù)樣本。SVM在許多場合也是非常受歡迎的算法,可以在很多領(lǐng)域獲得好的表現(xiàn)。如果你想在處理數(shù)據(jù)時,掌握更多機器學(xué)習(xí)的算法,那么SVM也是非常值得學(xué)習(xí)的。
以上就是Python中的支持向量機算法實例的詳細內(nèi)容,更多請關(guān)注php中文網(wǎng)其它相關(guān)文章!
python怎么學(xué)習(xí)?python怎么入門?python在哪學(xué)?python怎么學(xué)才快?不用擔(dān)心,這里為大家提供了python速學(xué)教程(入門到精通),有需要的小伙伴保存下載就能學(xué)習(xí)啦!
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號