Skip to content

XiaoMaColtAI/math-modeling-skill / dsh-plugin/math-modeling-agent/skills/math-modeling

math-modeling

Verified

当用户要求数学建模、建模竞赛、建模分析、代码求解、结果可视化或生成数学建模论文时使用。支持完整三阶段流程、单独执行任一角色,以及在关键节点使用独立 Subagent 进行阶段内质检;默认只启用质检 Subagent,用户可明确选择额外协作。

assets/05-统计分析与数据处理算法说明.md

View on GitHub
# 统计分析与数据处理算法说明文档

## 概述

统计分析与数据处理是数学建模的基础,用于数据预处理、模式识别、假设检验、分类聚类等。这些算法广泛应用于数据挖掘、机器学习、生物统计、社会科学等领域。

---

## 1. 数据预处理 (Data Preprocessing)

### 算法介绍

数据预处理是数据分析的第一步,包括数据清洗、变换、归约等操作。

#### 1.1 缺失值处理

**删除法**:删除含有缺失值的样本或特征
- 删除样本:适用于缺失比例小的样本
- 删除特征:适用于缺失比例大的特征

**填充法**:
- 均值填充:$x_{ij} = \bar{x}_j$(数值型)
- 中位数填充:$x_{ij} = \tilde{x}_j$(数值型,有异常值)
- 众数填充:$x_{ij} = \text{mode}(x_j)$(分类型)
- KNN填充:用K近邻的均值填充
- 回归填充:用回归模型预测缺失值

**插值法**:
- 线性插值:$x_t = \frac{x_{t-1} + x_{t+1}}{2}$
- 多项式插值
- 样条插值

#### 1.2 异常值检测与处理

**统计方法**:
- $3\sigma$原则:$|x_i - \bar{x}| > 3\sigma$
- 箱线图:$x_i < Q_1 - 1.5 \times IQR$ 或 $x_i > Q_3 + 1.5 \times IQR$
- Z-score:$|Z| > 3$ 为异常值

$$
Z_i = \frac{x_i - \bar{x}}{\sigma}
$$

**距离方法**:
- K近邻距离
- LOF(局部异常因子)

**处理方法**:
- 删除异常值
- 替换为边界值
- 对数变换
- 分箱处理

#### 1.3 数据标准化/归一化

**Min-Max归一化**:
$$
x'_i = \frac{x_i - \min(x)}{\max(x) - \min(x)}
$$

**Z-score标准化**:
$$
x'_i = \frac{x_i - \bar{x}}{\sigma}
$$

**小数定标标准化**:
$$
x'_i = \frac{x_i}{10^j}
$$

其中$j$是使$\max(|x'_i|) < 1$的最小整数。

#### 1.4 特征变换

**对数变换**:$x'_i = \log(x_i + c)$

**Box-Cox变换**:
$$
x'_i = \begin{cases}
\frac{x_i^\lambda - 1}{\lambda}, & \lambda \neq 0 \\
\ln(x_i), & \lambda = 0
\end{cases}
$$

**Yeo-Johnson变换**:可处理负值
$$
x'_i = \begin{cases}
\frac{(x_i + 1)^\lambda - 1}{\lambda}, & \lambda \neq 0, x_i \geq 0 \\
\ln(x_i + 1), & \lambda = 0, x_i \geq 0 \\
\frac{(-x_i + 1)^{2-\lambda} - 1}{2 - \lambda}, & \lambda \neq 2, x_i < 0 \\
-\ln(-x_i + 1), & \lambda = 2, x_i < 0
\end{cases}
$$

### 适用范围

| 题型类型 | 典型问题 | 特征 |
|---------|---------|------|
| 数据清洗 | 数据集预处理 | 缺失值/异常值 |
| 特征工程 | 机器学习特征 | 特征变换 |
| 数据集成 | 多数据源合并 | 格式统一 |
| 数据规约 | 大数据降维 | 采样/特征选择 |

### 可视化图表类型

- **缺失值热力图**:缺失值分布
- **箱线图**:异常值检测
- **分布图**:数据分布对比(变换前后)
- **QQ图**:正态性检验
- **散点图矩阵**:特征关系

### 关键文献

| 论文名称 | 作者 | 年份 | 来源 |
|---------|------|------|------|
| Data Mining: Concepts and Techniques | Han, Kamber & Pei | 2012 | Morgan Kaufmann |
| An Introduction to Statistical Learning | James et al. | 2021 | Springer |

### 代码实现要点

```python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.preprocessing import StandardScaler, MinMaxScaler, PowerTransformer, RobustScaler
from sklearn.impute import SimpleImputer, KNNImputer
from scipy import stats
import warnings
warnings.filterwarnings('ignore')

# 设置中文字体 - 多字体备选防止渲染问题
plt.rcParams['font.sans-serif'] = ['SimHei', 'DejaVu Sans', 'Arial Unicode MS', 'Microsoft YaHei', 'Arial']
plt.rcParams['axes.unicode_minus'] = False

class DataPreprocessor:
    """
    数据预处理类 - 包含缺失值处理、异常值检测、数据标准化等功能
    """
    
    @staticmethod
    def handle_missing_values(df, strategy='mean', columns=None, fill_value=None):
        """
        缺失值处理
        :param df: DataFrame
        :param strategy: 填充策略 ('mean', 'median', 'most_frequent', 'constant', 'knn')
        :param columns: 要处理的列名列表,None表示全部数值列
        :param fill_value: 当strategy='constant'时的填充值
        :return: 处理后的DataFrame, 缺失值统计
        """
        df_processed = df.copy()
        
        # 自动选择数值列
        if columns is None:
            columns = df.select_dtypes(include=[np.number]).columns.tolist()
        
        # 记录缺失值统计
        missing_stats = df[columns].isnull().sum()
        missing_stats = missing_stats[missing_stats > 0]
        
        if strategy == 'knn':
            imputer = KNNImputer(n_neighbors=5)
            df_processed[columns] = imputer.fit_transform(df[columns])
        elif strategy == 'constant':
            imputer = SimpleImputer(strategy='constant', fill_value=fill_value)
            df_processed[columns] = imputer.fit_transform(df[columns])
        else:
            imputer = SimpleImputer(strategy=strategy)
            df_processed[columns] = imputer.fit_transform(df[columns])
        
        return df_processed, missing_stats
    
    @staticmethod
    def detect_outliers_zscore(data, threshold=3):
        """
        使用Z-score检测异常值
        :param data: 数据数组
        :param threshold: Z-score阈值
        :return: 异常值索引, Z-score数组
        """
        z_scores = np.abs(stats.zscore(data, nan_policy='omit'))
        outlier_indices = np.where(z_scores > threshold)[0]
        return outlier_indices, z_scores
    
    @staticmethod
    def detect_outliers_iqr(data, k=1.5):
        """
        使用箱线图IQR方法检测异常值
        :param data: 数据数组
        :param k: IQR倍数,默认1.5
        :return: 异常值索引, 上下界
        """
        Q1 = np.percentile(data, 25)
        Q3 = np.percentile(data, 75)
        IQR = Q3 - Q1
        lower_bound = Q1 - k * IQR
        upper_bound = Q3 + k * IQR
        outlier_indices = np.where((data < lower_bound) | (data > upper_bound))[0]
        return outlier_indices, (lower_bound, upper_bound)
    
    @staticmethod
    def detect_outliers_modified_zscore(data, threshold=3.5):
        """
        使用改进的Z-score(基于中位数绝对偏差MAD)检测异常值
        :param data: 数据数组
        :param threshold: 阈值,默认3.5
        :return: 异常值索引
        """
        median = np.median(data)
        mad = np.median(np.abs(data - median))
        modified_z_scores = 0.6745 * (data - median) / mad
        outlier_indices = np.where(np.abs(modified_z_scores) > threshold)[0]
        return outlier_indices
    
    @staticmethod
    def standardize_data(data, method='zscore'):
        """
        数据标准化
        :param data: 数据矩阵 (样本×特征)
        :param method: 标准化方法 ('zscore', 'minmax', 'robust', 'maxabs')
        :return: 标准化后的数据, scaler对象
        """
        if method == 'zscore':
            scaler = StandardScaler()
        elif method == 'minmax':
            scaler = MinMaxScaler()
        elif method == 'robust':
            scaler = RobustScaler()
        elif method == 'maxabs':
            from sklearn.preprocessing import MaxAbsScaler
            scaler = MaxAbsScaler()
        else:
            raise ValueError(f"Unknown method: {method}")
        
        standardized = scaler.fit_transform(data)
        return standardized, scaler
    
    @staticmethod
    def boxcox_transform(data, lmbda=None):
        """
        Box-Cox变换(要求数据为正)
        :param data: 正数数据
        :param lmbda: 变换参数,None则自动选择
        :return: 变换后的数据, 最优lambda
        """
        # 确保数据为正
        min_val = np.min(data)
        if min_val <= 0:
            data = data - min_val + 1e-8
        
        transformed, fitted_lambda = stats.boxcox(data.flatten(), lmbda=lmbda)
        return transformed, fitted_lambda
    
    @staticmethod
    def yeo_johnson_transform(data, lmbda=None):
        """
        Yeo-Johnson变换(可处理负值)
        :param data: 数据
        :param lmbda: 变换参数,None则自动选择
        :return: 变换后的数据, 最优lambda
        """
        pt = PowerTransformer(method='yeo-johnson', standardize=False)
        if lmbda is not None:
            pt.lambdas_ = np.array([lmbda])
        transformed = pt.fit_transform(data.reshape(-1, 1)).flatten()
        return transformed, pt.lambdas_[0]

def visualize_preprocessing(data_dict, title="数据预处理可视化"):
    """
    可视化数据预处理效果
    :param data_dict: 字典,键为处理名称,值为数据数组
    :param title: 图表标题
    """
    n_plots = len(data_dict)
    fig, axes = plt.subplots(2, n_plots, figsize=(5*n_plots, 8))
    
    if n_plots == 1:
        axes = axes.reshape(-1, 1)
    
    for idx, (name, data) in enumerate(data_dict.items()):
        # 直方图
        axes[0, idx].hist(data, bins=30, edgecolor='black', alpha=0.7, color='skyblue')
        axes[0, idx].set_title(f'{name}\n均值={np.mean(data):.2f}, 标准差={np.std(data):.2f}')
        axes[0, idx].set_xlabel('值')
        axes[0, idx].set_ylabel('频数')
# Q-Q图
        stats.probplot(data, dist="norm", plot=axes[1, idx])
        axes[1, idx].set_title(f'{name} - Q-Q图')
    plt.suptitle(title, fontsize=14, fontweight='bold')
    plt.tight_layout()
    plt.savefig('data_preprocessing_visualization.png', dpi=150, bbox_inches='tight')
    plt.show()
    print("\n图表已保存为 'data_preprocessing_visualization.png'")

# 运行示例
if __name__ == "__main__":
    print("=" * 60)
    print("数据预处理示例")
    print("=" * 60)
    
    # 生成示例数据
    np.random.seed(42)
    n_samples = 1000
    
    # 正态分布数据(带异常值)
    normal_data = np.random.normal(100, 15, n_samples)
    normal_data[np.random.choice(n_samples, 20, replace=False)] += np.random.uniform(50, 80, 20)
    
    # 右偏分布数据
    skewed_data = np.random.exponential(2, n_samples)
    
    # 创建DataFrame
    df = pd.DataFrame({
        'normal_feature': normal_data,
        'skewed_feature': skewed_data,
        'missing_feature': np.where(np.random.random(n_samples) > 0.9, np.nan, normal_data)
    })
    
    print("\n原始数据统计:")
    print(df.describe())
    print(f"\n缺失值统计:\n{df.isnull().sum()}")
    
    preprocessor = DataPreprocessor()
    
    # 1. 缺失值处理
    print("\n" + "=" * 60)
    print("1. 缺失值处理")
    print("=" * 60)
    df_filled, missing_stats = preprocessor.handle_missing_values(df, strategy='mean')
    print(f"填充后缺失值:\n{df_filled.isnull().sum()}")
    
    # 2. 异常值检测
    print("\n" + "=" * 60)
    print("2. 异常值检测")
    print("=" * 60)
    
    # Z-score方法
    outlier_idx_z, z_scores = preprocessor.detect_outliers_zscore(df_filled['normal_feature'].values)
    print(f"Z-score方法检测到 {len(outlier_idx_z)} 个异常值")
    
    # IQR方法
    outlier_idx_iqr, bounds = preprocessor.detect_outliers_iqr(df_filled['normal_feature'].values)
    print(f"IQR方法检测到 {len(outlier_idx_iqr)} 个异常值")
    print(f"正常值范围: [{bounds[0]:.2f}, {bounds[1]:.2f}]")
    
    # 3. 数据标准化
    print("\n" + "=" * 60)
    print("3. 数据标准化")
    print("=" * 60)
    
    data_matrix = df_filled[['normal_feature', 'skewed_feature']].values
    
    # Z-score标准化
    zscore_data, zscore_scaler = preprocessor.standardize_data(data_matrix, method='zscore')
    print(f"Z-score标准化后 - 均值: {np.mean(zscore_data, axis=0)}")
    print(f"Z-score标准化后 - 标准差: {np.std(zscore_data, axis=0)}")
    
    # Min-Max归一化
    minmax_data, minmax_scaler = preprocessor.standardize_data(data_matrix, method='minmax')
    print(f"Min-Max归一化后 - 最小值: {np.min(minmax_data, axis=0)}")
    print(f"Min-Max归一化后 - 最大值: {np.max(minmax_data, axis=0)}")
    
    # 4. 数据变换
    print("\n" + "=" * 60)
    print("4. 数据变换")
    print("=" * 60)
    
    # Box-Cox变换
    transformed, lmbda = preprocessor.boxcox_transform(df_filled['skewed_feature'].values)
    print(f"Box-Cox变换 - 最优lambda: {lmbda:.4f}")
    print(f"变换前偏度: {stats.skew(df_filled['skewed_feature']):.4f}")
    print(f"变换后偏度: {stats.skew(transformed):.4f}")
    
    # 可视化对比
    visualize_preprocessing({
        '原始偏态数据': df_filled['skewed_feature'].values,
        'Box-Cox变换后': transformed
    }, "数据变换效果对比")
```

---

## 2. 聚类分析 (Cluster Analysis)

### 算法介绍

聚类分析是无监督学习方法,将相似样本归为一类。

#### 2.1 K-Means聚类

**目标函数**:
$$
J = \sum_{j=1}^{K} \sum_{x_i \in C_j} \|x_i - \mu_j\|^2
$$

其中$\mu_j$是簇$C_j$的质心。

**算法步骤**:
1. 随机选择$K$个初始质心
2. 将每个样本分配到最近的质心
3. 重新计算每个簇的质心
4. 重复2-3直到收敛

**时间复杂度**:$O(nKti)$($n$样本数,$K$簇数,$t$迭代次数,$i$特征数)

**K值选择**:
- 肘部法则(Elbow Method)
- 轮廓系数(Silhouette Coefficient)
- Gap统计量

#### 2.2 层次聚类

**凝聚层次聚类**(自底向上):
1. 每个样本作为一个簇
2. 合并最相似的两个簇
3. 重复直到只剩一个簇

**距离度量**:
- 单链接(Single Linkage):$d(C_i, C_j) = \min_{x \in C_i, y \in C_j} d(x, y)$
- 全链接(Complete Linkage):$d(C_i, C_j) = \max_{x \in C_i, y \in C_j} d(x, y)$
- 平均链接(Average Linkage):$d(C_i, C_j) = \frac{1}{|C_i||C_j|} \sum_{x \in C_i, y \in C_j} d(x, y)$
- Ward方法:最小化合并后的方差增加

#### 2.3 DBSCAN聚类

基于密度的聚类算法,可以发现任意形状的簇。

**核心概念**:
- **核心点**:半径$\varepsilon$内至少有MinPts个点
- **边界点**:半径$\varepsilon$内点数少于MinPts,但可从核心点到达
- **噪声点**:既不是核心点也不是边界点

**算法步骤**:
1. 随机选择未访问的点$p$
2. 若$p$是核心点,创建新簇,添加所有密度可达点
3. 若$p$不是核心点,标记为噪声
4. 重复直到所有点被访问

#### 2.4 模糊C-Means聚类

每个样本以一定隶属度属于各个簇。

**目标函数**:
$$
J_m = \sum_{i=1}^{n} \sum_{j=1}^{c} u_{ij}^m \|x_i - c_j\|^2
$$

约束条件:$\sum_{j=1}^{c} u_{ij} = 1$, $u_{ij} \in [0, 1]$

其中$u_{ij}$是样本$i$对簇$j$的隶属度,$m > 1$是模糊系数。

#### 2.5 自组织映射 (Self-Organizing Maps, SOM)

**基本原理**:

SOM是一种基于竞争学习的神经网络,将高维数据映射到低维(通常是2D)网格上,同时保持拓扑结构。

**网络结构**:
- 输入层:$n$个神经元(对应$n$个特征)
- 输出层:$m \times m$的网格(竞争层)
- 每个输出神经元有一个权重向量$w_{ij} \in \mathbb{R}^n$

**学习算法**:

1. **初始化**:随机初始化权重向量$w_{ij}$

2. **竞争阶段**:对于输入样本$x$,找到最佳匹配单元(BMU)
$$
\text{BMU} = \arg\min_{i,j} \|x - w_{ij}\|
$$

3. **合作阶段**:确定邻域函数
$$
h_{ij,BMU}(t) = \exp\left(-\frac{d_{ij,BMU}^2}{2\sigma(t)^2}\right)
$$

其中$d_{ij,BMU}$是神经元$(i,j)$与BMU的网格距离,$\sigma(t)$是随时间衰减的邻域半径。

4. **适应阶段**:更新邻域内神经元的权重
$$
w_{ij}(t+1) = w_{ij}(t) + \eta(t) \cdot h_{ij,BMU}(t) \cdot (x - w_{ij}(t))
$$

其中$\eta(t)$是学习率,随时间递减。

5. **重复**:对所有样本迭代训练

**参数调整**:
- 学习率:$\eta(t) = \eta_0 \exp(-t/\tau)$
- 邻域半径:$\sigma(t) = \sigma_0 \exp(-t/\tau)$
- 训练轮数:通常需要数千次迭代

#### 2.6 高斯混合模型 (Gaussian Mixture Models, GMM)

**基本模型**:

GMM假设数据来自$K$个高斯分布的混合。

**概率密度函数**:
$$
p(x) = \sum_{k=1}^{K} \pi_k \mathcal{N}(x | \mu_k, \Sigma_k)
$$

其中:
- $\pi_k$是混合系数(权重),$\sum_{k=1}^{K} \pi_k = 1$
- $\mu_k$是第$k$个高斯分布的均值
- $\Sigma_k$是第$k$个高斯分布的协方差矩阵
- $\mathcal{N}(x | \mu_k, \Sigma_k) = \frac{1}{(2\pi)^{d/2}|\Sigma_k|^{1/2}} \exp\left(-\frac{1}{2}(x-\mu_k)^T\Sigma_k^{-1}(x-\mu_k)\right)$

**EM算法求解**:

**E步**:计算后验概率(责任度)
$$
\gamma(z_{nk}) = \frac{\pi_k \mathcal{N}(x_n | \mu_k, \Sigma_k)}{\sum_{j=1}^{K} \pi_j \mathcal{N}(x_n | \mu_j, \Sigma_j)}
$$

**M步**:更新参数
$$
\mu_k^{new} = \frac{\sum_{n=1}^{N} \gamma(z_{nk}) x_n}{\sum_{n=1}^{N} \gamma(z_{nk})}
$$

$$
\Sigma_k^{new} = \frac{\sum_{n=1}^{N} \gamma(z_{nk}) (x_n - \mu_k^{new})(x_n - \mu_k^{new})^T}{\sum_{n=1}^{N} \gamma(z_{nk})}
$$

$$
\pi_k^{new} = \frac{\sum_{n=1}^{N} \gamma(z_{nk})}{N}
$$

**协方差矩阵类型**:
- **full**:完全协方差矩阵(最灵活)
- **tied**:所有分量共享相同协方差
- **diag**:对角协方差
- **spherical**:球状协方差(各方向方差相同)

**模型选择**:
使用**贝叶斯信息准则(BIC)**或**赤池信息准则(AIC)**选择最优$K$值:

$$
\text{BIC} = -2 \log \mathcal{L} + p \log N
$$

$$
\text{AIC} = -2 \log \mathcal{L} + 2p
$$

其中$p$是参数数量,$N$是样本数。

### 适用范围

| 题型类型 | 典型问题 | 特征 | 推荐算法 |
|---------|---------|------|---------|
| 客户细分 | 客户分群 | 无标签数据 | K-Means, GMM |
| 图像分割 | 图像区域划分 | 像素聚类 | SOM |
| 文本聚类 | 文档主题分类 | 高维稀疏 | K-Means, NMF |
| 异常检测 | 离群点识别 | 密度聚类 | DBSCAN, GMM |
| 基因分析 | 基因表达聚类 | 高维生物数据 | 层次聚类, SOM |
| 数据可视化 | 高维数据降维可视化 | 拓扑保持 | SOM |
| 概率建模 | 不确定性建模 | 概率分布 | GMM |

### 可视化图表类型

- **散点图**:聚类结果(不同颜色)
- **簇中心图**:质心位置
- **树状图**:层次聚类结构
- **密度图**:DBSCAN密度分布
- **轮廓图**:轮廓系数分析
- **肘部图**:K值选择
- **U-Matrix图**:SOM统一距离矩阵
- **权重向量图**:SOM权重可视化
- **命中直方图**:SOM每个神经元的样本数
- **概率密度图**:GMM各分量概率分布
- **置信椭圆图**:GMM协方差椭圆

### 关键文献

| 论文名称 | 作者 | 年份 | 来源 |
|---------|------|------|------|
| Some methods for classification and analysis of multivariate observations | MacQueen | 1967 | Proceedings of the 5th Berkeley Symposium |
| A density-based algorithm for discovering clusters in large spatial databases | Ester et al. | 1996 | KDD |
| Fuzzy models for pattern recognition | Bezdek | 1981 | Plenum Press |
| Self-Organizing Maps | Kohonen | 2001 | Springer |
| The self-organizing map | Kohonen | 1990 | Neurocomputing |
| Maximum likelihood from incomplete data via the EM algorithm | Dempster et al. | 1977 | Journal of the Royal Statistical Society |
| Pattern Recognition and Machine Learning | Bishop | 2006 | Springer |

### 代码实现要点

```python
from sklearn.cluster import KMeans, AgglomerativeClustering, DBSCAN
from sklearn.metrics import silhouette_score, silhouette_samples
import matplotlib.pyplot as plt
import numpy as np

# K-Means聚类
def kmeans_clustering(data, n_clusters=3, random_state=42):
    """
    K-Means聚类
    :param data: 数据矩阵 (样本×特征)
    :param n_clusters: 簇数
    :param random_state: 随机种子
    :return: 聚类标签, 质心, 模型
    """
    kmeans = KMeans(n_clusters=n_clusters, random_state=random_state, n_init=10)
    labels = kmeans.fit_predict(data)
    return labels, kmeans.cluster_centers_, kmeans

# 最佳K值选择(肘部法则)
def find_optimal_k(data, max_k=10):
    """
    使用肘部法则寻找最佳K值
    :param data: 数据矩阵
    :param max_k: 最大K值
    :return: 各K值的SSE值
    """
    sse = []
    for k in range(1, max_k + 1):
        kmeans = KMeans(n_clusters=k, random_state=42, n_init=10)
        kmeans.fit(data)
        sse.append(kmeans.inertia_)

    # 绘制肘部图
    plt.figure(figsize=(10, 6))
    plt.plot(range(1, max_k + 1), sse, 'bo-')
    plt.xlabel('Number of clusters (K)')
    plt.ylabel('Sum of Squared Errors (SSE)')
    plt.title('Elbow Method for Optimal K')
    plt.show()

    return sse

# 轮廓系数分析
def silhouette_analysis(data, labels):
    """
    轮廓系数分析
    :param data: 数据矩阵
    :param labels: 聚类标签
    :return: 平均轮廓系数, 各样本轮廓系数
    """
    avg_silhouette = silhouette_score(data, labels)
    sample_silhouettes = silhouette_samples(data, labels)
    return avg_silhouette, sample_silhouettes

# 层次聚类
def hierarchical_clustering(data, n_clusters=3, linkage='ward'):
    """
    层次聚类
    :param data: 数据矩阵
    :param n_clusters: 簇数
    :param linkage: 链接方法 ('ward', 'complete', 'average', 'single')
    :return: 聚类标签, 模型
    """
    model = AgglomerativeClustering(n_clusters=n_clusters, linkage=linkage)
    labels = model.fit_predict(data)
    return labels, model

# DBSCAN聚类
def dbscan_clustering(data, eps=0.5, min_samples=5):
    """
    DBSCAN聚类
    :param data: 数据矩阵
    :param eps: 邻域半径
    :param min_samples: 最小样本数
    :return: 聚类标签, 模型
    """
    dbscan = DBSCAN(eps=eps, min_samples=min_samples)
    labels = dbscan.fit_predict(data)
    return labels, dbscan

# 绘制聚类结果(2D)
def plot_clusters_2d(data, labels, centers=None):
    """
    绘制2D聚类结果
    :param data: 数据矩阵
    :param labels: 聚类标签
    :param centers: 质心位置(可选)
    """
    plt.figure(figsize=(10, 6))
    unique_labels = np.unique(labels)

    colors = plt.cm.tab10(np.linspace(0, 1, len(unique_labels)))

    for label, color in zip(unique_labels, colors):
        if label == -1:  # 噪声点(DBSCAN)
            color = (0.5, 0.5, 0.5, 0.5)  # 灰色半透明

        mask = labels == label
        plt.scatter(data[mask, 0], data[mask, 1],
                   c=[color], label=f'Cluster {label}',
                   alpha=0.7, edgecolors='w', linewidth=0.5)

    if centers is not None:
        plt.scatter(centers[:, 0], centers[:, 1],
                   c='red', marker='x', s=200,
                   linewidths=3, label='Centroids')

    plt.xlabel('Feature 1')
    plt.ylabel('Feature 2')
    plt.title('Clustering Results')
    plt.legend()
    plt.show()

# 自组织映射 (SOM)
def som_clustering(data, map_size=(10, 10), sigma=1.0, learning_rate=0.5,
                   num_epochs=100, random_state=42):
    """
    自组织映射聚类
    :param data: 数据矩阵 (样本×特征)
    :param map_size: SOM网格大小 (行, 列)
    :param sigma: 初始邻域半径
    :param learning_rate: 初始学习率
    :param num_epochs: 训练轮数
    :param random_state: 随机种子
    :return: SOM模型, 聚类标签, U矩阵
    """
    try:
        from minisom import MiniSom
    except ImportError:
        print("请安装 minisom: pip install minisom")
        return None, None, None

    n_features = data.shape[1]
    som = MiniSom(x=map_size[0], y=map_size[1], input_len=n_features,
                  sigma=sigma, learning_rate=learning_rate,
                  random_state=random_state)

    som.random_weights_init(data)
    som.train_random(data, num_epochs, verbose=False)

    # 获取聚类标签(每个样本的BMU)
    labels = np.array([som.winner(x) for x in data])
    # 将二维坐标转换为一维标签
    labels_1d = labels[:, 0] * map_size[1] + labels[:, 1]

    # 计算U矩阵(统一距离矩阵)
    u_matrix = som.distance_map()

    return som, labels_1d, u_matrix

def plot_som_results(som, data, labels, u_matrix, feature_names=None):
    """
    绘制SOM结果
    :param som: SOM模型
    :param data: 原始数据
    :param labels: 聚类标签
    :param u_matrix: U矩阵
    :param feature_names: 特征名称
    """
    fig = plt.figure(figsize=(16, 10))

    # U矩阵热力图
    ax1 = plt.subplot(2, 3, 1)
    im1 = ax1.imshow(u_matrix, cmap='viridis_r', aspect='auto')
    ax1.set_title('U-Matrix (Distance Map)')
    plt.colorbar(im1, ax=ax1)

    # 命中直方图
    ax2 = plt.subplot(2, 3, 2)
    map_size = u_matrix.shape
    hit_map = np.zeros(map_size)
    for x, y in [som.winner(d) for d in data]:
        hit_map[x, y] += 1
    im2 = ax2.imshow(hit_map, cmap='YlOrRd', aspect='auto')
    ax2.set_title('Hit Histogram')
    plt.colorbar(im2, ax=ax2)

    # 特征分量图(前4个特征)
    for i in range(min(4, data.shape[1])):
        ax = plt.subplot(2, 3, i + 3)
        weights = som.get_weights()[:, :, i]
        im = ax.imshow(weights, cmap='coolwarm', aspect='auto')
        name = feature_names[i] if feature_names else f'Feature {i+1}'
        ax.set_title(f'Component: {name}')
        plt.colorbar(im, ax=ax)

    plt.tight_layout()
    plt.show()

# 高斯混合模型
def gmm_clustering(data, n_components=3, covariance_type='full', random_state=42):
    """
    高斯混合模型聚类
    :param data: 数据矩阵 (样本×特征)
    :param n_components: 高斯分量数量
    :param covariance_type: 协方差类型 ('full', 'tied', 'diag', 'spherical')
    :param random_state: 随机种子
    :return: GMM模型, 聚类标签, 后验概率
    """
    from sklearn.mixture import GaussianMixture

    gmm = GaussianMixture(n_components=n_components,
                          covariance_type=covariance_type,
                          random_state=random_state,
                          max_iter=200)
    gmm.fit(data)

    labels = gmm.predict(data)
    posterior_probs = gmm.predict_proba(data)

    return gmm, labels, posterior_probs

def find_optimal_gmm_components(data, max_components=10, plot=True):
    """
    使用BIC和AIC寻找最优GMM分量数
    :param data: 数据矩阵
    :param max_components: 最大分量数
    :param plot: 是否绘制曲线
    :return: 各分量数的BIC和AIC值, 最优分量数
    """
    from sklearn.mixture import GaussianMixture

    n_components_range = range(1, max_components + 1)
    bic_scores = []
    aic_scores = []

    for n_components in n_components_range:
        gmm = GaussianMixture(n_components=n_components,
                              covariance_type='full',
                              random_state=42,
                              max_iter=200)
        gmm.fit(data)
        bic_scores.append(gmm.bic(data))
        aic_scores.append(gmm.aic(data))

    # 最优分量数(最小BIC)
    optimal_n_bic = n_components_range[np.argmin(bic_scores)]
    optimal_n_aic = n_components_range[np.argmin(aic_scores)]

    if plot:
        plt.figure(figsize=(10, 6))
        plt.plot(n_components_range, bic_scores, 'bo-', label='BIC')
        plt.plot(n_components_range, aic_scores, 'gs-', label='AIC')
        plt.axvline(x=optimal_n_bic, color='b', linestyle='--',
                    label=f'Optimal (BIC): {optimal_n_bic}')
        plt.axvline(x=optimal_n_aic, color='g', linestyle='--',
                    label=f'Optimal (AIC): {optimal_n_aic}')
        plt.xlabel('Number of Components')
        plt.ylabel('Information Criterion')
        plt.title('GMM: BIC and AIC for Different Component Numbers')
        plt.legend()
        plt.show()

    return {
        'bic': bic_scores,
        'aic': aic_scores,
        'optimal_bic': optimal_n_bic,
        'optimal_aic': optimal_n_aic
    }

def plot_gmm_results_2d(data, gmm, labels):
    """
    绘制2D GMM聚类结果(带置信椭圆)
    :param data: 2D数据矩阵
    :param gmm: 拟合的GMM模型
    :param labels: 聚类标签
    """
    if data.shape[1] != 2:
        print("此函数仅适用于2D数据")
        return

    plt.figure(figsize=(12, 8))

    # 绘制数据点
    colors = plt.cm.tab10(np.linspace(0, 1, gmm.n_components))
    for k in range(gmm.n_components):
        mask = labels == k
        plt.scatter(data[mask, 0], data[mask, 1],
                   c=[colors[k]], label=f'Component {k}',
                   alpha=0.6, edgecolors='w', linewidth=0.5)

    # 绘制置信椭圆
    from matplotlib.patches import Ellipse
    for k in range(gmm.n_components):
        if gmm.covariance_type == 'full':
            cov = gmm.covariances_[k][:2, :2]
        elif gmm.covariance_type == 'diag':
            cov = np.diag(gmm.covariances_[k][:2])
        else:
            cov = np.eye(2) * gmm.covariances_[k]

        # 计算椭圆参数
        lambda_, v = np.linalg.eigh(cov)
        lambda_ = np.sqrt(lambda_)

        for j in range(1, 4):
            ell = Ellipse(xy=gmm.means_[k, :2],
                         width=lambda_[0] * j * 2,
                         height=lambda_[1] * j * 2,
                         angle=np.rad2deg(np.arctan2(*v[:, 0][::-1])),
                         edgecolor=colors[k],
                         facecolor='none',
                         linewidth=1.5,
                         alpha=0.5 / j,
                         linestyle='--')
            plt.gca().add_patch(ell)

    plt.xlabel('Feature 1')
    plt.ylabel('Feature 2')
    plt.title('GMM Clustering with Confidence Ellipses')
    plt.legend()
plt.show()

def plot_gmm_uncertainty(data, posterior_probs):
    """
    绘制GMM不确定性
    :param data: 数据矩阵
    :param posterior_probs: 后验概率 (样本×分量)
    """
    # 计算最大后验概率(确定性)
    max_probs = np.max(posterior_probs, axis=1)

    plt.figure(figsize=(10, 6))
    plt.scatter(data[:, 0], data[:, 1], c=max_probs,
               cmap='RdYlGn', s=50, alpha=0.7, edgecolors='w')
    plt.colorbar(label='Max Posterior Probability (Certainty)')
    plt.xlabel('Feature 1')
    plt.ylabel('Feature 2')
    plt.title('GMM Uncertainty Visualization')
plt.show()
```

---

## 3. 假设检验 (Hypothesis Testing)

### 算法介绍

假设检验用于根据样本数据推断总体参数。

#### 3.1 参数检验

**t检验**:

| 类型 | 检验 | 统计量 |
|-----|------|--------|
| 单样本t检验 | 均值是否等于某值 | $t = \frac{\bar{x} - \mu_0}{s/\sqrt{n}}$ |
| 两独立样本t检验 | 两组均值是否相等 | $t = \frac{\bar{x}_1 - \bar{x}_2}{\sqrt{s_1^2/n_1 + s_2^2/n_2}}$ |
| 配对样本t检验 | 配对差异均值是否为0 | $t = \frac{\bar{d}}{s_d/\sqrt{n}}$ |

**方差分析(ANOVA)**:

**单因素方差分析**:检验多个组均值是否相等

$$
F = \frac{MS_{between}}{MS_{within}} = \frac{\sum_{j} n_j(\bar{x}_j - \bar{x})^2/(k-1)}{\sum_{j}\sum_{i}(x_{ij} - \bar{x}_j)^2/(n-k)}
$$

**卡方检验**:
- 适合性检验:观察分布是否符合理论分布
- 独立性检验:两个分类变量是否独立

$$
\chi^2 = \sum_{i,j} \frac{(O_{ij} - E_{ij})^2}{E_{ij}}
$$

#### 3.2 非参数检验

**Mann-Whitney U检验**:两独立样本比较(非参数)

**Wilcoxon符号秩检验**:配对样本比较(非参数)

**Kruskal-Wallis检验**:多组比较(非参数)

**Spearman秩相关**:单调相关性检验

$$
\rho = 1 - \frac{6\sum d_i^2}{n(n^2-1)}
$$

其中$d_i$是秩次差。

### 适用范围

| 题型类型 | 典型问题 | 特征 |
|---------|---------|------|
| A/B测试 | 策略效果对比 | 两组比较 |
| 质量控制 | 产品质量检验 | 均值检验 |
| 医学研究 | 治疗效果评估 | 配对检验 |
| 市场调研 | 问卷分析 | 独立性检验 |
| 相关分析 | 变量关系 | 相关性检验 |

### 可视化图表类型

- **分布对比图**:两组数据分布对比
- **箱线图**:多组数据对比
- **QQ图**:正态性检验
- **置信区间图**:参数置信区间
- **p值可视化**:检验结果

### 关键文献

| 论文名称 | 作者 | 年份 | 来源 |
|---------|------|------|------|
| Statistical Methods | Snedecor & Cochran | 1989 | Iowa State University Press |
| Nonparametric Statistical Methods | Hollander & Wolfe | 1999 | Wiley |

### 代码实现要点

```python
from scipy import stats
import numpy as np
import matplotlib.pyplot as plt

# 单样本t检验
def one_sample_t_test(data, mu0, alpha=0.05):
    """
    单样本t检验
    :param data: 样本数据
    :param mu0: 假设均值
    :param alpha: 显著性水平
    :return: 检验结果字典
    """
    t_stat, p_value = stats.ttest_1samp(data, mu0)
    df = len(data) - 1
    ci = stats.t.interval(1 - alpha, df, loc=np.mean(data), scale=stats.sem(data))

    return {
        't_statistic': t_stat,
        'p_value': p_value,
        'reject_null': p_value < alpha,
        'confidence_interval': ci,
        'sample_mean': np.mean(data),
        'sample_std': np.std(data, ddof=1)
    }

# 两独立样本t检验
def two_sample_t_test(sample1, sample2, alpha=0.05, equal_var=True):
    """
    两独立样本t检验
    :param sample1: 样本1数据
    :param sample2: 样本2数据
    :param alpha: 显著性水平
    :param equal_var: 是否假设方差相等
    :return: 检验结果字典
    """
    t_stat, p_value = stats.ttest_ind(sample1, sample2, equal_var=equal_var)

    # 置信区间
    n1, n2 = len(sample1), len(sample2)
    pooled_se = np.sqrt(np.var(sample1, ddof=1)/n1 + np.var(sample2, ddof=1)/n2)
    mean_diff = np.mean(sample1) - np.mean(sample2)
    df = n1 + n2 - 2
    me = stats.t.ppf(1 - alpha/2, df) * pooled_se
    ci = (mean_diff - me, mean_diff + me)

    return {
        't_statistic': t_stat,
        'p_value': p_value,
        'reject_null': p_value < alpha,
        'mean_difference': mean_diff,
        'confidence_interval': ci,
        'sample1_mean': np.mean(sample1),
        'sample2_mean': np.mean(sample2)
    }

# 单因素方差分析
def one_way_anova(*samples, alpha=0.05):
    """
    单因素方差分析
    :param samples: 各组样本数据
    :param alpha: 显著性水平
    :return: 检验结果字典
    """
    f_stat, p_value = stats.f_oneway(*samples)

    # 效应量(eta squared)
    all_data = np.concatenate(samples)
    grand_mean = np.mean(all_data)
    ss_between = sum(len(s) * (np.mean(s) - grand_mean)**2 for s in samples)
    ss_total = sum((x - grand_mean)**2 for x in all_data)
    eta_squared = ss_between / ss_total

    return {
        'f_statistic': f_stat,
        'p_value': p_value,
        'reject_null': p_value < alpha,
        'eta_squared': eta_squared,
        'sample_means': [np.mean(s) for s in samples]
    }

# 卡方检验(独立性)
def chi_square_test(contingency_table, alpha=0.05):
    """
    卡方检验(独立性检验)
    :param contingency_table: 列联表
    :param alpha: 显著性水平
    :return: 检验结果字典
    """
    chi2, p_value, dof, expected = stats.chi2_contingency(contingency_table)

    # Phi系数(2×2表)或Cramer's V
    n = contingency_table.sum().sum()
    min_dim = min(contingency_table.shape[0] - 1, contingency_table.shape[1] - 1)
    cramers_v = np.sqrt(chi2 / (n * min_dim))

    return {
        'chi2_statistic': chi2,
        'p_value': p_value,
        'reject_null': p_value < alpha,
        'degrees_of_freedom': dof,
        'expected_frequencies': expected,
        'cramers_v': cramers_v
    }

# 正态性检验
def normality_test(data, alpha=0.05):
    """
    正态性检验(Shapiro-Wilk)
    :param data: 样本数据
    :param alpha: 显著性水平
    :return: 检验结果字典
    """
    statistic, p_value = stats.shapiro(data)

    return {
        'statistic': statistic,
        'p_value': p_value,
        'reject_null': p_value < alpha,
        'is_normal': p_value >= alpha
    }

# 绘制QQ图
def plot_qq(data, title="Q-Q Plot"):
    """
    绘制Q-Q图
    :param data: 样本数据
    :param title: 图标题
    """
    plt.figure(figsize=(8, 6))
    stats.probplot(data, dist="norm", plot=plt)
    plt.title(title)
plt.show()
```

---

## 4. 主成分分析 (Principal Component Analysis, PCA)

### 算法介绍

PCA是一种降维技术,通过线性变换将数据投影到低维空间,保留最大方差。

#### 4.1 基本原理

**目标**:找到正交的主成分方向,使数据投影后的方差最大。

**第一主成分**:最大化方差
$$
\max_{w_1} \frac{1}{n} \sum_{i=1}^{n} (w_1^T x_i)^2 \quad \text{s.t.} \quad \|w_1\| = 1
$$

**一般解**:协方差矩阵的特征向量。

**协方差矩阵**:
$$
\Sigma = \frac{1}{n} \sum_{i=1}^{n} (x_i - \bar{x})(x_i - \bar{x})^T
$$

**特征分解**:$\Sigma = W \Lambda W^T$

其中$W$是特征向量矩阵,$\Lambda$是特征值对角矩阵。

#### 4.2 PCA步骤

1. 数据标准化(中心化)
2. 计算协方差矩阵
3. 特征分解
4. 选择主成分(按特征值大小)
5. 数据转换

**解释方差比**:
$$
\text{Explained Variance Ratio}_k = \frac{\lambda_k}{\sum_{i=1}^{p} \lambda_i}
$$

**累计解释方差比**:
$$
\text{Cumulative Ratio}_k = \frac{\sum_{i=1}^{k} \lambda_i}{\sum_{i=1}^{p} \lambda_i}
$$

### 适用范围

| 题型类型 | 典型问题 | 特征 |
|---------|---------|------|
| 数据降维 | 高维数据压缩 | 减少特征数 |
| 特征提取 | 图像特征提取 | 保留主要信息 |
| 数据可视化 | 多维数据可视化 | 2D/3D投影 |
| 噪声去除 | 信号去噪 | 保留主要成分 |
| 多重共线性 | 回归变量选择 | 消除共线性 |

### 可视化图表类型

- **碎石图**:特征值/解释方差
- **累计方差图**:累计解释方差
- **主成分载荷图**:变量与主成分关系
- **得分图**:样本在主成分空间
- **双标图**:载荷和得分
- **热力图**:特征重要性

### 关键文献

| 论文名称 | 作者 | 年份 | 来源 |
|---------|------|------|------|
| On lines and planes of closest fit to systems of points in space | Pearson | 1901 | Philosophical Magazine |
| The Elements of Statistical Learning | Hastie, Tibshirani & Friedman | 2009 | Springer |

### 代码实现要点

```python
from sklearn.decomposition import PCA
import numpy as np
import matplotlib.pyplot as plt

def perform_pca(data, n_components=None, standardize=True):
    """
    主成分分析
    :param data: 数据矩阵 (样本×特征)
    :param n_components: 主成分数量,None表示保留所有
    :param standardize: 是否标准化
    :return: PCA模型, 转换后数据, 解释方差比
    """
    from sklearn.preprocessing import StandardScaler

    if standardize:
        scaler = StandardScaler()
        data_scaled = scaler.fit_transform(data)
    else:
        data_scaled = data

    pca = PCA(n_components=n_components)
    transformed_data = pca.fit_transform(data_scaled)

    return pca, transformed_data

def plot_scree_plot(pca):
    """
    绘制碎石图
    :param pca: 拟合后的PCA模型
    """
    plt.figure(figsize=(10, 6))
    components = range(1, len(pca.explained_variance_ratio_) + 1)
    plt.bar(components, pca.explained_variance_ratio_, alpha=0.7, label='Individual')
    plt.plot(components, np.cumsum(pca.explained_variance_ratio_),
             'ro-', label='Cumulative')
    plt.xlabel('Principal Component')
    plt.ylabel('Explained Variance Ratio')
    plt.title('Scree Plot')
    plt.legend()
plt.show()

def plot_pca_biplot(pca, transformed_data, feature_names, n_features=10):
    """
    绘制PCA双标图
    :param pca: PCA模型
    :param transformed_data: 转换后的数据
    :param feature_names: 特征名称列表
    :param n_features: 显示的特征数量
    """
    plt.figure(figsize=(12, 8))

    # 样本点
    plt.scatter(transformed_data[:, 0], transformed_data[:, 1],
               alpha=0.5, c='blue', label='Samples')

    # 特征向量(载荷)
    loadings = pca.components_.T * np.sqrt(pca.explained_variance_)

    for i in range(min(n_features, len(feature_names))):
        plt.arrow(0, 0, loadings[i, 0], loadings[i, 1],
                 color='r', alpha=0.8, head_width=0.05)
        plt.text(loadings[i, 0] * 1.1, loadings[i, 1] * 1.1,
                feature_names[i], color='r')

    plt.xlabel(f'PC1 ({pca.explained_variance_ratio_[0]:.2%})')
    plt.ylabel(f'PC2 ({pca.explained_variance_ratio_[1]:.2%})')
    plt.title('PCA Biplot')
    plt.axhline(y=0, color='k', linestyle='--', alpha=0.3)
    plt.axvline(x=0, color='k', linestyle='--', alpha=0.3)
    plt.show()

def get_optimal_components(pca, threshold=0.95):
    """
    获取达到累计解释方差阈值的主成分数量
    :param pca: PCA模型
    :param threshold: 累计解释方差阈值
    :return: 最优主成分数量
    """
    cumulative = np.cumsum(pca.explained_variance_ratio_)
    n_components = np.argmax(cumulative >= threshold) + 1
    return n_components
```

---

## 5. 因子分析 (Factor Analysis, FA)

### 算法介绍

因子分析是用少数潜在变量(因子)解释可观测变量之间的相关性。

#### 5.1 基本模型

**数学模型**:
$$
X = \mu + \Lambda F + \epsilon
$$

其中:
- $X$是可观测变量向量
- $\mu$是均值向量
- $\Lambda$是因子载荷矩阵
- $F$是公共因子向量
- $\epsilon$是特殊因子(误差)

#### 5.2 因子提取方法

**主成分法**:基于主成分分析

**主因子法**:基于公共因子方差

**最大似然法**:假设数据多元正态分布

#### 5.3 因子旋转

**目的**:使因子结构更易解释。

**正交旋转**:
- 方差最大化旋转(Varimax)
- 四次方最大旋转(Quartimax)
- 平方最大旋转(Equamax)

**斜交旋转**:
- Promax旋转
- Oblimin旋转

### 适用范围

| 题型类型 | 典型问题 | 特征 |
|---------|---------|------|
| 心理测量 | 问卷结构分析 | 潜在变量 |
| 市场研究 | 消费者偏好 | 因子识别 |
| 社会科学 | 社会指标分析 | 变量归类 |
| 金融分析 | 风险因子提取 | 公共风险 |
| 生物信息 | 基因表达分析 | 潜在模式 |

### 可视化图表类型

- **碎石图**:因子特征值
- **因子载荷图**:变量在因子上的载荷
- **因子得分图**:样本因子得分
- **路径图**:因子结构

### 关键文献

| 论文名称 | 作者 | 年份 | 来源 |
|---------|------|------|------|
| The Common Factor Model | Thurstone | 1947 | University of Chicago Press |
| Factor Analysis as a Statistical Method | Lawley & Maxwell | 1971 | Butterworths |

### 代码实现要点

```python
from sklearn.decomposition import FactorAnalysis
from factor_analyzer import FactorAnalyzer, Rotator
import numpy as np

def perform_factor_analysis(data, n_factors=3, rotation='varimax'):
    """
    因子分析
    :param data: 数据矩阵
    :param n_factors: 因子数量
    :param rotation: 旋转方法
    :return: 因子载荷, 因子得分, 方差解释
    """
    # 使用factor_analyzer库
    fa = FactorAnalyzer(n_factors=n_factors, rotation=rotation)
    fa.fit(data)

    # 因子载荷
    loadings = fa.loadings_

    # 因子方差
    communalities = fa.get_communalities()

    # 方差解释
    variance = fa.get_factor_variance()

    return {
        'loadings': loadings,
        'communalities': communalities,
        'variance': variance,  # (SS Loadings, Proportion Var, Cumulative Var)
        'factor_scores': fa.transform(data)
    }

def determine_n_factors(data, max_factors=10):
    """
    确定因子数量(Kaiser准则 + 碎石图)
    :param data: 数据矩阵
    :param max_factors: 最大因子数
    :return: 特征值, 推荐因子数
    """
    from factor_analyzer.factor_analyzer import calculate_kmo

    # Kaiser准则:特征值>1
    fa = FactorAnalyzer(n_factors=max_factors, rotation=None)
    fa.fit(data)
    ev, v = fa.get_eigenvalues()

    n_factors_kaiser = sum(ev > 1)

    return ev, n_factors_kaiser

def plot_factor_loadings(loadings, feature_names, figsize=(10, 8)):
    """
    绘制因子载荷热力图
    :param loadings: 载荷矩阵
    :param feature_names: 特征名称
    :param figsize: 图大小
    """
    import seaborn as sns
    import matplotlib.pyplot as plt

    plt.figure(figsize=figsize)
    sns.heatmap(loadings, annot=True, cmap='coolwarm',
                xticklabels=[f'F{i+1}' for i in range(loadings.shape[1])],
                yticklabels=feature_names,
                center=0, cbar_kws={'label': 'Loading'})
    plt.title('Factor Loadings')
    plt.xlabel('Factors')
    plt.ylabel('Variables')
    plt.tight_layout()
    plt.show()
```

---

## 6. 典型相关分析 (Canonical Correlation Analysis, CCA)

### 算法介绍

典型相关分析用于研究两组变量之间的整体相关性,通过线性组合找到两组变量之间的最大相关关系。

#### 6.1 基本原理

**问题设定**:
- 第一组变量:$X = (x_1, x_2, \ldots, x_p)^T$
- 第二组变量:$Y = (y_1, y_2, \ldots, y_q)^T$

**目标**:寻找线性组合
$$
U = a_1 x_1 + a_2 x_2 + \cdots + a_p x_p = a^T X
$$
$$
V = b_1 y_1 + b_2 y_2 + \cdots + b_q y_q = b^T Y
$$

使得$U$和$V$的相关系数$\rho(U, V)$最大化。

#### 6.2 数学推导

**相关系数**:
$$
\rho = \frac{\text{Cov}(U, V)}{\sqrt{\text{Var}(U)\text{Var}(V)}} = \frac{a^T \Sigma_{XY} b}{\sqrt{a^T \Sigma_{XX} a \cdot b^T \Sigma_{YY} b}}
$$

其中$\Sigma_{XX}$、$\Sigma_{YY}$、$\Sigma_{XY}$分别为协方差矩阵。

**优化问题**:
$$
\max_{a, b} a^T \Sigma_{XY} b
$$
$$
\text{s.t. } a^T \Sigma_{XX} a = 1, b^T \Sigma_{YY} b = 1
$$

**拉格朗日乘数法**得到特征值问题:
$$
\Sigma_{XY} \Sigma_{YY}^{-1} \Sigma_{YX} a = \lambda^2 \Sigma_{XX} a
$$
$$
\Sigma_{YX} \Sigma_{XX}^{-1} \Sigma_{XY} b = \lambda^2 \Sigma_{YY} b
$$

$\lambda^2$为典型相关系数的平方。

#### 6.3 典型变量

第$k$对典型变量:
$$
U_k = a_k^T X, \quad V_k = b_k^T Y
$$

典型相关系数按递减顺序排列:$\lambda_1 \geq \lambda_2 \geq \cdots \geq \lambda_m$

其中$m = \min(p, q)$

#### 6.4 显著性检验

**Wilks' Lambda统计量**:
$$
\Lambda = \prod_{i=k}^{m} (1 - \lambda_i^2)
$$

**卡方近似**:
$$
\chi^2 = -[n - k - \frac{p + q + 1}{2}] \ln \Lambda
$$

自由度:$df = (p - k + 1)(q - k + 1)$

### 适用范围

| 题型类型 | 典型问题 | 特征 |
|---------|---------|------|
| 心理测量 | 智商与成绩关系 | 两组变量相关 |
| 经济分析 | 宏观指标与股市 | 多变量关系 |
| 生态环境 | 气候与植被 | 复杂关联 |
| 医学研究 | 症状与检验指标 | 诊断分析 |
| 社会科学 | 教育与收入 | 因素关联 |

### 可视化图表类型

- **典型变量得分图**:典型变量的散点图
- **相关系数图**:典型相关系数柱状图
- **载荷图**:原始变量与典型变量的相关性
- **冗余度分析图**:解释方差比例
- **显著性检验图**:各对典型变量的显著性

### 关键文献

| 论文名称 | 作者 | 年份 | 来源 |
|---------|------|------|------|
| Multivariate Statistical Analysis | Hardle & Simar | 2015 | Springer |
| Applied Multivariate Statistical Analysis | Johnson & Wichern | 2007 | Pearson |

### 代码实现要点

```python
import numpy as np
import pandas as pd
from scipy import stats
import matplotlib.pyplot as plt

def canonical_correlation_analysis(X, Y):
    """
    典型相关分析
    :param X: 第一组变量 (n_samples, p)
    :param Y: 第二组变量 (n_samples, q)
    :return: 典型相关系数, 典型权重, 典型变量得分
    """
    n, p = X.shape
    q = Y.shape[1]

    # 中心化
    X = X - X.mean(axis=0)
    Y = Y - Y.mean(axis=0)

    # 计算协方差矩阵
    Cxx = np.cov(X, rowvar=False, bias=True)
    Cyy = np.cov(Y, rowvar=False, bias=True)
    Cxy = np.cov(X, Y, rowvar=False, bias=True)[:p, q:]

    # 广义特征值问题
    # Cxy @ inv(Cyy) @ Cyx @ a = lambda^2 @ Cxx @ a
    from scipy.linalg import eigh

    Cyy_inv = np.linalg.inv(Cyy)
    Cyx = Cxy.T
    M1 = np.linalg.inv(Cxx) @ Cxy @ Cyy_inv @ Cyx

    # 求解特征值和特征向量
    eigenvalues, eigenvectors_a = eigh(M1)
    eigenvalues = eigenvalues[::-1]  # 降序排列
    eigenvectors_a = eigenvectors_a[:, ::-1]

    # 计算典型相关系数
    canonical_correlations = np.sqrt(np.maximum(eigenvalues, 0))

    # 计算b的典型权重
    eigenvectors_b = []
    for k in range(len(canonical_correlations)):
        a_k = eigenvectors_a[:, k]
        b_k = (1 / canonical_correlations[k]) * Cyy_inv @ Cyx @ a_k
        eigenvectors_b.append(b_k)
    eigenvectors_b = np.column_stack(eigenvectors_b)

    # 计算典型变量得分
    canonical_scores_X = X @ eigenvectors_a
    canonical_scores_Y = Y @ eigenvectors_b

    return {
        'canonical_correlations': canonical_correlations,
        'coefficients_x': eigenvectors_a,
        'coefficients_y': eigenvectors_b,
        'scores_x': canonical_scores_X,
        'scores_y': canonical_scores_Y
    }

def cca_significance_test(canonical_corrs, n, p, q, alpha=0.05):
    """
    CCA显著性检验(Wilks' Lambda)
    :param canonical_corrs: 典型相关系数数组
    :param n: 样本量
    :param p: 第一组变量数
    :param q: 第二组变量数
    :param alpha: 显著性水平
    :return: 各对典型变量的显著性
    """
    m = len(canonical_corrs)
    results = []

    for k in range(m):
        # Wilks' Lambda
        wilks_lambda = np.prod(1 - canonical_corrs[k:]**2)

        # 卡方近似
        t = n - k - (p + q + 1) / 2
        df = (p - k + 1) * (q - k + 1)
        chi2 = -t * np.log(wilks_lambda)

        p_value = 1 - stats.chi2.cdf(chi2, df)
        significant = p_value < alpha

        results.append({
            'pair': k + 1,
            'canonical_corr': canonical_corrs[k],
            'wilks_lambda': wilks_lambda,
            'chi2': chi2,
            'df': df,
            'p_value': p_value,
            'significant': significant
        })

    return pd.DataFrame(results)

def plot_canonical_scores(scores_x, scores_y, pair=0):
    """
    绘制典型变量得分图
    :param scores_x: 第一组典型变量得分
    :param scores_y: 第二组典型变量得分
    :param pair: 第几对典型变量
    """
    plt.figure(figsize=(8, 8))
    plt.scatter(scores_x[:, pair], scores_y[:, pair], alpha=0.6)
    plt.xlabel(f'Canonical Variable U_{pair+1}')
    plt.ylabel(f'Canonical Variable V_{pair+1}')
    plt.title(f'Canonical Scores for Pair {pair+1}')
# 添加回归线
    z = np.polyfit(scores_x[:, pair], scores_y[:, pair], 1)
    p = np.poly1d(z)
    x_line = np.linspace(scores_x[:, pair].min(), scores_x[:, pair].max(), 100)
    plt.plot(x_line, p(x_line), "r--", alpha=0.8, label='Regression Line')
    plt.legend()
    plt.show()

def plot_canonical_loadings(X, Y, coeff_x, coeff_y, feature_names_x=None, feature_names_y=None):
    """
    绘制典型载荷图
    :param X: 第一组原始变量
    :param Y: 第二组原始变量
    :param coeff_x: X的典型权重
    :param coeff_y: Y的典型权重
    :param feature_names_x: X的变量名
    :param feature_names_y: Y的变量名
    """
    # 计算典型载荷(原始变量与典型变量的相关系数)
    scores_x = X @ coeff_x
    scores_y = Y @ coeff_y

    loadings_x = np.array([np.corrcoef(X[:, i], scores_x[:, 0])[0, 1] for i in range(X.shape[1])])
    loadings_y = np.array([np.corrcoef(Y[:, i], scores_y[:, 0])[0, 1] for i in range(Y.shape[1])])

    fig, axes = plt.subplots(1, 2, figsize=(14, 6))

    # X的载荷
    axes[0].barh(range(len(loadings_x)), loadings_x)
    axes[0].set_xlabel('Canonical Loading')
    axes[0].set_ylabel('Variable')
    axes[0].set_title('Loadings - Group X')
    axes[0].set_yticks(range(len(loadings_x)))
    axes[0].set_yticklabels(feature_names_x if feature_names_x else range(len(loadings_x)))
    axes[0].axvline(x=0, color='k', linestyle='-', alpha=0.3)
# Y的载荷
    axes[1].barh(range(len(loadings_y)), loadings_y)
    axes[1].set_xlabel('Canonical Loading')
    axes[1].set_ylabel('Variable')
    axes[1].set_title('Loadings - Group Y')
    axes[1].set_yticks(range(len(loadings_y)))
    axes[1].set_yticklabels(feature_names_y if feature_names_y else range(len(loadings_y)))
    axes[1].axvline(x=0, color='k', linestyle='-', alpha=0.3)
    plt.tight_layout()
    plt.show()
```

---

## 7. 非负矩阵分解 (Non-negative Matrix Factorization, NMF)

### 算法介绍

非负矩阵分解是一种降维和特征提取方法,将非负矩阵分解为两个非负矩阵的乘积。

#### 7.1 基本原理

**分解形式**:
$$
V \approx W H
$$

其中:
- $V \in \mathbb{R}^{n \times m}$:非负数据矩阵
- $W \in \mathbb{R}^{n \times r}$:基矩阵
- $H \in \mathbb{R}^{r \times m}$:系数矩阵
- $r$:分解秩($r < \min(n, m)$)

**约束条件**:
$$
W_{ij} \geq 0, \quad H_{ij} \geq 0
$$

#### 7.2 损失函数

**Frobenius范数损失**:
$$
\|V - WH\|_F^2 = \sum_{i,j} (V_{ij} - (WH)_{ij})^2
$$

**KL散度损失**:
$$
D_{KL}(V \| WH) = \sum_{i,j} \left( V_{ij} \log\frac{V_{ij}}{(WH)_{ij}} - V_{ij} + (WH)_{ij} \right)
$$

#### 7.3 乘法更新规则

**基于Frobenius范数的更新**:

初始化$W$和$H$为随机非负矩阵,然后迭代更新:

$$
H_{kj} \leftarrow H_{kj} \frac{(W^T V)_{kj}}{(W^T W H)_{kj} + \epsilon}
$$

$$
W_{ik} \leftarrow W_{ik} \frac{(V H^T)_{ik}}{(W H H^T)_{ik} + \epsilon}
$$

其中$\epsilon$是很小的正数,防止除零。

**归一化**:每次更新后对$W$的列进行归一化:
$$
W_{ik} \leftarrow \frac{W_{ik}}{\sum_i W_{ik}}
$$

#### 7.4 NMF与PCA对比

| 特性 | NMF | PCA |
|-----|-----|-----|
| 约束 | 非负 | 正交 |
| 可解释性 | 部分整体结构 | 全局结构 |
| 基向量 | 稀疏 | 非稀疏 |
| 适用数据 | 非负数据 | 任意数据 |

### 适用范围

| 题型类型 | 典型问题 | 特征 |
|---------|---------|------|
| 图像分析 | 图像压缩、特征提取 | 像素非负 |
| 文本挖掘 | 主题发现 | 词频非负 |
| 推荐系统 | 用户偏好分解 | 非负评分 |
| 音频处理 | 音频分离 | 频谱非负 |
| 基因表达 | 模式识别 | 表达水平非负 |

### 可视化图表类型

- **基向量图**:基矩阵W的各列可视化
- **系数矩阵热力图**:系数矩阵H的热力图
- **重构对比图**:原始与重构对比
- **收敛曲线**:损失函数变化
- **特征贡献图**:各基向量的贡献

### 关键文献

| 论文名称 | 作者 | 年份 | 来源 |
|---------|------|------|------|
| Learning the parts of objects by non-negative matrix factorization | Lee & Seung | 1999 | Nature |
| Algorithms for non-negative matrix factorization | Lee & Seung | 2001 | NIPS |

### 代码实现要点

```python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import NMF
from sklearn.preprocessing import MinMaxScaler

def nmf_decomposition(V, n_components, max_iter=200, tol=1e-4, random_state=42):
    """
    非负矩阵分解
    :param V: 非负数据矩阵 (n_samples, n_features)
    :param n_components: 分解秩
    :param max_iter: 最大迭代次数
    :param tol: 收敛容忍度
    :param random_state: 随机种子
    :return: W, H, 重构误差历史
    """
    model = NMF(n_components=n_components, init='random', random_state=random_state,
                max_iter=max_iter, tol=tol, verbose=False)

    W = model.fit_transform(V)
    H = model.components_

    return W, H, model.reconstruction_err_

def plot_nmf_components(W, H, feature_names=None, sample_names=None):
    """
    绘制NMF分解结果
    :param W: 基矩阵 (n_samples, n_components)
    :param H: 系数矩阵 (n_components, n_features)
    :param feature_names: 特征名称
    :param sample_names: 样本名称
    """
    fig, axes = plt.subplots(1, 2, figsize=(14, 6))

    # 基矩阵热力图
    im1 = axes[0].imshow(W, cmap='YlOrRd', aspect='auto')
    axes[0].set_xlabel('Component')
    axes[0].set_ylabel('Sample')
    axes[0].set_title('Basis Matrix (W)')
    if sample_names is not None and len(sample_names) <= 20:
        axes[0].set_yticks(range(len(sample_names)))
        axes[0].set_yticklabels(sample_names)
    plt.colorbar(im1, ax=axes[0])

    # 系数矩阵热力图
    im2 = axes[1].imshow(H, cmap='YlOrRd', aspect='auto')
    axes[1].set_xlabel('Feature')
    axes[1].set_ylabel('Component')
    axes[1].set_title('Coefficient Matrix (H)')
    if feature_names is not None and len(feature_names) <= 20:
        axes[1].set_xticks(range(len(feature_names)))
        axes[1].set_xticklabels(feature_names, rotation=90)
    plt.colorbar(im2, ax=axes[1])

    plt.tight_layout()
    plt.show()

def plot_nmf_basis_images(W, image_shape=(28, 28), n_plot=16):
    """
    绘制NMF基向量图像(用于图像数据)
    :param W: 基矩阵
    :param image_shape: 图像尺寸
    :param n_plot: 显示的基向量数量
    """
    n_components = min(n_plot, W.shape[1])
    n_cols = 4
    n_rows = (n_components + n_cols - 1) // n_cols

    fig, axes = plt.subplots(n_rows, n_cols, figsize=(n_cols * 2, n_rows * 2))
    axes = axes.flatten()

    for i in range(n_components):
        basis = W[:, i].reshape(image_shape)
        axes[i].imshow(basis, cmap='gray')
        axes[i].set_title(f'Basis {i+1}')
        axes[i].axis('off')

    # 隐藏多余的子图
    for i in range(n_components, len(axes)):
        axes[i].axis('off')

    plt.tight_layout()
    plt.show()

def find_optimal_components_nmf(V, max_components=10, plot=True):
    """
    寻找最优NMF组件数
    :param V: 数据矩阵
    :param max_components: 最大组件数
    :param plot: 是否绘制曲线
    :return: 各组件数的重构误差
    """
    errors = []
    components_range = range(1, max_components + 1)

    for n_comp in components_range:
        model = NMF(n_components=n_comp, init='random', random_state=42, max_iter=200)
        W = model.fit_transform(V)
        error = model.reconstruction_err_
        errors.append(error)

    if plot:
        plt.figure(figsize=(10, 6))
        plt.plot(components_range, errors, 'bo-')
        plt.xlabel('Number of Components')
        plt.ylabel('Reconstruction Error')
        plt.title('NMF: Components vs Reconstruction Error')
        plt.show()

    return errors

def nmf_topic_modeling(document_term_matrix, n_topics, feature_names, n_top_words=10):
    """
    基于NMF的主题建模
    :param document_term_matrix: 文档-词频矩阵
    :param n_topics: 主题数量
    :param feature_names: 词列表
    :param n_top_words: 每个主题显示的词数
    :return: 主题词分布
    """
    model = NMF(n_components=n_topics, init='random', random_state=42, max_iter=300)
    W = model.fit_transform(document_term_matrix)
    H = model.components_

    # 提取每个主题的高频词
    topics = []
    for topic_idx, topic in enumerate(H):
        top_word_indices = topic.argsort()[:-n_top_words - 1:-1]
        top_words = [feature_names[i] for i in top_word_indices]
        topics.append(top_words)

        print(f"Topic {topic_idx + 1}:")
        print(", ".join(top_words))
        print()

    return W, H, topics

def compare_nmf_pca(V, n_components):
    """
    比较NMF和PCA
    :param V: 数据矩阵(非负)
    :param n_components: 组件数
    :return: NMF和PCA的重构误差
    """
    from sklearn.decomposition import PCA

    # NMF
    nmf_model = NMF(n_components=n_components, init='random', random_state=42)
    W_nmf = nmf_model.fit_transform(V)
    V_recon_nmf = W_nmf @ nmf_model.components_
    nmf_error = np.linalg.norm(V - V_recon_nmf, 'fro')

    # PCA (中心化后)
    V_centered = V - V.mean(axis=0)
    pca_model = PCA(n_components=n_components)
    W_pca = pca_model.fit_transform(V)
    V_recon_pca = W_pca @ pca_model.components_ + V.mean(axis=0)
    pca_error = np.linalg.norm(V - V_recon_pca, 'fro')

    print(f"NMF Reconstruction Error: {nmf_error:.4f}")
    print(f"PCA Reconstruction Error: {pca_error:.4f}")

    return nmf_error, pca_error
```

---

## 统计分析算法选择指南

### 按数据特征选择

| 数据特征 | 推荐算法 |
|---------|---------|
| 有缺失值 | 缺失值处理、KNN填充 |
| 有异常值 | 异常值检测、鲁棒处理 |
| 高维数据 | PCA、因子分析 |
| 非正态分布 | 非参数检验、Box-Cox变换 |
| 分类型数据 | 卡方检验、关联分析 |
| 时间序列 | 时间序列预处理 |

### 按分析目的选择

| 分析目的 | 推荐算法 |
|---------|---------|
| 数据清洗 | 缺失值处理、异常值处理 |
| 降维 | PCA、因子分析、t-SNE |
| 分组 | K-Means、层次聚类、DBSCAN |
| 组间比较 | t检验、方差分析、非参数检验 |
| 相关分析 | 相关系数、典型相关分析 |
| 模式发现 | 聚类、因子分析 |

### 按样本量选择

| 样本量 | 推荐算法 |
|--------|---------|
| 小样本(<30) | 非参数检验、精确检验 |
| 中样本(30-500) | t检验、方差分析 |
| 大样本(>500) | 聚类、PCA、各种检验 |

---

## 参考文献

1. Han, J., Pei, J., & Kamber, M. (2012). *Data Mining: Concepts and Techniques* (3rd ed.). Morgan Kaufmann.
2. James, G., Witten, D., Hastie, T., & Tibshirani, R. (2021). *An Introduction to Statistical Learning with Applications in R* (2nd ed.). Springer.
3. Hastie, T., Tibshirani, R., & Friedman, J. (2009). *The Elements of Statistical Learning* (2nd ed.). Springer.
4. MacQueen, J. B. (1967). Some methods for classification and analysis of multivariate observations. *Proceedings of the Fifth Berkeley Symposium on Mathematical Statistics and Probability*, 1(14), 281-297.
5. Ester, M., Kriegel, H. P., Sander, J., & Xu, X. (1996). A density-based algorithm for discovering clusters in large spatial databases with noise. *KDD*, 96, 226-231.
6. Snedecor, G. W., & Cochran, W. G. (1989). *Statistical Methods* (8th ed.). Iowa State University Press.
7. Pearson, K. (1901). On lines and planes of closest fit to systems of points in space. *The London, Edinburgh, and Dublin Philosophical Magazine and Journal of Science*, 2(11), 559-572.
8. Thurstone, L. L. (1947). *Multiple-Factor Analysis*. University of Chicago Press.
reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.Stars: 323kUpdated Claude CodeCodexVerifiedInstall
dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependenciesStars: 323kUpdated Claude CodeCodexVerifiedInstall
executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is availableStars: 323kUpdated Claude CodeCodexVerifiedInstall