读书笔记--python数据可视化--007_清理异常值

#-*- coding: UTF-8 -*-
'''
 #################################################  
 # Author : 余欢
 # Date : Dec 28, 2015    4:09:29 PM
 #company : 南京师范大学--大数据实验室
 # description : 清理异常值
 ################################################# 
'''

'''
1  生成0~1之间的随机数据;
2  加入一些异常值;
3  用is_outlier()方法检测异常值;
4  绘制出两个数据的集合(x和filtered)的图表,观察他们的区别。
'''

import numpy as np
import matplotlib.pyplot as plt

def is_outlier(points, threshold=3.5):
    """
    返回一个布尔型的数组,如果数据点是异常值返回True,反之,返回False。

    数据点的值不在阈值范围内将被定义为异常值
    阈值默认为3.5
    """
    # 转化为向量
    if len(points.shape) == 1:
        points = points[:,None]

    # 数组的中位数
    median = np.median(points, axis=0)

    # 计算方差
    diff = np.sum((points - median)**2, axis=-1)
    #标准差
    diff = np.sqrt(diff)
    # 中位数绝对偏差
    med_abs_deviation = np.median(diff)

    # compute modified Z-score
    # http://www.itl.nist.gov/div898/handbook/eda/section4/eda43.htm#Iglewicz
    modified_z_score = 0.6745 * diff / med_abs_deviation

    # return a mask for each outlier
    return modified_z_score > threshold

# 随机数据(100个在0~1之间的浮点数)
x = np.random.random(100)

# 直方图桶数量
buckets = 50

# 加入一些异常值
x = np.r_[x, -49, 95, 100, -100]

# Keep inlier data points
# "~"操作符被重载为一个逻辑操作符,作用在布尔数组上时为取非操作
filtered = x[~is_outlier(x)]

# 画一个直方图
plt.figure()

plt.subplot(211)
plt.hist(x, buckets)
plt.xlabel('Raw')

plt.subplot(212)
plt.hist(filtered, buckets)
plt.xlabel('Cleaned')

plt.show()
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值