• 简介

在数据挖掘的过程中,我们可能会经常遇到一些偏离于预测趋势之外的数据,通常我们称之为异常值。

通常将这样的一些数据的出现归为误差。有很多情况会出现误差,具体的情况需要就对待:

传感器故障   ->  忽略

数据输入错误  ->  忽略

反常事件    ->  重视

  • 异常值检测/删除算法

1、训练数据

2、异常值检测,找出训练集中访问最多的点,去除这些点(一般约10%的异常数据)

3、再训练

需要多次重复2、3步骤

例:对数据第一次使用回归后的拟合

 

误差点的出现使拟合线相对偏离,将误差点去除后进行一次回归:

    

去除误差点后的回归线很好的对数据进行了拟合

  • 代码实现

环境:MacOS mojave  10.14.3

Python  3.7.0

使用库:scikit-learn    0.19.2

原始数据集:

    

对原始数据进行一次回归:

    

删除10%的异常值后进行一次回归:
    

outlier_removal_regression.py  主程序

#!/usr/bin/python

import random
import numpy
import matplotlib.pyplot as plt
import pickle from outlier_cleaner import outlierCleaner class StrToBytes:
def __init__(self, fileobj):
self.fileobj = fileobj
def read(self, size):
return self.fileobj.read(size).encode()
def readline(self, size=-1):
return self.fileobj.readline(size).encode() ### load up some practice data with outliers in it
ages = pickle.load(StrToBytes(open("practice_outliers_ages.pkl", "r") ) )
net_worths = pickle.load(StrToBytes(open("practice_outliers_net_worths.pkl", "r") ) ) ### ages and net_worths need to be reshaped into 2D numpy arrays
### second argument of reshape command is a tuple of integers: (n_rows, n_columns)
### by convention, n_rows is the number of data points
### and n_columns is the number of features
ages = numpy.reshape( numpy.array(ages), (len(ages), 1))
net_worths = numpy.reshape( numpy.array(net_worths), (len(net_worths), 1))
from sklearn.cross_validation import train_test_split
ages_train, ages_test, net_worths_train, net_worths_test = train_test_split(ages, net_worths, test_size=0.1, random_state=42) ### fill in a regression here! Name the regression object reg so that
### the plotting code below works, and you can see what your regression looks like from sklearn import linear_model
reg = linear_model.LinearRegression()
reg.fit(ages_train,net_worths_train)
print (reg.coef_)
print (reg.intercept_)
print (reg.score(ages_test,net_worths_test) ) try:
plt.plot(ages, reg.predict(ages), color="blue")
except NameError:
pass
plt.scatter(ages, net_worths)
plt.show() ### identify and remove the most outlier-y points
cleaned_data = []
try:
predictions = reg.predict(ages_train)
cleaned_data = outlierCleaner( predictions, ages_train, net_worths_train ) except NameError:
print ("your regression object doesn't exist, or isn't name reg")
print ("can't make predictions to use in identifying outliers") ### only run this code if cleaned_data is returning data
if len(cleaned_data) > 0:
ages, net_worths, errors = zip(*cleaned_data)
ages = numpy.reshape( numpy.array(ages), (len(ages), 1))
net_worths = numpy.reshape( numpy.array(net_worths), (len(net_worths), 1)) ### refit your cleaned data!
try:
reg.fit(ages, net_worths)
plt.plot(ages, reg.predict(ages), color="blue")
print (reg.coef_)
print (reg.intercept_)
print (reg.score(ages_test,net_worths_test) )
except NameError:
print ("you don't seem to have regression imported/created,")
print (" or else your regression object isn't named reg")
print (" either way, only draw the scatter plot of the cleaned data")
plt.scatter(ages, net_worths)
plt.xlabel("ages")
plt.ylabel("net worths")
plt.show() else:
print ("outlierCleaner() is returning an empty list, no refitting to be done")

outlier_cleaner.py  清除10%的异常值

import numpy as np
import math def outlierCleaner(predictions, ages, net_worths):
"""
Clean away the 10% of points that have the largest
residual errors (difference between the prediction
and the actual net worth).
Return a list of tuples named cleaned_data where
each tuple is of the form (age, net_worth, error).
""" cleaned_data = [] ages = ages.reshape((1,len(ages)))[0]
net_worths = net_worths.reshape((1,len(ages)))[0]
predictions = predictions.reshape((1,len(ages)))[0]
# zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。
cleaned_data = zip(ages,net_worths,abs(net_worths-predictions))
#按照error大小排序
cleaned_data = sorted(cleaned_data , key=lambda x: (x[2]))
#ceil() 函数返回数字的上入整数,计算要删除的元素个数
cleaned_num = int(-1 * math.ceil(len(cleaned_data)* 0.1))
#切片
cleaned_data = cleaned_data[:cleaned_num] return cleaned_data

同时得到这两次回归的拟合优度:

第一次:0.8782624703664675

第二次:0.983189455395532

可见,去除异常值对于预测数据具有重要作用

异常值(outlier)的更多相关文章

  1. python异常值(outlier)检测实战:KMeans + PCA + IsolationForest + SVM + EllipticEnvelope

    机器学习_深度学习_入门经典(博主永久免费教学视频系列) https://study.163.com/course/courseMain.htm?courseId=1006390023&sha ...

  2. SD与SE的关系,以及异常值

    很多刚进入实验室的同学对实验数据的标准差(SD)与标准误(SE)的含义搞不清,不知道自己的数据报告到底该用SD还是SE.这里对这两个概念进行一些介绍. 标准差(SD)强调raw data的Variat ...

  3. (转)Decision Tree

    Decision Tree:Analysis 大家有没有玩过猜猜看(Twenty Questions)的游戏?我在心里想一件物体,你可以用一些问题来确定我心里想的这个物体:如是不是植物?是否会飞?能游 ...

  4. 平均值(Mean)、方差(Variance)、标准差(Standard Deviation) (转)

    http://blog.csdn.net/xidiancoder/article/details/71341345 平均值 平均值的概念很简单:所有数据之和除以数据点的个数,以此表示数据集的平均大小: ...

  5. [译]用R语言做挖掘数据《六》

    异常值检测 一.实验说明 1. 环境登录 无需密码自动登录,系统用户名shiyanlou,密码shiyanlou 2. 环境介绍 本实验环境采用带桌面的Ubuntu Linux环境,实验中会用到程序: ...

  6. 支持向量机SVM、优化问题、核函数

    1.介绍 它是一种二类分类模型,其基本模型定义为特征空间上的间隔最大的线性分类器,即支持向量机的学习策略便是间隔最大化,最终可转化为一个凸二次规划问题的求解. 2.求解过程 1.数据分类—SVM引入 ...

  7. 【Udacity】数据的差异性:值域、IQR、方差和标准差

    一.值域(Range) Range = Max - Min 受异常值(Outliers)影响 二.四分位差(IQR) 四分位距(interquartile range, IQR),又称四分差.是描述统 ...

  8. 用随机森林分类器和GBDT进行特征筛选

    一.决策树(类型.节点特征选择的算法原理.优缺点.随机森林算法产生的背景) 1.分类树和回归树 由目标变量是离散的还是连续的来决定的:目标变量是离散的,选择分类树:反之(目标变量是连续的,但自变量可以 ...

  9. opencv之SURF图像匹配

    1.概述 前面介绍模板匹配的时候已经提到模板匹配时一种基于灰度的匹配方法,而基于特征的匹配方法有FAST.SIFT.SURF等.上面两篇文章已经介绍过使用Surf算法进行特征点检測以及使用暴力匹配(B ...

  10. ML-软间隔(slack)的 SVM

    Why Slack? 为了处理异常值(outlier). 前面推导的svm形式, 是要求严格地全部分对, 基于该情况下, 在margin 的边界线 线上的点, 只能是支持向量. \(min_w \ \ ...

随机推荐

  1. [ZOJ]3541 Last Puzzle (区间DP)

    ZOJ 3541 题目大意:有n个按钮,第i个按钮在按下ti 时间后回自动弹起,每个开关的位置是di,问什么策略按开关可以使所有的开关同时处于按下状态 Description There is one ...

  2. Oracle与Mysql内嵌游标的使用示例

    Oracle 游标用For循环比较简单,Mysql也是最近才开始用,感觉稍微麻烦一点,下边直接上代码: ------------------------------------------------ ...

  3. Context - React跨组件访问数据的利器

    Context提供了一种跨组件访问数据的方法.它无需在组件树间逐层传递属性,也可以方便的访问其他组件的数据 在经典的React应用中,数据是父组件通过props向子组件传递的.但是在某些特定场合,有些 ...

  4. Problem 3

    Problem 3 # Problem_3.py """ The prime factors of 13195 are 5, 7, 13 and 29. What is ...

  5. kfka学习笔记一:使用Python操作Kafka

    1.准备工作 使用python操作kafka目前比较常用的库是kafka-python库,但是在安装这个库的时候需要依赖setuptools库和six库,下面就要分别来下载这几个库 https://p ...

  6. 设计模式之二十:责任链模式(Chain of Responsibility)

    感觉这个设计模式和组合模式一样是一种非常巧妙的设计模式,在须要使用它的地方假设不使用这样的设计模式代码会变的非常复杂,可是这样的设计模式的基本原理又是非常easy的. 责任链模式: 通过使多个对象都有 ...

  7. Ruby中使用patch HTTP方法

    Ruby中使用patch HTTP方法 如果使用patch,在后台可以看到只更新了改动的部分: Started PATCH "/ads/5/update" for ::1 at 2 ...

  8. AWR系列之中的一个——AWR简单介绍

    AWR的全称是Automatic Workload Repository(自己主动负载知识库). 它是通过对照两次快照的方式收集到统计信息.来生成txt或者html页面形式的报告. 通常,通过AWR报 ...

  9. Oracle 位图索引

    内容简介: 1.位图索引 1.1位图索引使用注意事项; 1.2 使用位图索引; 1.3 位图索引对DML操作的影响; 2.位图连接索引 2.1 明确需求后使用位图索引; 2.1创建位图连接索引的注意事 ...

  10. 【转】C# ABP WebApi与Swagger UI的集成

    以前在做WebAPI调用测试时,一直在使用Fiddler测试工具了,而且这个用起来比较繁琐,需要各种配置,并且不直观,还有一点是还得弄明白URL地址和要传递的参数,然后才能调用.  最近新入职,公司里 ...