异常检测(三)之线性模型

线性模型即线性方法,本文介绍线性回归与主成成分分析2种方法
对数据进行线性建模的两个前提:

  • 近似线性相关假设
    因变量与所有自变量存在线性关系,且与每一个自变量之间都存在线性关系的假设
  • 子空间假设
    子空间假设认为数据是镶嵌在低维子空间中的,线性方法的目的是找到合适的低维子空间使得异常点(o)在其中区别于正常点(n)。
  1. 数据可视化
    首先,确定数据集适应的模型,因此需要对数据进行可视化
    采用的数据集为breast-cancer-unsupervised-ad数据集,下载地址:
    数据集包下载
    观察数据,打印出前5行,共31列,最右边的列为标签在这里插入图片描述
    使用train.tail()函数,观察数据尾部,得到一共367行数据
    使用train.describe()函数,得到数据的最大值最小值等统计量,如下图
    在这里插入图片描述
    使用train.info()函数,每一列数据的类型和数量,可见每一列都是367个数据,类型是64位,如下图
    在这里插入图片描述
    得到数据的特征,首先计算相关系数,即计算线性数据的相关系数。
numeric_features = ['f' + str(i) for i in range(30)]
print(numeric_features)
## 1) 相关性分析
numeric = train_data[numeric_features]
correlation = numeric.corr()
print(correlation)#相关系数
f , ax = plt.subplots(figsize = (14, 14))

sns.heatmap(correlation,square = True)
plt.title('Correlation of Numeric Features with Price',y=1,size=16)
plt.show()
f = pd.melt(train_data, value_vars=numeric_features)#列数据合并为行数据
print(f)
g = sns.FacetGrid(f, col="variable",  col_wrap=6, sharex=False, sharey=False)#结构化多绘图网格,col_wrap=6-6列,是否共享x轴或者y轴
g = g.map(sns.distplot, "value", hist=False, rug=True)
sns.set()
#主要展现的是变量两两之间的关系
sns.pairplot(train_data[numeric_features],size = 2 ,kind ='scatter',diag_kind='kde')#对于特征使用散点图
plt.savefig('correlation.png')
plt.show()

facetgrid:多网格,不共享x或者y轴
pairplot:
kind:用于控制非对角线上的图的类型,可选"scatter"与"reg"

diag_kind:控制对角线上的图的类型,可选"hist"与"kde"
最终输出为:
热力图
热力图,相关系数
在这里插入图片描述
facegrid输出,30,30个特征的分布
在这里插入图片描述
pairplot输出,30*30,两两之间

接着使用降维方法:TSNE
t-SNE(t-distributed stochastic neighbor embedding)是用于降维的一种机器学习算法,是由 Laurens van der Maaten 等在08年提出来。此外,t-SNE 是一种非线性降维算法,非常适用于高维数据降维到2维或者3维,进行可视化。该算法可以将对于较大相似度的点,t分布在低维空间中的距离需要稍小一点;而对于低相似度的点,t分布在低维空间中的距离需要更远。
其主要用于可视化,很难用于其他目的,t-SNE没有唯一最优解,且没有预估部分。点击这里查看更多有关tsne的介绍

init:字符串,可选(默认值:“random”)嵌入的初始化。可能的选项是“随机”和“pca”。 PCA初始化不能用于预先计算的距离,并且通常比随机初始化更全局稳定

#数据降维可视化
from sklearn.manifold import TSNE
tsne = TSNE(n_components=2, init='pca', random_state=0)
result = tsne.fit_transform(numeric)
x_min, x_max = np.min(result, 0), np.max(result, 0)
#对结果进行标准化
result = (result - x_min) / (x_max - x_min)
label = train_data['label']
fig = plt.figure(figsize = (7, 7))
#f , ax = plt.subplots()
color = {'o':0, 'n':7}#8种颜色
for i in range(result.shape[0]):
    plt.text(result[i, 0], result[i, 1], str(label[i]),
                color=plt.cm.Set1(color[label[i]] / 10.),#颜色
                fontdict={'weight': 'bold', 'size': 9})#字体
plt.xticks([])
plt.yticks([])
plt.title('Visualization of data dimension reduction')

在这里插入图片描述
可以看到上面的图非常奇怪。。。
确实也分开了,接下来使用pca看看效果:

  1. PCA提取特征
    首先用pyod库生成example,这里选择生成30维的数据
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import pyod as py
from pyod.utils.data import generate_data
from pyod.models.pca import PCA
from pyod.utils.example import visualize
from pyod.utils.data import evaluate_print
import seaborn as sns
#生成数据 维度30


x_train,y_train=generate_data(
        n_train=500, n_features=30,
        train_only=True,behaviour='old',offset=10)
outlier_fraction = 0.1

再将数据转换成dataframe格式,看看数据之间的关联性

#转换为dataframe
df_train = pd.DataFrame(x_train)
numeric_features = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29]
print(numeric_features)
numeric = df_train[numeric_features]
correlation = numeric.corr()#相关系数
f , ax = plt.subplots(figsize = (14, 14))
sns.heatmap(correlation,square = True)
plt.title('Correlation of Numeric Features with Price',y=1,size=16)
plt.show()
f = pd.melt(df_train, value_vars=numeric_features)#列数据合并为行数据
print(f)
g = sns.FacetGrid(f, col="variable",  col_wrap=6, sharex=False, sharey=False)#结构化多绘图网格,col_wrap=6-6列,是否共享x轴或者y轴
g = g.map(sns.distplot, "value", hist=False, rug=True)
sns.set()
#主要展现的是变量两两之间的关系
sns.pairplot(df_train[numeric_features],size = 2 ,kind ='scatter',diag_kind='kde')#对于特征使用散点图
plt.savefig('correlation.png')
plt.show()

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

随后对数据进行PCA分析

df_train['y'] = y_train
#定义异常值点
x_outliers, x_inliers = py.utils.data.get_outliers_inliers(x_train,y_train)
n_inliers = len(x_inliers)
n_outliers = len(x_outliers)
sns.scatterplot(x=0, y=1, hue='y', data=df_train)
plt.show()
xx , yy = np.meshgrid(np.linspace(-10, 10, 200), np.linspace(-10, 10, 200))
#使用PCA
classifiers = {
    'Principal component analysis (PCA)': PCA(n_components=2,contamination=outlier_fraction)
}

for i, (clf_name, clf) in enumerate(classifiers.items()):
    clf.fit(x_train)
    y_train_pred = clf.labels_  # binary labels (0: inliers, 1: outliers)
    y_train_scores = clf.decision_scores_  # raw outlier scores
# get the prediction on the test data

    clf_name = 'PCA'
    print("\nOn Training Data:")
    evaluate_print(clf_name, y_train, y_train_scores)
    # print(precision_score(y_train,y_train_pred))
    sns.scatterplot(x=0, y=1, hue=y_train_scores, data=df_train, palette='RdBu_r')
    plt.show()

在这里插入图片描述

在这里插入图片描述
可见效果良好。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值