具有非線性內核(RBF)的一類支持向量機(One-class SVM)?

使用一類SVM進行新穎性檢測的示例。

一類SVM是一種無監督算法,可學習用于新穎性檢測的決策函數:將新數據分類為與訓練集相似或不同。

輸入:

print(__doc__)

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.font_manager
from sklearn import svm

xx, yy = np.meshgrid(np.linspace(-55500), np.linspace(-55500))
# 獲取訓練數據
X = 0.3 * np.random.randn(1002)
X_train = np.r_[X + 2, X - 2]
# 獲取一些常規的新穎觀察值
X = 0.3 * np.random.randn(202)
X_test = np.r_[X + 2, X - 2]
# 獲取一些異常的新穎觀察值
X_outliers = np.random.uniform(low=-4, high=4, size=(202))

# 擬合模型
clf = svm.OneClassSVM(nu=0.1, kernel="rbf", gamma=0.1)
clf.fit(X_train)
y_pred_train = clf.predict(X_train)
y_pred_test = clf.predict(X_test)
y_pred_outliers = clf.predict(X_outliers)
n_error_train = y_pred_train[y_pred_train == -1].size
n_error_test = y_pred_test[y_pred_test == -1].size
n_error_outliers = y_pred_outliers[y_pred_outliers == 1].size

# 繪制直線,點和最接近平面的向量
Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)

plt.title("Novelty Detection")
plt.contourf(xx, yy, Z, levels=np.linspace(Z.min(), 07), cmap=plt.cm.PuBu)
a = plt.contour(xx, yy, Z, levels=[0], linewidths=2, colors='darkred')
plt.contourf(xx, yy, Z, levels=[0, Z.max()], colors='palevioletred')

s = 40
b1 = plt.scatter(X_train[:, 0], X_train[:, 1], c='white', s=s, edgecolors='k')
b2 = plt.scatter(X_test[:, 0], X_test[:, 1], c='blueviolet', s=s,
                 edgecolors='k')
c = plt.scatter(X_outliers[:, 0], X_outliers[:, 1], c='gold', s=s,
                edgecolors='k')
plt.axis('tight')
plt.xlim((-55))
plt.ylim((-55))
plt.legend([a.collections[0], b1, b2, c],
           ["learned frontier""training observations",
            "new regular observations""new abnormal observations"],
           loc="upper left",
           prop=matplotlib.font_manager.FontProperties(size=11))
plt.xlabel(
    "error train: %d/200 ; errors novel regular: %d/40 ; "
    "errors novel abnormal: %d/40"
    % (n_error_train, n_error_test, n_error_outliers))
plt.show()

腳本的總運行時間:(0分鐘0.362秒)