异常检测算法:One Class SVM算法的python代码实现

本文介绍了OneClassSVM算法,一种无监督学习方法,用于识别正例样本并检测异常点。通过寻找将正例包围的超平面,OneClassSVM可以有效地在未标记数据中找出可能的离群点。代码示例展示了如何使用sklearn库实现该算法,并通过可视化案例解释了其工作原理和效果。
摘要由CSDN通过智能技术生成

One Class SVM

算法介绍

One Class SVM也是属于支持向量机大家族的,但是它和传统的基于监督学习的分类回归支持向量机不同,它是无监督学习的方法,也就是说,它不需要我们标记训练集的输出标签。

One-Class-SVM,这个算法的思路非常简单,就是寻找一个超平面将样本中的正例圈出来,在超平面之外的就认为是离群点。预测就是用这个超平面做决策,在圈内的样本就认为是正样本。

代码实现

使用sklearn中的相关包来实现One class SVM算法,举一个很简单的小demo:

from sklearn.svm import OneClassSVM
X = [[0], [0.44], [0.45], [0.46], [1]]
clf = OneClassSVM(gamma='auto')
clf = clf.fit(X)
# score越小,代表越有可能是离群点
scores = clf.score_samples(X)
"""
输出的结果是:
[1.77987316 2.05479873 2.05560497 2.05615569 1.73328509]
"""
print(scores)

其他的内置函数以及介绍在:scikit-learn-oneclasssvm

可视化

sklearn上的可视化案例,链接为:scikit-learn

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

xx, yy = np.meshgrid(np.linspace(-5, 5, 500), np.linspace(-5, 5, 500))
# Generate train data
X = 0.3 * np.random.randn(100, 2)
X_train = np.r_[X + 2, X - 2]
# Generate some regular novel observations
X = 0.3 * np.random.randn(20, 2)
X_test = np.r_[X + 2, X - 2]
# Generate some abnormal novel observations
X_outliers = np.random.uniform(low=-4, high=4, size=(20, 2))

# fit the model
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

# plot the line, the points, and the nearest vectors to the plane
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(), 0, 7), 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((-5, 5))
plt.ylim((-5, 5))
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()

显示的结果是:

好的,以下是使用遗传算法优化OneClassSVM分类器参数的示例代码: ```python import numpy as np from sklearn.metrics import confusion_matrix from sklearn.model_selection import train_test_split from sklearn.svm import OneClassSVM import genetic_algorithm as ga # 遗传算法模块,需自行安装 # 定义目标函数:返回 OneClassSVM 分类器在测试集上的混淆矩阵(即 TP,FP,TN,FN) def fitness_func(params, x_train, x_test): clf = OneClassSVM(kernel='rbf', nu=params[0], gamma=params[1]) clf.fit(x_train) y_pred = clf.predict(x_test) cm = confusion_matrix(y_test, y_pred) # 计算混淆矩阵 tp, fp, tn, fn = cm.ravel() # 摊平混淆矩阵 return tp, fp, tn, fn # 加载数据集 data = np.load('data.npy') x = data[:, :-1] y = data[:, -1] # 划分训练集和测试集 x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=42) # 定义变量的取值范围(nu ∈ [0.01, 0.3],gamma ∈ [0.01, 10.0]) genes = [ {'name': 'nu', 'type': 'float', 'min': 0.01, 'max': 0.3}, {'name': 'gamma', 'type': 'float', 'min': 0.01, 'max': 10.0}, ] # 定义遗传算法的相关参数 num_generations = 50 population_size = 10 mutation_rate = 0.01 # 运行遗传算法进行参数优化 best_params, best_fitness = ga.run(fitness_func, genes, x_train, x_test, num_generations, population_size, mutation_rate) # 打印最佳参数和最佳适应度 print('Best parameters:', best_params) print('Best fitness:', best_fitness) # 运行 OneClassSVM 分类器,并在测试集上计算混淆矩阵 clf = OneClassSVM(kernel='rbf', nu=best_params[0], gamma=best_params[1]) clf.fit(x_train) y_pred = clf.predict(x_test) cm = confusion_matrix(y_test, y_pred) # 打印混淆矩阵 print('Confusion matrix:') print(cm) ``` 其中, `genetic_algorithm.py` 是自己编写的遗传算法模块,也可以使用开源遗传算法库,例如 DEAP。运行时需要将数据集 `data.npy` 放在同一目录下,并在代码中指定变量的取值范围。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值