
























标准差(Standard Deviation)是统计学中用于衡量数据分散程度的重要指标。它表示数据点与数据集平均值(均值)之间的偏离程度。标准差越大,说明数据分布越分散;标准差越小,说明数据分布越集中。
Z分数异常检测,是一种基于统计学的异常检测方法,通过计算数据点的Z分数(Z-score)来判断其是否为异常值。Z分数反映了数据点与数据集均值之间的偏离程度,以标准差为单位。
Z分数的计算公式为:Z =(X−μ)/σ
其中:
Z 分数的意义:
以下示例数据(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()
将代码保存为 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

可见,通过Z分数成功识别了示例数据中的异常值。
需要注意的是,通过Z分数进行异常数据检测,只是异常数据检测中的基础方法之一,只在限定的条件下适用。
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。