实例 — 异常检测(1):用Pyod工具检测人工数据生成数据

import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
import matplotlib.font_manager
# 导入想要用来检测数据集中异常值的模型。使用ABOD和KNN:
from pyod.models.abod import ABOD
from pyod.models.knn import KNN
# 创建一个带有异常值的随机数据集并绘制它
from pyod.utils.data import generate_data, get_outliers_inliers
# 生成数据
X_train, Y_train = generate_data(n_train=200,train_only=True, n_features=2)
# 在默认情况下,离群值在生成数据函数中是0.1
outlier_fraction = 0.1
# 将异常值和异常值存储在不同的numpy数组中
x_outliers, x_inliers = get_outliers_inliers(X_train,Y_train)
n_inliers = len(x_inliers)
n_outliers = len(x_outliers)
#分离这两个特性并使用它来绘制数据
F1 = X_train[:,[0]].reshape(-1,1)
F2 = X_train[:,[1]].reshape(-1,1)
# create a meshgrid
xx , yy = np.meshgrid(np.linspace(-10, 10, 200), np.linspace(-10, 10, 200))
# scatter plot
plt.scatter(F1,F2)
plt.xlabel('F1')
plt.ylabel('F2')
#plt.show()
#创建一个dictionary并添加要用于检测异常值的所有模型:
classifiers = {
'Angle-based Outlier Detector (ABOD)' : ABOD(contamination=outlier_fraction),
'K Nearest Neighbors (KNN)' : KNN(contamination=outlier_fraction)
}
#将数据拟合到我们在dictionary中添加的每个模型,然后,查看每个模型如何检测异常值:
#set the figure size
plt.figure(figsize=(10, 10))
for i, (clf_name,clf) in enumerate(classifiers.items()) :
    # fit the dataset to the model
    clf.fit(X_train)
    # predict raw anomaly score
    scores_pred = clf.decision_function(X_train)*-1
    # prediction of a datapoint category outlier or inlier
    y_pred = clf.predict(X_train)
    # no of errors in prediction
    n_errors = (y_pred != Y_train).sum()
    print('No of Errors : ',clf_name, n_errors)
    # rest of the code is to create the visualization
    # threshold value to consider a datapoint inlier or outlier
    threshold = stats.scoreatpercentile(scores_pred,100 *outlier_fraction)
    # decision function calculates the raw anomaly score for every point
    Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()]) * -1
    Z = Z.reshape(xx.shape)
    subplot = plt.subplot(1, 2, i + 1)
    # fill blue colormap from minimum anomaly score to threshold value
    subplot.contourf(xx, yy, Z, levels = np.linspace(Z.min(), threshold, 10),cmap=plt.cm.Blues_r)
    # draw red contour line where anomaly score is equal to threshold
    a = subplot.contour(xx, yy, Z, levels=[threshold],linewidths=2, colors='red')
    # fill orange contour lines where range of anomaly score is from threshold to maximum anomaly score
    subplot.contourf(xx, yy, Z, levels=[threshold, Z.max()],colors='orange')
    # scatter plot of inliers with white dots
    b = subplot.scatter(X_train[:-n_outliers, 0], X_train[:-n_outliers, 1], c='white',s=20, edgecolor='k')
    # scatter plot of outliers with black dots
    c = subplot.scatter(X_train[-n_outliers:, 0], X_train[-n_outliers:, 1], c='black',s=20, edgecolor='k')
    subplot.axis('tight')
    subplot.legend(
    [a.collections[0], b, c],
    ['learned decision function', 'true inliers', 'true outliers'],
    prop=matplotlib.font_manager.FontProperties(size=10),
    loc='lower right')
    subplot.set_title(clf_name)
subplot.set_xlim((-10, 10))
subplot.set_ylim((-10, 10))

plt.show()
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
支持向量机(Support Vector Machine,SVM)是一种常用的机器学习算法,可以用于分类和回归问题。在数据检测领域,SVM可以用来检测虚假数据,以下是一个简单的SVM模型实例: 假设我们有一个数据集,其中包含100个样本,每个样本由3个特征组成。我们要使用SVM来检测其中的虚假数据。首先,我们需要将数据集划分为训练集和测试集。我们可以使用80%的数据作为训练集,剩下的20%作为测试集。 接下来,我们需要选择一个合适的SVM核函数。在这个例子中,我们选择使用径向基函数(Radial Basis Function,RBF)作为核函数。然后,我们使用SVM训练模型,使用训练集来确定模型的参数。在训练完成后,我们可以使用测试集来评估模型的准确性。 下面是一个Python实现的SVM模型实例: ```python from sklearn import svm from sklearn.model_selection import train_test_split import numpy as np # 创建数据集 X = np.random.rand(100, 3) y = np.random.randint(0, 2, 100) # 划分训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) # 创建SVM模型 clf = svm.SVC(kernel='rbf') # 训练模型 clf.fit(X_train, y_train) # 测试模型 accuracy = clf.score(X_test, y_test) print("Accuracy:", accuracy) ``` 在这个例子中,我们使用随机数生成器来创建一个包含100个样本的数据集,其中每个样本由3个特征组成。然后,我们使用train_test_split函数将数据集划分为训练集和测试集。接下来,我们创建一个SVM模型,并使用训练集来训练模型。最后,我们使用测试集来评估模型的准确性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值