惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

TaoSecurity Blog
TaoSecurity Blog
T
Troy Hunt's Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Vercel News
Vercel News
T
Threatpost
G
Google Developers Blog
T
Threat Research - Cisco Blogs
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
T
The Exploit Database - CXSecurity.com
H
Heimdal Security Blog
Google DeepMind News
Google DeepMind News
Cyberwarzone
Cyberwarzone
T
The Blog of Author Tim Ferriss
Know Your Adversary
Know Your Adversary
Hacker News: Ask HN
Hacker News: Ask HN
www.infosecurity-magazine.com
www.infosecurity-magazine.com
S
Schneier on Security
B
Blog
V2EX - 技术
V2EX - 技术
NISL@THU
NISL@THU
C
CERT Recently Published Vulnerability Notes
W
WeLiveSecurity
C
Cybersecurity and Infrastructure Security Agency CISA
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Y
Y Combinator Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Spread Privacy
Spread Privacy
The Last Watchdog
The Last Watchdog
V
Vulnerabilities – Threatpost
N
Netflix TechBlog - Medium
Schneier on Security
Schneier on Security
F
Fortinet All Blogs
N
News | PayPal Newsroom
Attack and Defense Labs
Attack and Defense Labs
Blog — PlanetScale
Blog — PlanetScale
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Microsoft Security Blog
Microsoft Security Blog
S
Security @ Cisco Blogs
人人都是产品经理
人人都是产品经理
爱范儿
爱范儿
P
Privacy & Cybersecurity Law Blog
P
Proofpoint News Feed
Project Zero
Project Zero
I
Intezer
罗磊的独立博客
H
Hackread – Cybersecurity News, Data Breaches, AI and More
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - Franky
SecWiki News
SecWiki News
Martin Fowler
Martin Fowler

博客园 - ffb

一次AI辅助调试记录(2024年文章补发) 最廉价的5.1家庭影院系统解决方案 2023年如何选购一部4000元价位的笔记本电脑(附带坑的说明) 使用chatGPT聊天到底要花多少钱? 大家是如何利用AI来挣钱的 跑在笔记本里的大语言模型 - GPT4All AI人工智能简史 这些AI绘画工具教你秒变艺术大师! 最强绘图AI:一文搞定Midjourney(附送咒语) 微软产品和中文输入法相关的一些缺陷 在MacAir上搭建人工智能AI画图环境 Excel无法vlookup事件 不高级不能发帖的WPS论坛 打不开盖子的酸奶 无意中发现的一个好设计:不浸水的香皂盒 几件小事 网络相册产品分析(一):十年需求变迁 微盘产品分析(零):时代向前走了一步 网易云音乐点评(一):音乐应用的播放列表 豆瓣音乐使用体验(一):iPad一直很抱歉 ipad上的电子阅读器们
Z分数异常数据检测方法
ffb · 2026-06-04 · via 博客园 - ffb

Z分数异常数据检测方法

标准差(Standard Deviation)是统计学中用于衡量数据分散程度的重要指标。它表示数据点与数据集平均值(均值)之间的偏离程度。标准差越大,说明数据分布越分散;标准差越小,说明数据分布越集中。

Z分数异常检测,是一种基于统计学的异常检测方法,通过计算数据点的Z分数(Z-score)来判断其是否为异常值。Z分数反映了数据点与数据集均值之间的偏离程度,以标准差为单位。

适用场景

  • 数据近似服从正态分布(或至少是对称分布),例如:金融数据(如股票收益率)、考试成绩、生产质量数据(如产品尺寸、重量)
  • 需要快速识别极端值的时候,例如:传感器数据中的异常值、网络流量中的异常行为、财务数据中的异常交易等
  • 数据标准化需求,例如机器学习中的数据预处理、多指标综合评价(如学生成绩、员工绩效)
  • 异常值定义明确的场景

计算公式

Z分数的计算公式为:Z =(X−μ)/σ

其中:

  • X:某个数据点的值
  • μ:数据集的均值(平均值)
  • σ:数据集的标准差

Z 分数的意义:

  • Z=0:数据点等于均值
  • Z>0:数据点高于均值
  • Z<0:数据点低于均值

原理说明

  • 如果某个数据点的 Z 分数绝对值较大(即远离均值),则该数据点可能是异常值
  • 通常,设定一个阈值(如 Z=3 或 Z=2),如果数据点的 Z 分数绝对值超过该阈值,则认为它是异常值

阈值选择

  • ∣Z∣ > 3:适用于严格检测,只有非常极端的数据点才会被标记为异常
  • ∣Z∣ > 2:适用于一般检测,可能会标记更多的潜在异常值

示例数据说明

以下示例数据(data.csv)中,构造了一组随机数,并人为修改了其中几个让其z分数大于3来模拟异常情况;

63.75,62.43,51.79,42.50,57.78,30.53,38.54,56.05,44.12,37.44,206.71,55.50,56.02,40.32,40.78,46.88,30.66,40.39,68.34,31.88,58.10,35.47,69.57,59.48,66.84,45.56,34.63,43.30,46.87,48.85,45.41,34.33,65.25,34.86,35.52,50.05,65.33,55.70,68.85,57.02,64.62,35.78,39.80,69.44,62.43,39.23,43.59,38.58,45.01,36.83,36.40,52.71,63.07,52.09,39.17,40.18,39.03,65.55,31.97,50.84,57.35,129.51,134.86,121.94,132.03,130.88,130.33,128.39,202.08,208.72,100.55,239.86,130.93,111.57,101.99,105.49,116.00,107.51,111.02,131.58,107.05,136.89,111.09,124.50,103.30,107.55,55.65,31.15,48.87,36.01,57.97,47.08,32.42,51.04,55.61,68.73,68.66,36.25,57.20,62.03

代码实现

StandardScaler 是 Python 机器学习库 scikit-learn(sklearn)中的一个数据预处理工具,用于对数据进行标准化处理。使用python调用StandardScaler完成Z分数计算:

import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt
from matplotlib import font_manager
import os

def setup_font():
    potential_fonts = [
        '/usr/share/fonts/truetype/wqy/wqy-microhei.ttc',
        '/usr/share/fonts/wqy-microhei/wqy-microhei.ttc',
    ]
    
    for font_path in potential_fonts:
        if os.path.exists(font_path):
            font_manager.fontManager.addfont(font_path)
            plt.rcParams['font.family'] = font_manager.FontProperties(fname=font_path).get_name()
            break
    plt.rcParams['axes.unicode_minus'] = False

def load_data(file_path):
    data = pd.read_csv(file_path, header=None)
    return data.iloc[0].values

def detect_anomalies_zscore(data, threshold=3):
    scaler = StandardScaler()
    z_scores = scaler.fit_transform(data.reshape(-1, 1))
    return (abs(z_scores) > threshold).ravel()

def plot_results(data, anomalies, output_path='zscore_anomalies.png'):
    plt.figure(figsize=(15, 5))
    plt.plot(range(len(data)), data, label='原始数据')
    anomaly_indices = np.where(anomalies)[0]
    anomaly_values = data[anomaly_indices]
    plt.scatter(anomaly_indices, anomaly_values, color='red', label='异常值')
    plt.title('使用Z-score方法检测的异常值')
    plt.legend()
    plt.tight_layout()
    plt.savefig(output_path)
    plt.close()

def main():
    setup_font()
    data = load_data('data.csv')
    
    anomalies = detect_anomalies_zscore(data, threshold=3)
    print(f'Z-score方法检测到 {sum(anomalies)} 个异常值')
    
    plot_results(data, anomalies)
    
    print("\n详细的异常值信息:")
    anomaly_indices = np.where(anomalies)[0]
    anomaly_values = data[anomaly_indices]
    for idx, value in zip(anomaly_indices, anomaly_values):
        print(f"索引: {idx}, 值: {value:.2f}")

if __name__ == "__main__":
    main() 

代码说明

  • pandas:数据分析和处理库,用于数据的导入和基本处理,例如数据清洗和预处理、数据重塑和透视、时间序列处理、数据合并和连接、统计分析、数据可视化等
    • read_csv():读取CSV格式的数据文件
      • iloc[]:索引器,用于按位置进行整数索引
        • values[]:将pandas对象转换为NumPy数组
          • reshape():重塑数组的形状
  • numpy:数学和科学计算库,用于数值计算、数组和矩阵操作等
    • where():条件判断,用于判断数组中的元素是否满足某个条件
  • sklearn:机器学习库,用于数据预处理、模型训练和评估等
    • preprocessing:数据预处理,包括标准化、缩放等
      • StandardScaler:标准化数据,将特征缩放到标准化的分布(均值为0,标准差为1)
        • fit_transform():拟合并转换数据
  • matplotlib:数据可视化库,用于绘图、图表、图形和动画等
    • font_manager:字体管理,用于设置字体和字号等,解决中文问题
    • pyplot:绘图工具,用于生成静态图形和动态图形
      • figure:创建图形对象,用于绘制图形和图表
      • plot:绘制图形,用于绘制折线图、柱状图等
      • scatter:绘制散点图,用于显示数据点
      • title:设置图形标题
      • legend:设置图例
      • tight_layout:自动调整子图布局
      • savefig:保存图形,用于保存绘制的图形
      • close:关闭图形,用于关闭绘制的图形

异常数据识别

将代码保存为 z-score.py,执行得到结果,并在生成的图片zscore_anomalies.png中标识异常位置。

python z-score.py
Z-score方法检测到 4 个异常值

详细的异常值信息:
索引: 10, 值: 206.71
索引: 68, 值: 202.08
索引: 69, 值: 208.72
索引: 71, 值: 239.86

2025-0204-zscore_anomalies

可见,通过Z分数成功识别了示例数据中的异常值。

注意事项

需要注意的是,通过Z分数进行异常数据检测,只是异常数据检测中的基础方法之一,只在限定的条件下适用。