Java自学者论坛

 找回密码
 立即注册

手机号码,快捷登录

恭喜Java自学者论坛(https://www.javazxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,会员资料板块,购买链接:点击进入购买VIP会员

JAVA高级面试进阶训练营视频教程

Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程Go语言视频零基础入门到精通Java架构师3期(课件+源码)
Java开发全终端实战租房项目视频教程SpringBoot2.X入门到高级使用教程大数据培训第六期全套视频教程深度学习(CNN RNN GAN)算法原理Java亿级流量电商系统视频教程
互联网架构师视频教程年薪50万Spark2.0从入门到精通年薪50万!人工智能学习路线教程年薪50万大数据入门到精通学习路线年薪50万机器学习入门到精通教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程MySQL入门到精通教程
查看: 707|回复: 0

sklearn异常检测demo

[复制链接]
  • TA的每日心情
    奋斗
    7 天前
  • 签到天数: 745 天

    [LV.9]以坛为家II

    2041

    主题

    2099

    帖子

    70万

    积分

    管理员

    Rank: 9Rank: 9Rank: 9

    积分
    704660
    发表于 2021-5-30 14:49:31 | 显示全部楼层 |阅读模式

    sklearn 异常检测demo代码走读

    # 0基础学python,读代码学习python组件api
    import time
     
    import numpy as np
    import matplotlib
    import matplotlib.pyplot as plt
     
    from sklearn import svm
    from sklearn.datasets import make_moons, make_blobs
    from sklearn.covariance import EllipticEnvelope
    from sklearn.ensemble import IsolationForest
    from sklearn.neighbors import LocalOutlierFactor
     
    print(__doc__)
     
    matplotlib.rcParams['contour.negative_linestyle'] = 'solid'
     
    # Example settings
    n_samples = 300
    outliers_fraction = 0.15
    n_outliers = int(outliers_fraction * n_samples)
    n_inliers = n_samples - n_outliers
     
    # define outlier/anomaly detection methods to be compared
    # 四种异常检测算法,之后的文章详细介绍
    anomaly_algorithms = [
        ("Robust covariance", EllipticEnvelope(contamination=outliers_fraction)),
        ("One-Class SVM", svm.OneClassSVM(nu=outliers_fraction, kernel="rbf",
                                          gamma=0.1)),
        ("Isolation Forest", IsolationForest(contamination=outliers_fraction,
                                             random_state=42)),
        ("Local Outlier Factor", LocalOutlierFactor(
            n_neighbors=35, contamination=outliers_fraction))]
     
    # Define datasets
    blobs_params = dict(random_state=0, n_samples=n_inliers, n_features=2)
    datasets = [
        # make_blobes用于生成聚类数据。centers表示聚类中心,cluster_std表示聚类数据方差。返回值(数据, 类别)
        # **用于传递dict key-value参数,*用于传递元组不定数量参数。
        make_blobs(centers=[[0, 0], [0, 0]], cluster_std=0.5,
                   **blobs_params)[0],
        make_blobs(centers=[[2, 2], [-2, -2]], cluster_std=[0.5, 0.5],
                   **blobs_params)[0],
        make_blobs(centers=[[2, 2], [-2, -2]], cluster_std=[1.5, .3],
                   **blobs_params)[0],
         
        # make_moons用于生成月亮形数据。返回值数据(x, y)
        4. * (make_moons(n_samples=n_samples, noise=.05, random_state=0)[0] -
              np.array([0.5, 0.25])),
        14. * (np.random.RandomState(42).rand(n_samples, 2) - 0.5)]
     
    # Compare given classifiers under given settings
    # np.meshgrid生产成网格数据
    # 如输入x = [0, 1, 2, 3] y = [0, 1, 2],则输出
    # xx 0 1 2 3   yy 0 0 0 0
    #    0 1 2 3      1 1 1 1
    #    0 1 2 3      2 2 2 2
    xx, yy = np.meshgrid(np.linspace(-7, 7, 150),
                         np.linspace(-7, 7, 150))
     
    # figure生成画布,subplots_adjust子图的间距调整,左边距,右边距,下边距,上边距,列间距,行间距
    plt.figure(figsize=(len(anomaly_algorithms) * 2 + 3, 12.5))
    plt.subplots_adjust(left=.02, right=.98, bottom=.001, top=.96, wspace=.05,
                        hspace=.01)
     
    plot_num = 1
    rng = np.random.RandomState(42)
     
    for i_dataset, X in enumerate(datasets):
        # Add outliers
        # np.concatenate数组拼接。axis=0行增加,axis=1列增加(对应行拼接)。
        X = np.concatenate([X, rng.uniform(low=-6, high=6,
                           size=(n_outliers, 2))], axis=0)
     
        for name, algorithm in anomaly_algorithms:
            t0 = time.time()
            # 专门用于评估执行时间,无用代码
            algorithm.fit(X)
            t1 = time.time()
            # 定位子图位置。参数:列,行,序号
            plt.subplot(len(datasets), len(anomaly_algorithms), plot_num)
            if i_dataset == 0:
                plt.title(name, size=18)
     
            # fit the data and tag outliers
            # 训练与预测
            if name == "Local Outlier Factor":
                y_pred = algorithm.fit_predict(X)
            else:
                y_pred = algorithm.fit(X).predict(X)
     
            # plot the levels lines and the points
            # 用训练的模型预测网格数据点,主要是要得到聚类模型边缘
            if name != "Local Outlier Factor":  # LOF does not implement predict
                # ravel()多维数组平铺为一维数组。np.c_ cloumn列连接,np.r_ row行连接。
                Z = algorithm.predict(np.c_[xx.ravel(), yy.ravel()])
                # reshape这里把一维数组转化为二维数组
                Z = Z.reshape(xx.shape)
                # plt.contour画等高线。Z表示对应点类别,可以理解为不同的高度,plt.contour就是要画出不同高度间的分界线。
                plt.contour(xx, yy, Z, levels=[0], linewidths=2, colors='black')
     
            colors = np.array(['#377eb8', '#ff7f00'])
            plt.scatter(X[:, 0], X[:, 1], s=10, color=colors[(y_pred + 1) // 2])
     
            # x轴范围
            plt.xlim(-7, 7)
            plt.ylim(-7, 7)
            # x轴坐标
            plt.xticks(())
            plt.yticks(())
            # 坐标图上显示的文字
            plt.text(.99, .01, ('%.2fs' % (t1 - t0)).lstrip('0'),
                     transform=plt.gca().transAxes, size=15,
                     horizontalalignment='right')
            plot_num += 1
     
    plt.show()

    执行结果

     

    哎...今天够累的,签到来了1...
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|小黑屋|Java自学者论坛 ( 声明:本站文章及资料整理自互联网,用于Java自学者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2024-3-29 09:43 , Processed in 0.056744 second(s), 29 queries .

    Powered by Discuz! X3.4

    Copyright © 2001-2021, Tencent Cloud.

    快速回复 返回顶部 返回列表