数据质量监控:YData Profiling的告警与异常检测

数据质量监控:YData Profiling的告警与异常检测

【免费下载链接】ydata-profiling ydataai/ydata-profiling: 是一个开源的数据探索和分析工具,用于快速分析和理解数据。它可以帮助开发者轻松发现数据中的规律和异常,提高数据分析和决策的准确性。特点包括易于使用、支持多种数据源、支持实时分析等。 【免费下载链接】ydata-profiling 项目地址: https://gitcode.com/gh_mirrors/yd/ydata-profiling

YData Profiling 提供了强大的数据质量问题自动识别与分类能力,通过内置的告警系统能够检测超过20种不同类型的数据质量问题。该系统基于统计学原理和机器学习方法,能够智能地识别数据集中的异常模式、数据质量问题以及潜在的数据清洗需求。告警系统采用层次化的分类体系,涵盖了数值型数据问题、分类数据问题、数据集级别问题、时间序列问题和相关性问题等多个维度,并提供了灵活的配置系统和阈值管理机制。

数据质量问题的自动识别与分类

YData Profiling 提供了强大的数据质量问题自动识别与分类能力,通过内置的告警系统能够检测超过20种不同类型的数据质量问题。这个系统基于统计学原理和机器学习方法,能够智能地识别数据集中的异常模式、数据质量问题以及潜在的数据清洗需求。

告警类型体系

YData Profiling 的告警系统采用层次化的分类体系,将数据质量问题分为以下几个主要类别:

1. 数值型数据问题
  • 常量值检测:识别数值列中所有值都相同的常量变量
  • 零值过多:检测数值列中零值占比过高的情况
  • 无限值存在:识别包含无穷大(inf)或无穷小(-inf)的数值
  • 偏斜分布:检测数值分布严重偏斜的情况(偏度 > 20)
  • 均匀分布:使用卡方检验识别过于均匀的数值分布
2. 分类数据问题
  • 高基数问题:识别分类变量中唯一值数量过多(默认阈值 > 50)
  • 类别不平衡:检测分类变量中某些类别占比过高的问题
  • 日期误识别:识别被错误归类为分类变量的日期数据
  • 恒定长度:检测文本字段长度完全一致的情况
  • 脏分类数据:识别包含模糊值或近似重复值的分类变量
3. 数据集级别问题
  • 空数据集:检测完全为空的数据框
  • 重复行:识别数据集中的完全重复行
  • 近似重复行:检测高度相似但不完全相同的行
4. 时间序列问题
  • 非平稳性:检测时间序列数据的平稳性问题
  • 季节性模式:识别时间序列中的季节性规律
5. 相关性问题
  • 高相关性:检测变量间的高度相关性(相关系数 > 0.9)

自动检测算法原理

YData Profiling 使用多种统计检验和机器学习算法来实现数据质量问题的自动检测:

统计检验方法
# 卡方检验用于检测分布均匀性
from scipy.stats import chi2_contingency

def chi_square_test(observed_frequencies):
    """执行卡方检验判断分布是否均匀"""
    chi2, p_value, dof, expected = chi2_contingency(observed_frequencies)
    return p_value > threshold  # p值大于阈值表示分布均匀
偏度检测算法
def detect_skewness(data, threshold=20):
    """检测数据偏度"""
    from scipy.stats import skew
    skewness = skew(data.dropna())
    return abs(skewness) > threshold
相关性检测
def detect_high_correlation(df, threshold=0.9):
    """检测高相关性变量"""
    corr_matrix = df.corr().abs()
    high_corr_pairs = []
    
    for i in range(len(corr_matrix.columns)):
        for j in range(i+1, len(corr_matrix.columns)):
            if corr_matrix.iloc[i, j] > threshold:
                high_corr_pairs.append((
                    corr_matrix.columns[i], 
                    corr_matrix.columns[j],
                    corr_matrix.iloc[i, j]
                ))
    
    return high_corr_pairs

配置与阈值管理

YData Profiling 提供了灵活的配置系统,允许用户自定义各种检测阈值:

vars:
  num:
    skewness_threshold: 20        # 偏度阈值
    chi_squared_threshold: 0.999  # 卡方检验p值阈值
  cat:
    cardinality_threshold: 50     # 高基数阈值
    imbalance_threshold: 0.8      # 不平衡阈值
correlations:
  pearson:
    threshold: 0.9                # 皮尔逊相关系数阈值
  spearman:
    threshold: 0.9                # 斯皮尔曼相关系数阈值

检测流程与分类逻辑

YData Profiling 的数据质量问题检测遵循严格的流程:

mermaid

实际应用示例

以下是一个完整的数据质量问题检测示例:

import pandas as pd
import numpy as np
from ydata_profiling import ProfileReport

# 创建包含多种数据质量问题的示例数据
data = {
    'constant_col': [1] * 100,  # 常量值
    'high_zeros': [0] * 80 + [1] * 20,  # 高零值占比
    'skewed_data': np.random.exponential(2, 100),  # 偏斜分布
    'high_cardinality': [f'category_{i}' for i in range(80)] + ['other'] * 20,  # 高基数
    'correlated_1': np.random.randn(100),
    'correlated_2': np.random.randn(100) * 0.1 + 0.9 * np.random.randn(100)  # 高相关性
}

df = pd.DataFrame(data)

# 生成数据质量报告
profile = ProfileReport(df, title="数据质量问题检测示例")
alerts = profile.get_description().alerts

print(f"检测到 {len(alerts)} 个数据质量问题:")
for alert in alerts:
    print(f"- {alert.alert_type_name}: {alert._get_description()}")

告警严重性分级

YData Profiling 的告警系统还支持严重性分级,帮助用户优先处理最重要的数据质量问题:

严重级别问题类型影响程度建议处理优先级
🔴 严重空数据集、常量值数据完全无效立即处理
🟡 警告高相关性、高基数影响分析准确性高优先级
🔵 提示轻微偏斜、轻微不平衡可能影响结果中等优先级
⚪ 信息分布特征、统计信息仅供参考低优先级

自定义检测规则

对于高级用户,YData Profiling 支持自定义数据质量检测规则:

from ydata_profiling.config import Settings
from ydata_profiling.model.alerts import AlertType, Alert

def custom_quality_check(config, series, summary):
    """自定义数据质量检测规则"""
    alerts = []
    
    # 自定义检测逻辑
    if series.name == 'special_column' and summary.get('n_distinct', 0) < 5:
        alerts.append(Alert(
            alert_type=AlertType.CUSTOM,
            values=summary,
            column_name=series.name
        ))
    
    return alerts

# 应用自定义检测规则
config = Settings()
config.custom_checks = [custom_quality_check]

集成与自动化

YData Profiling 的数据质量问题检测可以轻松集成到数据管道中:

from ydata_profiling import ProfileReport
import pandas as pd

class DataQualityMonitor:
    def __init__(self, config_path=None):
        self.config = self._load_config(config_path)
    
    def monitor_quality(self, df, output_path=None):
        """监控数据质量并生成报告"""
        profile = ProfileReport(df, config=self.config)
        
        if output_path:
            profile.to_file(output_path)
        
        return profile.get_description().alerts
    
    def _load_config(self, config_path):
        """加载配置"""
        if config_path:
            return Settings().from_file(config_path)
        return Settings()

# 在数据管道中使用
quality_monitor = DataQualityMonitor()
alerts = quality_monitor.monitor_quality(df, "quality_report.html")

通过这种系统化的数据质量问题自动识别与分类,YData Profiling 帮助数据科学家和分析师快速发现数据中的问题,提高数据质量,确保分析结果的可靠性。

相关性分析:Pearson、Spearman、Kendall等

在数据质量监控中,相关性分析是识别变量间关系强度的关键工具。YData Profiling提供了多种相关性分析方法,帮助用户发现数据中的潜在模式和异常关系。本节将深入探讨Pearson、Spearman、Kendall等相关系数的原理、应用场景以及在YData Profiling中的实现。

相关性分析方法概述

YData Profiling支持以下主要相关性分析方法:

方法适用场景值域特点
Pearson相关系数连续变量间的线性关系[-1, 1]测量线性相关程度
Spearman等级相关系数顺序变量或非线性关系[-1, 1]基于秩次的非参数方法
Kendall等级相关系数小样本或存在大量相同值[-1, 1]更稳健的秩相关方法
Cramér's V系数分类变量间的关系[0, 1]基于卡方检验的关联度量
Phik系数混合类型变量关系[0, 1]适用于数值和分类变量

Pearson相关系数

Pearson相关系数衡量两个连续变量之间的线性相关程度,是最常用的相关性度量方法。

数学公式:

ρ = Σ[(xi - x̄)(yi - ȳ)] / √[Σ(xi - x̄)² Σ(yi - ȳ)²]

YData Profiling实现:

def pearson_compute(config: Settings, df: pd.DataFrame, summary: dict) -> Optional[pd.DataFrame]:
    df_aux = df.select_dtypes(include="number").copy()
    return df_aux.corr(method="pearson")

应用场景:

  • 检验线性关系假设
  • 识别多重共线性问题
  • 特征选择中的冗余变量检测

Spearman等级相关系数

Spearman相关系数基于变量的秩次而非原始值,适用于非线性但单调的关系。

数学公式:

ρ = 1 - (6Σdi²)/(n(n²-1))
其中di为每对观测值的秩次差

YData Profiling实现:

def spearman_compute(config: Settings, df: pd.DataFrame, summary: dict) -> Optional[pd.DataFrame]:
    df_aux = df.select_dtypes(include="number").copy()
    return df_aux.corr(method="spearman")

优势:

  • 对异常值不敏感
  • 适用于非正态分布数据
  • 能够检测单调非线性关系

Kendall等级相关系数

Kendall相关系数通过计算一致对和不一致对的比例来度量相关性,特别适用于小样本数据。

数学公式:

τ = (nc - nd) / √[(n(n-1)/2 - T)(n(n-1)/2 - U)]
其中nc为一致对数量,nd为不一致对数量

YData Profiling实现:

def kendall_compute(config: Settings, df: pd.DataFrame, summary: dict) -> Optional[pd.DataFrame]:
    df_aux = df.select_dtypes(include="number").copy()
    return df_aux.corr(method="kendall")

适用情况:

  • 样本量较小
  • 数据中存在大量相同值
  • 需要更稳健的相关性估计

自动相关性检测(Auto模式)

YData Profiling的Auto模式智能选择最适合的相关性计算方法:

mermaid

Auto模式实现逻辑:

def auto_compute(config: Settings, df: pd.DataFrame, summary: dict) -> Optional[pd.DataFrame]:
    # 识别数值型和分类型变量
    numerical_columns = [key for key, value in summary.items() 
                        if value["type"] in {"Numeric", "TimeSeries"} and value["n_distinct"] > 1]
    categorical_columns = [key for key, value in summary.items() 
                          if value["type"] in {"Categorical", "Boolean"} 
                          and 1 < value["n_distinct"] <= threshold]
    
    # 智能选择计算方法
    method = _pairwise_spearman if not any(elem in categorical_columns for elem in [col_1_name, col_2_name]) else _pairwise_cramers

相关性警告与异常检测

YData Profiling通过阈值检测识别高度相关的变量对:

def perform_check_correlation(correlation_matrix: pd.DataFrame, threshold: float) -> Dict[str, List[str]]:
    """检查相关性矩阵中超过阈值的变量对"""
    cols = correlation_matrix.columns
    bool_index = abs(correlation_matrix.values) >= threshold
    np.fill_diagonal(bool_index, False)
    return {
        col: cols[bool_index[i]].values.tolist()
        for i, col in enumerate(cols)
        if any(bool_index[i])
    }

告警机制:

  • 默认阈值:0.9
  • 支持自定义阈值配置
  • 生成详细的告警信息,包括相关变量名称和相关系数类型

配置与使用示例

基本配置:

correlations:
  pearson:
    calculate: true
    warn_high_correlations: true
    threshold: 0.9
  spearman:
    calculate: true
    warn_high_correlations: false
    threshold: 0.9
  kendall:
    calculate: true
    warn_high_correlations: false
    threshold: 0.9

代码示例:

import pandas as pd
import numpy as np
from ydata_profiling import ProfileReport

# 创建示例数据
np.random.seed(42)
df = pd.DataFrame({
    'feature1': np.random.normal(0, 1, 1000),
    'feature2': np.random.normal(0, 1, 1000) * 0.8 + df['feature1'] * 0.2,
    'category': np.random.choice(['A', 'B', 'C'], 1000)
})

# 配置相关性分析
profile = ProfileReport(df, 
                       correlations={
                           'pearson': {'calculate': True, 'threshold': 0.8},
                           'spearman': {'calculate': True},
                           'auto': {'calculate': True}
                       })

# 生成报告
profile.to_file("correlation_analysis.html")

可视化输出

YData Profiling生成丰富的可视化结果:

  1. 热力图展示:使用颜色梯度直观显示相关系数大小
  2. 数值表格:提供精确的相关性系数数值
  3. 交互式探索:支持点击查看详细的相关性信息

热力图生成逻辑:

def correlation_matrix(config: Settings, data: pd.DataFrame, vmin: int = -1) -> str:
    """生成相关性矩阵热力图"""
    cmap = plt.get_cmap(config.plot.correlation.cmap)
    if vmin == 0:
        cmap = get_cmap_half(cmap)  # 对于[0,1]范围的相关性
    matrix_image = axes_cor.imshow(data, vmin=vmin, vmax=1, interpolation="nearest", cmap=cmap)

最佳实践建议

  1. 多重共线性检测:使用Pearson相关系数识别高度相关的特征对
  2. 非线性关系探索:结合Spearman和Kendall方法发现非线性模式
  3. 混合数据类型:利用Auto模式自动处理数值和分类变量的混合情况
  4. 阈值调整:根据业务需求调整相关性告警阈值
  5. 周期性检查:将相关性分析纳入数据质量监控的常规流程

通过YData Profiling提供的多种相关性分析方法,数据工程师和分析师能够全面了解数据集中的变量关系,及时发现数据质量问题,为后续的数据清洗、特征工程和模型构建奠定坚实基础。

缺失值模式分析与可视化

在数据质量监控体系中,缺失值分析是至关重要的环节。YData Profiling 提供了强大的缺失值模式识别和可视化功能,能够帮助数据工程师和分析师快速识别数据中的缺失模式,为后续的数据清洗和质量改进提供有力支撑。

缺失值可视化类型

YData Profiling 提供了三种主要的缺失值可视化图表,每种图表都针对不同的分析场景:

1. 缺失值条形图(Missing Bar Chart)

缺失值条形图是最直观的缺失值分析工具,它以柱状图的形式展示每个字段的缺失值数量或比例。

import pandas as pd
import numpy as np
from ydata_profiling import ProfileReport

# 创建包含缺失值的示例数据
data = {
    'age': [25, 30, np.nan, 35, 40, np.nan, 45],
    'income': [50000, np.nan, 70000, 80000, np.nan, 90000, 100000],
    'education': ['Bachelor', 'Master', np.nan, 'PhD', 'Bachelor', np.nan, 'Master'],
    'experience': [2, 5, np.nan, 10, 3, 8, np.nan]
}

df = pd.DataFrame(data)
profile = ProfileReport(df, title="缺失值分析示例")
profile.to_file("missing_analysis.html")

生成的条形图会显示:

  • 每个字段的非空值数量
  • 缺失值的绝对数量和相对比例
  • 字段按照缺失值数量排序
2. 缺失值矩阵(Missing Matrix)

缺失值矩阵提供了数据级别的缺失模式视图,能够识别记录级别的缺失模式。

# 创建更复杂的缺失模式数据
np.random.seed(42)
data_complex = pd.DataFrame({
    'var1': np.random.choice([1, 2, np.nan], 100, p=[0.7, 0.2, 0.1]),
    'var2': np.random.choice([10, 20, np.nan], 100, p=[0.6, 0.3, 0.1]),
    'var3': np.random.choice([100, 200, np.nan], 100, p=[0.8, 0.1, 0.1]),
    'var4': np.random.choice([1000, 2000, np.nan], 100, p=[0.9, 0.05, 0.05])
})

profile_complex = ProfileReport(data_complex, title="复杂缺失模式分析")

矩阵图的特点:

  • 每个点代表一个数据点(存在值=白色,缺失值=黑色)
  • 可以识别系统性的缺失模式
  • 发现记录级别的数据完整性模式
3. 缺失值热力图(Missing Heatmap)

缺失值热力图展示字段间缺失值的相关性,帮助识别字段间的依赖关系。

# 创建具有相关缺失模式的数据
data_correlated = pd.DataFrame({
    'salary': np.random.choice([50000, 60000, np.nan], 200, p=[0.4, 0.4, 0.2]),
    'bonus': np.random.choice([5000, 10000, np.nan], 200, p=[0.4, 0.4, 0.2]),
    'age': np.random.choice([25, 30, 35, np.nan], 200, p=[0.3, 0.3, 0.3, 0.1]),
    'department': np.random.choice(['IT', 'HR', 'Finance', np.nan], 200, p=[0.4, 0.3, 0.2, 0.1])
})

# 人为创建相关性:当salary缺失时,bonus也倾向于缺失
mask = data_correlated['salary'].isna()
data_correlated.loc[mask, 'bonus'] = np.nan

profile_correlated = ProfileReport(data_correlated, title="相关缺失模式分析")

热力图的分析价值:

  • 颜色深浅表示缺失值相关性强度
  • 识别字段间的缺失依赖关系
  • 发现数据收集过程中的系统性问题

缺失模式识别算法

YData Profiling 使用先进的算法来识别和分析缺失模式:

缺失值统计计算
# 缺失值统计计算过程
def calculate_missing_stats(df):
    missing_stats = {}
    for column in df.columns:
        missing_count = df[column].isna().sum()
        total_count = len(df)
        missing_percentage = (missing_count / total_count) * 100
        
        missing_stats[column] = {
            'missing_count': missing_count,
            'total_count': total_count,
            'missing_percentage': missing_percentage,
            'data_type': df[column].dtype
        }
    return missing_stats
相关性分析算法
# 缺失值相关性计算
def calculate_missing_correlation(df):
    # 创建缺失指示矩阵
    missing_matrix = df.isnull().astype(int)
    
    # 计算字段间的缺失相关性
    correlation_matrix = missing_matrix.corr()
    
    return correlation_matrix

配置选项与自定义

YData Profiling 提供了丰富的配置选项来自定义缺失值分析:

from ydata_profiling import ProfileReport
from ydata_profiling.config import Settings

# 自定义配置
config = Settings()
config.missing_diagrams = {
    "bar": True,      # 启用条形图
    "matrix": True,   # 启用矩阵图  
    "heatmap": True   # 启用热力图
}

config.plot.missing.cmap = "RdBu"  # 设置颜色映射
config.plot.missing.force_labels = True  # 强制显示标签

# 应用配置生成报告
profile = ProfileReport(df, config=config)

高级缺失模式分析

对于复杂的数据集,YData Profiling 能够识别多种缺失模式:

完全随机缺失(MCAR)

mermaid

随机缺失(MAR)

mermaid

非随机缺失(MNAR)

mermaid

实际应用案例

电商数据缺失分析
# 模拟电商数据缺失分析
ecommerce_data = pd.DataFrame({
    'user_id': range(1000),
    'purchase_amount': np.random.exponential(100, 1000),
    'user_age': np.random.choice([18, 25, 35, 45, 55, np.nan], 1000, p=[0.2, 0.2, 0.2, 0.2, 0.1, 0.1]),
    'user_income': np.random.choice([30000, 50000, 80000, np.nan], 1000, p=[0.3, 0.3, 0.3, 0.1]),
    'purchase_category': np.random.choice(['Electronics', 'Clothing', 'Food', np.nan], 1000, p=[0.4, 0.3, 0.2, 0.1])
})

# 生成详细的缺失分析报告
ecommerce_profile = ProfileReport(
    ecommerce_data, 
    title="电商数据缺失模式分析",
    explorative=True
)
医疗数据质量监控
# 医疗数据缺失模式监控
medical_data = pd.DataFrame({
    'patient_id': range(500),
    'age': np.random.normal(45, 15, 500),
    'blood_pressure': np.random.choice([120, 130, 140, np.nan], 500, p=[0.3, 0.3, 0.3, 0.1]),
    'cholesterol': np.random.choice([180, 200, 220, np.nan], 500, p=[0.4, 0.3, 0.2, 0.1]),
    'diabetes': np.random.choice([0, 1, np.nan], 500, p=[0.7, 0.2, 0.1])
})

# 重点关注敏感数据的缺失情况
medical_profile = ProfileReport(
    medical_data,
    title="医疗数据质量报告",
    sensitive=True  # 启用敏感数据处理
)

缺失值处理建议

基于分析结果,YData Profiling 会提供针对性的处理建议:

缺失模式处理建议适用场景
MCAR < 5%删除缺失记录数据量充足时
MCAR 5-20%均值/中位数填充数值型变量
MAR回归填充有相关变量时
MNAR模型预测填充复杂缺失模式
高比例缺失考虑删除变量>50%缺失率

可视化配置优化

为了获得最佳的缺失值可视化效果,可以调整以下参数:

# 优化可视化配置
optimized_config = Settings()
optimized_config.html.style.primary_colors = ["#1f77b4", "#ff7f0e", "#2ca02c"]
optimized_config.plot.missing.cmap = "viridis"
optimized_config.plot.missing.force_labels = False  # 自动调整标签显示

# 应用优化配置
optimized_profile = ProfileReport(df, config=optimized_config)

通过 YData Profiling 的缺失值模式分析与可视化功能,数据团队能够:

  • 快速识别数据质量问题
  • 理解缺失值的分布和模式
  • 制定有效的数据清洗策略
  • 监控数据质量改进效果
  • 为机器学习模型提供高质量的训练数据

这种系统化的缺失值分析方法极大地提高了数据质量管理的效率和效果,为数据驱动的决策提供了可靠的基础。

异常值检测与数据分布评估

在数据质量监控体系中,异常值检测与数据分布评估是至关重要的环节。YData Profiling通过先进的统计算法和可视化技术,为数据科学家提供了全面的异常检测和数据分布分析能力。

异常值检测机制

YData Profiling采用多维度异常检测策略,能够自动识别数据中的各种异常模式:

1. 偏度检测 (Skewness Detection)

系统通过计算偏度系数来识别数据分布的偏斜程度:

def skewness_alert(v: float, threshold: int) -> bool:
    """检测偏度异常
    Args:
        v: 偏度系数值
        threshold: 阈值配置
    Returns:
        bool: 是否触发异常警报
    """
    return not pd.isna(v) and (v < (-1 * threshold) or v > threshold)

偏度检测的阈值默认为20,可通过配置文件调整:

vars:
  num:
    skewness_threshold: 20
2. 零值异常检测

系统统计零值比例并触发警报:

# 零值统计计算
summary["n_zeros"] = 0
if 0 in value_counts.index:
    summary["n_zeros"] = value_counts.loc[0]
summary["p_zeros"] = summary["n_zeros"] / summary["n"]
3. 无限值检测

识别包含无限值的数据列:

infinity_values = [np.inf, -np.inf]
infinity_index = value_counts.index.isin(infinity_values)
summary["n_infinite"] = value_counts.loc[infinity_index].sum()
summary["p_infinite"] = summary["n_infinite"] / summary["n"]

数据分布评估

YData Profiling提供全面的数据分布分析功能:

1. 分布均匀性检验

使用卡方检验评估数据分布的均匀性:

def chi_square(values: Optional[np.ndarray] = None, 
               histogram: Optional[np.ndarray] = None) -> dict:
    """执行卡方检验评估分布均匀性"""
    if histogram is None:
        bins = np.histogram_bin_edges(values, bins="auto")
        histogram, _ = np.histogram(values, bins=bins)
    if len(histogram) == 0 or np.sum(histogram) == 0:
        return {"statistic": 0, "pvalue": 0}
    return dict(chisquare(histogram)._asdict())
2. 直方图分析

系统自动生成数据分布的直方图:

def histogram_compute(config: Settings, finite_values: np.ndarray, 
                     n_unique: int, name: str = "histogram", 
                     weights: Optional[np.ndarray] = None) -> dict:
    """计算直方图统计数据"""
    stats = {}
    if len(finite_values) == 0:
        return {name: []}
    
    hist_config = config.plot.histogram
    bins_arg = "auto" if hist_config.bins == 0 else min(hist_config.bins, n_unique)
    bins = np.histogram_bin_edges(finite_values, bins=bins_arg)
    
    if len(bins) > hist_config.max_bins:
        bins = np.histogram_bin_edges(finite_values, bins=hist_config.max_bins)
        weights = weights if weights and len(weights) == hist_config.max_bins else None

    stats[name] = np.histogram(
        finite_values, bins=bins, weights=weights, 
        density=config.plot.histogram.density
    )
    return stats

统计指标计算

YData Profiling计算丰富的统计指标来评估数据分布:

描述性统计量
def numeric_stats_pandas(series: pd.Series) -> Dict[str, Any]:
    """计算数值型数据的描述性统计"""
    return {
        "mean": series.mean(),        # 均值
        "std": series.std(),          # 标准差
        "variance": series.var(),     # 方差
        "min": series.min(),          # 最小值
        "max": series.max(),          # 最大值
        "kurtosis": series.kurt(),    # 峰度
        "skewness": series.skew(),    # 偏度
        "sum": series.sum(),          # 总和
    }
稳健统计量
def mad(arr: np.ndarray) -> np.ndarray:
    """计算中位数绝对偏差(MAD) - 稳健的离散度度量"""
    return np.median(np.abs(arr - np.median(arr)))

异常检测流程

YData Profiling的异常检测遵循系统化的流程:

mermaid

配置参数详解

用户可以通过配置文件精细调整异常检测参数:

vars:
  num:
    skewness_threshold: 20          # 偏度阈值
    chi_squared_threshold: 0.999    # 卡方检验p值阈值
    quantiles:                      # 分位数计算
      - 0.05
      - 0.25
      - 0.5
      - 0.75
      - 0.95

plot:
  histogram:
    bins: 50                       # 直方图箱数
    max_bins: 250                  # 最大箱数
    density: false                 # 是否显示密度

实际应用示例

以下是一个完整的异常值检测示例:

import pandas as pd
import numpy as np
from ydata_profiling import ProfileReport

# 创建包含异常值的数据
data = {
    'normal_data': np.random.normal(0, 1, 1000),
    'skewed_data': np.concatenate([np.random.normal(0, 1, 900), 
                                 np.random.normal(10, 2, 100)]),
    'zero_inflated': np.concatenate([np.zeros(200), 
                                   np.random.normal(5, 1, 800)]),
    'with_inf': np.concatenate([np.random.normal(0, 1, 990),
                              [np.inf, -np.inf, np.inf, -np.inf, np.inf]])
}

df = pd.DataFrame(data)

# 生成分析报告
profile = ProfileReport(df, title="异常值检测示例")
profile.to_file("anomaly_detection_report.html")

检测结果解读

YData Profiling生成的报告包含以下关键信息:

检测类型指标说明异常阈值
偏度异常skewness数据分布不对称程度 skewness> 20
零值异常p_zeros零值比例p_zeros > 0.1
无限值p_infinite无限值比例p_infinite > 0
均匀分布chi_squared pvalue分布均匀性检验pvalue > 0.999

高级特性

1. 自定义异常阈值

用户可以根据业务需求调整异常检测阈值:

from ydata_profiling import ProfileReport
from ydata_profiling.config import Settings

config = Settings()
config.vars.num.skewness_threshold = 10  # 更严格的偏度检测
config.vars.num.chi_squared_threshold = 0.95  # 更宽松的均匀性检测

profile = ProfileReport(df, config=config)
2. 多维度异常关联分析

系统能够识别异常模式之间的关联关系,例如高偏度与特定数据范围的关联性。

3. 时间序列异常检测

对于时间序列数据,提供额外的异常检测能力:

config = Settings()
config.vars.timeseries.active = True
config.vars.timeseries.autocorrelation = 0.7

# 时间序列特定的异常检测
profile = ProfileReport(time_series_df, config=config, tsmode=True)

通过这套完善的异常值检测与数据分布评估体系,YData Profiling为用户提供了深度洞察数据质量的能力,帮助及时发现数据问题并采取相应的处理措施。

总结

YData Profiling 提供了全面的异常值检测与数据分布评估能力,通过多维度异常检测策略包括偏度检测、零值异常检测、无限值检测等,结合丰富的统计指标计算和可视化技术,帮助用户深度洞察数据质量问题。系统支持自定义异常阈值配置,能够识别异常模式之间的关联关系,并为时间序列数据提供专门的异常检测功能。这套完善的异常检测体系为用户提供了强大的数据质量监控能力,帮助及时发现数据问题并采取相应的处理措施,确保数据分析结果的可靠性和准确性。

【免费下载链接】ydata-profiling ydataai/ydata-profiling: 是一个开源的数据探索和分析工具,用于快速分析和理解数据。它可以帮助开发者轻松发现数据中的规律和异常,提高数据分析和决策的准确性。特点包括易于使用、支持多种数据源、支持实时分析等。 【免费下载链接】ydata-profiling 项目地址: https://gitcode.com/gh_mirrors/yd/ydata-profiling

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值