機器學習100天|Day1數據預處理 100天搞定機器學習|Day2簡單線性回歸分析 100天搞定機器學習|Day3多元線性回歸 100天搞定機器學習|Day4-6 邏輯回歸 100天搞定機器學習|Day7 K-NN 100天搞定機器學習|Day8 邏輯回歸的數學原理 100天搞定機器學習|Day9 ...
昨天我們學習了支持向量機基本概念,重申數學推導原理的重要性並向大家介紹了一篇非常不錯的文章。今天,我們使用Scikit-Learn中的SVC分類器實現SVM。我們將在day16使用kernel-trick實現SVM。 導入庫
import numpy as np import matplotlib.pyplot as plt import pandas as pd
導入數據 數據集依然是Social_Network_Ads,下載鏈接: https://pan.baidu.com/s/1cPBt2DAF2NraOMhbk5-_pQ 提取碼:vl2g
dataset = pd.read_csv('Social_Network_Ads.csv') X = dataset.iloc[:, [2, 3]].values y = dataset.iloc[:, 4].values拆分數據集為訓練集合和測試集合
from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)
特征量化
from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.fit_transform(X_test)
適配SVM到訓練集合
from sklearn.svm import SVC classifier = SVC(kernel = 'linear', random_state = 0) classifier.fit(X_train, y_train)
預測測試集合結果
y_pred = classifier.predict(X_test)創建混淆矩陣
from sklearn.metrics import confusion_matrix cm = confusion_matrix(y_test, y_pred)訓練集合結果可視化
from matplotlib.colors import ListedColormap X_set, y_set = X_train, y_train X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01), np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01)) plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape), alpha = 0.75, cmap = ListedColormap(('red', 'green'))) plt.xlim(X1.min(), X1.max()) plt.ylim(X2.min(), X2.max()) for i, j in enumerate(np.unique(y_set)): plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1], c = ListedColormap(('red', 'green'))(i), label = j) plt.title('SVM (Training set)') plt.xlabel('Age') plt.ylabel('Estimated Salary') plt.legend() plt.show()
測試集合結果可視化
from matplotlib.colors import ListedColormap X_set, y_set = X_test, y_test X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01), np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01)) plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape), alpha = 0.75, cmap = ListedColormap(('red', 'green'))) plt.xlim(X1.min(), X1.max()) plt.ylim(X2.min(), X2.max()) for i, j in enumerate(np.unique(y_set)): plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1], c = ListedColormap(('red', 'green'))(i), label = j) plt.title('SVM (Test set)') plt.xlabel('Age') plt.ylabel('Estimated Salary') plt.legend() plt.show()