API 参考
本节提供 PyCorrAna 的完整 API 参考文档。
核心分析模块
quick_corr 函数
- pycorrana.quick_corr(data: str | DataFrame | pl.DataFrame, target: str | None = None, columns: List[str] | None = None, method: str = 'auto', missing_strategy: str = 'warn', fill_method: str | None = None, pvalue_correction: str = 'fdr_bh', plot: bool = True, export: bool | str = False, verbose: bool = True, large_data_config: LargeDataConfig | None = None, **kwargs) Dict[源代码]
快速相关性分析入口函数。
一键完成数据加载、预处理、相关性计算、可视化和报告生成。
- 参数:
data (str, pd.DataFrame, pl.DataFrame) -- 数据输入(文件路径或DataFrame)
target (str, optional) -- 目标变量
columns (list, optional) -- 指定分析的列
method (str, default='auto') -- 相关性方法
missing_strategy (str, default='warn') -- 缺失值处理策略
fill_method (str, optional) -- 填充方法
pvalue_correction (str, default='fdr_bh') -- p值校正方法
plot (bool, default=True) -- 是否自动绘图
verbose (bool, default=True) -- 是否输出详细信息
large_data_config (LargeDataConfig, optional) -- 大数据处理配置,用于优化大数据集的计算效率
**kwargs -- 其他参数
- 返回:
完整分析结果
- 返回类型:
示例
>>> # 基本用法 >>> result = quick_corr('data.csv')
>>> # 指定目标变量 >>> result = quick_corr(df, target='sales')
>>> # 自定义参数 >>> result = quick_corr(df, method='spearman', plot=False, export='results.xlsx')
>>> # 大数据集优化 >>> from pycorrana.utils import LargeDataConfig >>> config = LargeDataConfig(sample_size=50000, auto_sample=True) >>> result = quick_corr(large_df, large_data_config=config)
CorrAnalyzer 类
- class pycorrana.CorrAnalyzer(data: DataFrame, method: str = 'auto', missing_strategy: str = 'warn', fill_method: str | None = None, pvalue_correction: str = 'fdr_bh', verbose: bool = True, large_data_config: LargeDataConfig | None = None)[源代码]
相关性分析器类
提供完整的相关性分析流程,包括数据预处理、自动方法选择、 批量计算、可视化和报告生成。
- 参数:
data (pd.DataFrame) -- 输入数据
method (str, default='auto') -- 相关性计算方法:'auto'(自动选择)、'pearson'、'spearman'、'kendall'
missing_strategy (str, default='warn') -- 缺失值处理策略:'warn'、'drop'、'fill'
fill_method (str, optional) -- 填充方法:'mean'、'median'、'mode'、'knn'
pvalue_correction (str, default='fdr_bh') -- p值校正方法
verbose (bool, default=True) -- 是否输出详细信息
large_data_config (LargeDataConfig, optional) -- 大数据处理配置,用于优化大数据集的计算效率
示例
>>> analyzer = CorrAnalyzer(df) >>> result = analyzer.fit() >>> analyzer.plot_heatmap()
>>> # 大数据集优化 >>> from pycorrana.utils import LargeDataConfig >>> config = LargeDataConfig(sample_size=100000, auto_sample=True) >>> analyzer = CorrAnalyzer(large_df, large_data_config=config)
- __init__(data: DataFrame, method: str = 'auto', missing_strategy: str = 'warn', fill_method: str | None = None, pvalue_correction: str = 'fdr_bh', verbose: bool = True, large_data_config: LargeDataConfig | None = None)[源代码]
- preprocess() CorrAnalyzer[源代码]
数据预处理:类型推断、缺失值处理、大数据优化。
- 返回类型:
self
- compute_correlation(target: str | None = None, columns: List[str] | None = None) CorrAnalyzer[源代码]
计算相关性矩阵。
- plot_heatmap(figsize: Tuple[int, int] = (10, 8), annot: bool = True, cmap: str = 'RdBu_r', cluster: bool = False, savefig: str | None = None, **kwargs)[源代码]
绘制相关性热力图。
- plot_pairplot(columns: List[str] | None = None, hue: str | None = None, savefig: str | None = None, **kwargs)[源代码]
绘制散点图矩阵。
- plot_boxplot(numeric_col: str, categorical_col: str, kind: str = 'box', savefig: str | None = None, **kwargs)[源代码]
绘制数值变量按分类变量分组的箱线图/小提琴图。
- cca(x_vars: List[str], y_vars: List[str], compute_significance: bool = True, confidence_level: float = 0.95, n_permutations: int = 1000) Dict[源代码]
执行典型相关分析(Canonical Correlation Analysis, CCA)。
典型相关分析用于研究两组变量之间的线性关系。它寻找两组变量的 线性组合(典型变量),使得这些组合之间的相关性最大化。
- 参数:
- 返回:
CCA分析结果,包含: - canonical_correlations: 典型相关系数数组 - x_weights: X的典型变量系数 - y_weights: Y的典型变量系数 - x_scores: X的典型变量得分 - y_scores: Y的典型变量得分 - significance_tests: 显著性检验结果 - confidence_intervals: 置信区间 - redundancy: 冗余分析结果
- 返回类型:
示例
>>> analyzer = CorrAnalyzer(df) >>> analyzer.fit() >>> cca_result = analyzer.cca(x_vars=['var1', 'var2'], y_vars=['var3', 'var4']) >>> print(cca_result['canonical_correlations'])
引用
Hotelling, H. (1936). "Relations between two sets of variates" Biometrika, 28(3/4), 321-377
偏相关分析模块
partial_corr 函数
- pycorrana.partial_corr(data: DataFrame, x: str, y: str, covars: str | List[str], method: str = 'pearson') dict[源代码]
计算两个变量在控制协变量后的偏相关系数。
偏相关用于衡量两个变量在排除其他变量影响后的净相关关系。
- 参数:
- 返回:
包含偏相关系数、p值、置信区间等信息的字典
- 返回类型:
示例
>>> # 控制年龄后,计算身高与体重的偏相关 >>> result = partial_corr(df, x='height', y='weight', covars='age')
>>> # 控制多个变量 >>> result = partial_corr(df, x='X1', y='X2', covars=['Z1', 'Z2', 'Z3'])
partial_corr_matrix 函数
semipartial_corr 函数
PartialCorrAnalyzer 类
- class pycorrana.PartialCorrAnalyzer(data: DataFrame, verbose: bool = True)[源代码]
偏相关分析器类
提供偏相关分析的完整流程。
示例
>>> analyzer = PartialCorrAnalyzer(df) >>> result = analyzer.fit(x='income', y='happiness', covars=['age', 'education']) >>> matrix = analyzer.fit_matrix(covars='age')
- __init__(data: DataFrame, verbose: bool = True)[源代码]
- 参数:
data (pd.DataFrame) -- 输入数据
verbose (bool, default=True) -- 是否输出详细信息
非线性分析模块
distance_correlation 函数
- pycorrana.distance_correlation(x: ndarray, y: ndarray, return_pvalue: bool = False, n_permutations: int = 1000, confidence_level: float = 0.95, n_bootstrap: int = 500) dict[源代码]
计算距离相关系数(Distance Correlation)。
距离相关可以检测变量间的任意类型依赖关系(包括非线性), 当且仅当变量独立时距离相关为0。
- 参数:
- 返回:
包含距离相关系数、p值和置信区间的字典
- 返回类型:
示例
>>> x = np.random.randn(100) >>> y = x**2 + np.random.randn(100) * 0.1 >>> result = distance_correlation(x, y, return_pvalue=True) >>> print(f"dCor: {result['dcor']:.4f}, p-value: {result['p_value']:.4f}") >>> print(f"95% CI: {result['confidence_interval']}")
引用
Székely, G.J., Rizzo, M.L., and Bakirov, N.K. (2007) "Measuring and testing dependence by correlation of distances" Annals of Statistics, Vol. 35 No. 6, pp. 2769-2794
mutual_info_score 函数
- pycorrana.mutual_info_score(x: ndarray, y: ndarray, discrete_features: bool = False, n_neighbors: int = 3, return_pvalue: bool = False, n_permutations: int = 1000) dict[源代码]
计算互信息分数。
互信息衡量两个变量共享的信息量,可以检测非线性依赖关系。
- 参数:
- 返回:
包含互信息分数、p值和置信区间的字典
- 返回类型:
示例
>>> x = np.random.randn(100) >>> y = np.sin(x) + np.random.randn(100) * 0.1 >>> result = mutual_info_score(x, y, return_pvalue=True) >>> print(f"MI: {result['mi']:.4f}, Normalized: {result['mi_normalized']:.4f}, p-value: {result['p_value']:.4f}")
maximal_information_coefficient 函数
- pycorrana.maximal_information_coefficient(x: ndarray, y: ndarray, B: float | None = None, return_pvalue: bool = False, n_permutations: int = 1000, confidence_level: float = 0.95, n_bootstrap: int = 500) dict[源代码]
计算最大信息系数(Maximal Information Coefficient, MIC)。
MIC可以检测各种函数关系的强度,范围在[0, 1]。 使用完整的MIC算法实现,包括最优网格划分和归一化。
核心公式: MIC(X,Y) = max_{i*j < B} I*(X,Y,i,j) / log(min(i,j))
其中: - i, j:X轴和Y轴的网格划分数量 - B = n^0.6:网格复杂度上限 - I*:在i×j网格下的最大互信息 - 分母log(min(i,j)):归一化因子
警告
当前版本为纯 Python 实现,没有特殊优化,计算速度较慢。 对于大数据集(n > 1000),建议先进行采样处理。
- 参数:
- 返回:
包含以下键的字典: - mic: MIC值,范围[0, 1] - mas: 最大对称得分(Maximum Asymmetry Score) - mev: 最大边缘值(Maximum Edge Value) - mcn: 最大网格数(Maximum Cell Number) - n: 样本量 - p_value: p值(如果return_pvalue=True) - confidence_interval: 置信区间(如果样本量足够)
- 返回类型:
示例
>>> x = np.random.randn(100) >>> y = x**2 + np.random.randn(100) * 0.1 >>> result = maximal_information_coefficient(x, y, return_pvalue=True) >>> print(f"MIC: {result['mic']:.4f}, p-value: {result['p_value']:.4f}")
对于大数据集,建议先采样:
>>> from pycorrana.utils import smart_sample >>> sampled_df = smart_sample(df, sample_size=500) >>> result = maximal_information_coefficient(sampled_df['x'], sampled_df['y'])
引用
Reshef et al. (2011) "Detecting Novel Associations in Large Data Sets" Science, 334(6062), 1518-1524
nonlinear_dependency_report 函数
NonlinearAnalyzer 类
- class pycorrana.NonlinearAnalyzer(data: DataFrame, verbose: bool = True, sample_size: int = 20000)[源代码]
非线性依赖分析器类
提供非线性依赖检测的完整流程。
- 参数:
示例
>>> analyzer = NonlinearAnalyzer(df) >>> result = analyzer.analyze_pair('X', 'Y') >>> report = analyzer.generate_report()
典型相关分析模块
典型相关分析(Canonical Correlation Analysis, CCA)是一种多元统计方法, 用于研究两组变量之间的线性关系。它寻找两组变量的线性组合,使得这些组合之间的相关性最大化。
cca 函数
- pycorrana.cca(X: ndarray | DataFrame, Y: ndarray | DataFrame, compute_significance: bool = True, confidence_level: float = 0.95, n_permutations: int = 1000, verbose: bool = False) Dict[源代码]
执行典型相关分析(Canonical Correlation Analysis, CCA)。
典型相关分析用于研究两组变量之间的线性关系。它寻找两组变量的 线性组合(典型变量),使得这些组合之间的相关性最大化。
- 参数:
X (array-like or pd.DataFrame) -- 第一组变量,形状为 (n_samples, p)
Y (array-like or pd.DataFrame) -- 第二组变量,形状为 (n_samples, q)
compute_significance (bool, default=True) -- 是否计算显著性检验(p值)
confidence_level (float, default=0.95) -- 置信区间水平
n_permutations (int, default=1000) -- 置换检验次数(用于额外的显著性验证)
verbose (bool, default=False) -- 是否输出详细信息
- 返回:
包含以下键的字典: - canonical_correlations: 典型相关系数数组 - x_weights: X的典型变量系数(权重矩阵) - y_weights: Y的典型变量系数(权重矩阵) - x_scores: X的典型变量得分 - y_scores: Y的典型变量得分 - significance_tests: 显著性检验结果列表 - confidence_intervals: 置信区间列表 - redundancy: 冗余分析结果 - n_components: 典型变量对数 - n_samples: 样本量 - x_names: X的变量名(如果输入是DataFrame) - y_names: Y的变量名(如果输入是DataFrame)
- 返回类型:
示例
>>> import numpy as np >>> X = np.random.randn(100, 3) >>> Y = np.random.randn(100, 2) >>> result = cca(X, Y) >>> print(f"第一对典型相关系数: {result['canonical_correlations'][0]:.4f}")
>>> # 使用DataFrame >>> import pandas as pd >>> df = pd.DataFrame(np.random.randn(100, 5), ... columns=['x1', 'x2', 'x3', 'y1', 'y2']) >>> result = cca(df[['x1', 'x2', 'x3']], df[['y1', 'y2']])
引用
Hotelling, H. (1936). "Relations between two sets of variates" Biometrika, 28(3/4), 321-377
cca_permutation_test 函数
- pycorrana.cca_permutation_test(X: ndarray | DataFrame, Y: ndarray | DataFrame, n_permutations: int = 1000, random_state: int | None = None) Dict[源代码]
使用置换检验验证CCA结果的显著性。
置换检验通过随机打乱样本标签来生成零假设分布, 然后比较观测到的典型相关系数与零假设分布。
- 参数:
- 返回:
包含置换检验结果的字典
- 返回类型:
示例
>>> X = np.random.randn(100, 3) >>> Y = np.random.randn(100, 2) >>> result = cca_permutation_test(X, Y, n_permutations=500) >>> print(f"第一对典型相关系数p值: {result['p_values'][0]:.4f}")
CCAAnalyzer 类
- class pycorrana.CCAAnalyzer(X: DataFrame | ndarray, Y: DataFrame | ndarray, verbose: bool = True)[源代码]
典型相关分析器类
提供完整的典型相关分析流程,包括分析、可视化和结果解释。
- 参数:
X (pd.DataFrame) -- 第一组变量
Y (pd.DataFrame) -- 第二组变量
verbose (bool, default=True) -- 是否输出详细信息
示例
>>> analyzer = CCAAnalyzer(df[['x1', 'x2']], df[['y1', 'y2']]) >>> result = analyzer.fit() >>> analyzer.summary() >>> analyzer.plot_weights()
- fit(compute_significance: bool = True, confidence_level: float = 0.95, n_permutations: int = 1000) Dict[源代码]
执行典型相关分析。
- get_weights(component: int = 1) DataFrame[源代码]
获取指定典型变量的权重。
- 参数:
component (int) -- 典型变量序号(从1开始)
- 返回:
权重数据框
- 返回类型:
pd.DataFrame
- plot_weights(component: int = 1, figsize: Tuple[int, int] = (12, 5), savefig: str | None = None)[源代码]
绘制典型变量权重图。
- plot_scores(component: int = 1, figsize: Tuple[int, int] = (8, 8), savefig: str | None = None)[源代码]
绘制典型变量得分散点图。
可视化模块
CorrVisualizer 类
- class pycorrana.core.visualizer.CorrVisualizer(style: str = 'seaborn-v0_8-whitegrid')[源代码]
相关性可视化器
提供多种相关性可视化图表。
- __init__(style: str = 'seaborn-v0_8-whitegrid')[源代码]
- 参数:
style (str, default='seaborn-v0_8-whitegrid') -- matplotlib样式
- plot_heatmap(corr_matrix: DataFrame, figsize: Tuple[int, int] = (10, 8), annot: bool = True, fmt: str = '.2f', cmap: str = 'RdBu_r', center: float = 0, vmin: float = -1, vmax: float = 1, cluster: bool = False, mask_upper: bool = False, title: str | None = None, savefig: str | None = None, dpi: int = 100, **kwargs) Figure[源代码]
绘制相关性热力图。
- 参数:
corr_matrix (pd.DataFrame) -- 相关性矩阵
figsize (tuple, default=(10, 8)) -- 图表大小
annot (bool, default=True) -- 是否显示数值标注
fmt (str, default='.2f') -- 数值格式
cmap (str, default='RdBu_r') -- 颜色映射
center (float, default=0) -- 颜色中心值
vmin (float, default=-1, 1) -- 颜色范围
vmax (float, default=-1, 1) -- 颜色范围
cluster (bool, default=False) -- 是否进行层次聚类
mask_upper (bool, default=False) -- 是否只显示下三角
title (str, optional) -- 图表标题
savefig (str, optional) -- 保存路径
dpi (int, default=100) -- 分辨率
**kwargs -- 其他参数传递给seaborn.heatmap
- 返回:
matplotlib图表对象
- 返回类型:
plt.Figure
- plot_pairplot(data: DataFrame, columns: List[str] | None = None, hue: str | None = None, diag_kind: str = 'kde', kind: str = 'scatter', corner: bool = False, height: float = 2.5, aspect: float = 1, savefig: str | None = None, **kwargs) PairGrid[源代码]
绘制散点图矩阵。
- 参数:
data (pd.DataFrame) -- 输入数据
columns (list, optional) -- 要绘制的列
hue (str, optional) -- 用于颜色区分的列
diag_kind (str, default='kde') -- 对角线图表类型:'kde'、'hist'
kind (str, default='scatter') -- 非对角线图表类型:'scatter'、'reg'
corner (bool, default=False) -- 是否只绘制下三角
height (float, default=2.5) -- 每个子图的高度
aspect (float, default=1) -- 宽高比
savefig (str, optional) -- 保存路径
**kwargs -- 其他参数传递给seaborn.pairplot
- 返回:
seaborn PairGrid对象
- 返回类型:
sns.PairGrid
- plot_boxplot(data: DataFrame, numeric_col: str, categorical_col: str, kind: str = 'box', figsize: Tuple[int, int] = (10, 6), palette: str = 'Set2', show_points: bool = False, savefig: str | None = None, **kwargs) Figure[源代码]
绘制数值变量按分类变量分组的箱线图/小提琴图。
- 参数:
data (pd.DataFrame) -- 输入数据
numeric_col (str) -- 数值列名
categorical_col (str) -- 分类列名
kind (str, default='box') -- 图表类型:'box'、'violin'、'boxen'、'strip'、'swarm'
figsize (tuple, default=(10, 6)) -- 图表大小
palette (str, default='Set2') -- 颜色调色板
show_points (bool, default=False) -- 是否显示原始数据点
savefig (str, optional) -- 保存路径
**kwargs -- 其他参数
- 返回:
matplotlib图表对象
- 返回类型:
plt.Figure
- plot_correlation_network(corr_matrix: DataFrame, threshold: float = 0.5, figsize: Tuple[int, int] = (12, 12), savefig: str | None = None, **kwargs) Figure[源代码]
绘制相关性网络图。
报告生成模块
CorrReporter 类
- class pycorrana.core.reporter.CorrReporter[源代码]
相关性报告生成器
提供结果导出和文本摘要功能。
- export_results(corr_matrix: DataFrame, pvalue_matrix: DataFrame, significant_pairs: List[dict], path: str, format: str = 'excel') str[源代码]
导出分析结果。
- generate_summary(significant_pairs: List[dict], methods_used: Dict[str, str] | None = None, max_pairs_display: int = 10) str[源代码]
生成文本摘要。
- to_markdown(corr_matrix: DataFrame, significant_pairs: List[dict], title: str = '相关性分析报告') str[源代码]
生成Markdown格式报告。
数据处理工具
load_data 函数
- pycorrana.utils.data_utils.load_data(data: str | Path | DataFrame | DataFrame) DataFrame[源代码]
智能数据加载器,支持多种输入格式。
- 参数:
data (str, Path, pd.DataFrame, pl.DataFrame) -- 数据输入,可以是文件路径或DataFrame对象
- 返回:
标准化的pandas DataFrame
- 返回类型:
pd.DataFrame
示例
>>> df = load_data('data.csv') >>> df = load_data('data.xlsx') >>> df = load_data(polars_df)
infer_types 函数
handle_missing 函数
- pycorrana.utils.data_utils.handle_missing(df: DataFrame, strategy: str = 'warn', fill_method: str | None = None, verbose: bool = True) DataFrame[源代码]
缺失值处理工具。
- 参数:
df (pd.DataFrame) -- 输入数据
strategy (str, default='warn') -- 处理策略: - 'warn': 仅输出警告信息 - 'drop': 删除含缺失值的行 - 'fill': 使用fill_method填充
fill_method (str, optional) -- 填充方法,当strategy='fill'时使用: - 'mean': 均值填充(数值型) - 'median': 中位数填充(数值型) - 'mode': 众数填充 - 'knn': KNN预测填充
verbose (bool, default=True) -- 是否输出详细信息
- 返回:
处理后的数据
- 返回类型:
pd.DataFrame
detect_outliers 函数
is_large_data 函数
estimate_memory_usage 函数
统计工具
check_normality 函数
correct_pvalues 函数
cramers_v 函数
eta_coefficient 函数
point_biserial 函数
interpret_correlation 函数
大数据优化模块
LargeDataConfig 类
- class pycorrana.utils.large_data.LargeDataConfig(sample_size: int = 50000, chunk_size: int = 10000, auto_sample: bool = True, auto_optimize: bool = True, threshold_rows: int = 100000, threshold_memory_mb: float = 500, stratify_column: str | None = None, random_state: int = 42, verbose: bool = True)[源代码]
大数据处理配置类。
示例
>>> config = LargeDataConfig( ... sample_size=100000, ... chunk_size=50000, ... auto_sample=True ... ) >>> analyzer = CorrAnalyzer(df, large_data_config=config)