跳到主要内容

统计分析

收藏0

按数据情况选对检验方法、先查前提假设、再算效应量与样本量,最后按 APA 格式写报告;覆盖 t 检验、方差分析、卡方、相关、回归、非参数与贝叶斯方法。

让 AI 安装

星光尘缘LV2最新版本 0.1.0更新于 2026-11-12下载 0 次

references/assumptions_and_diagnostics.md

14.3 KB查看排版效果
1# Statistical Assumptions and Diagnostic Procedures
2
3This document provides comprehensive guidance on checking and validating statistical assumptions for various analyses.
4
5## General Principles
6
71. **Always check assumptions before interpreting test results**
82. **Use multiple diagnostic methods** (visual + formal tests)
93. **Consider robustness**: Some tests are robust to violations under certain conditions
104. **Document all assumption checks** in analysis reports
115. **Report violations and remedial actions taken**
12
13## Common Assumptions Across Tests
14
15### 1. Independence of Observations
16
17**What it means**: Each observation is independent; measurements on one subject do not influence measurements on another.
18
19**How to check**:
20- Review study design and data collection procedures
21- For time series: Check autocorrelation (ACF/PACF plots, Durbin-Watson test)
22- For clustered data: Consider intraclass correlation (ICC)
23
24**What to do if violated**:
25- Use mixed-effects models for clustered/hierarchical data
26- Use time series methods for temporally dependent data
27- Use generalized estimating equations (GEE) for correlated data
28
29**Critical severity**: HIGH - violations can severely inflate Type I error
30
31---
32
33### 2. Normality
34
35**What it means**: Data or residuals follow a normal (Gaussian) distribution.
36
37**When required**:
38- Small-sample normal-theory t/ANOVA inference: the relevant errors (paired differences for paired tests), not arbitrary pooled data
39- Linear regression: normal errors support exact finite-sample t/F inference; coefficient estimation itself does not require normal outcomes or predictors
40- Some correlation tests (Pearson)
41
42**How to check**:
43
44**Visual methods** (primary):
45- Q-Q (quantile-quantile) plot: Points should fall on diagonal line
46- Histogram with normal curve overlay
47- Kernel density plot
48
49**Formal tests** (secondary):
50- Shapiro-Wilk test (good default; scipy handles n up to ~5000 and warns above that)
51- Lilliefors test (`statsmodels.stats.diagnostic.lilliefors`) — use this instead of a plain Kolmogorov-Smirnov test, which is invalid when the mean/SD are estimated from the data
52- Anderson-Darling test
53
54**Python implementation**:
55```python
56from scipy import stats
57import matplotlib.pyplot as plt
58
59# Shapiro-Wilk test
60statistic, p_value = stats.shapiro(data)
61
62# Q-Q plot
63stats.probplot(data, dist="norm", plot=plt)
64```
65
66**Interpretation guidance**:
67- Assess plots, tail behavior, sample balance, dependence and the estimand at every sample size. Formal tests have low power in small samples and detect tiny departures in large samples; non-rejection does not validate a model.
68- Look for severe skewness, outliers, or bimodality
69
70**What to do if violated**:
71- **Departures**: Evaluate robustness for the target effect and design; there is no universal n=30 threshold. Prespecify robust inference or simulation-based sensitivity. Rank methods change the target and retain assumptions; they are not automatic replacements.
72- **Severe violations**:
73 - Transform data (log, square root, Box-Cox)
74 - Use non-parametric methods
75 - Use robust regression methods
76 - Consider bootstrapping
77
78**Critical severity**: MEDIUM - parametric tests are often robust to mild violations with adequate sample size
79
80---
81
82### 3. Homogeneity of Variance (Homoscedasticity)
83
84**What it means**: Variances are equal across groups or across the range of predictors.
85
86**When required**:
87- Pooled Student's t-test and classical equal-variance ANOVA (not Welch tests)
88- Usual homoscedastic OLS standard errors; HC3 addresses independent heteroscedastic errors, not clusters
89
90**How to check**:
91
92**Visual methods** (primary):
93- Box plots by group (for t-test/ANOVA)
94- Residuals vs. fitted values plot (for regression) - should show random scatter
95- Scale-location plot (square root of standardized residuals vs. fitted)
96
97**Formal tests** (secondary):
98- Levene's test (robust to non-normality)
99- Bartlett's test (sensitive to non-normality, not recommended)
100- Brown-Forsythe test (median-based version of Levene's)
101- Breusch-Pagan test (for regression)
102
103**Python implementation**:
104```python
105from scipy import stats
106import pingouin as pg
107
108# Median-centered Levene is the Brown-Forsythe variance test
109statistic, p_value = stats.levene(group1, group2, group3, center='median')
110
111# For regression
112# Breusch-Pagan test
113# Note: exog must include the constant column (e.g. exog = sm.add_constant(X),
114# or pass the fitted model's model.exog)
115from statsmodels.stats.diagnostic import het_breuschpagan
116_, p_value, _, _ = het_breuschpagan(residuals, exog)
117```
118
119**Interpretation guidance**:
120- No variance-ratio cutoff certifies validity. Balanced designs can help robustness but do not remove tail, dependence or variance concerns.
121- Do not choose pooled versus Welch inference based only on a preliminary variance p-value.
122- For regression: Look for funnel patterns in residual plots
123
124**What to do if violated**:
125- **t-test**: Use Welch's t-test (does not assume equal variances)
126- **ANOVA**: Use Welch's ANOVA or Brown-Forsythe ANOVA
127- **Regression**:
128 - Transform dependent variable (log, square root)
129 - Use weighted least squares (WLS)
130 - Use robust standard errors (HC3)
131 - Use generalized linear models (GLM) with appropriate variance function
132
133**Critical severity**: MEDIUM - tests can be robust with equal sample sizes
134
135---
136
137## Test-Specific Assumptions
138
139### T-Tests
140
141**Assumptions**:
1421. Independence of observations
1432. Normality (each group for independent t-test; differences for paired t-test)
1443. Homogeneity only for pooled Student's independent t-test; Welch permits unequal variances
145
146**Diagnostic workflow**:
147```python
148import scipy.stats as stats
149import pingouin as pg
150
151# Check normality for each group
152stats.shapiro(group1)
153stats.shapiro(group2)
154
155# Check homogeneity of variance
156stats.levene(group1, group2)
157
158# Prespecify inference from the design/estimand rather than the screening p-values:
159# Option 1: Welch's t-test (unequal variances)
160pg.ttest(group1, group2, correction=True) # correction=True applies Welch's
161# (correction='auto' applies Welch only when sample sizes are unequal;
162# correction=False forces Student's t-test)
163
164# Option 2: A separately justified rank/distribution question
165pg.mwu(group1, group2) # Mann-Whitney U
166```
167
168---
169
170### ANOVA
171
172**Assumptions**:
1731. Independence of observations within and between groups
1742. Normality in each group
1753. Homogeneity of variance across groups
176
177**Additional considerations**:
178- For repeated measures ANOVA: Sphericity assumption (Mauchly's test)
179
180**Diagnostic workflow**:
181```python
182import pingouin as pg
183from scipy import stats
184
185# Check normality per group
186for group in df['group'].unique():
187 data = df[df['group'] == group]['value']
188 w, p = stats.shapiro(data)
189 print(f"{group}: W = {w:.3f}, p = {p:.4f}")
190
191# Check homogeneity of variance
192print(pg.homoscedasticity(df, dv='value', group='group'))
193
194# For repeated measures: Check sphericity
195# Pingouin 0.7 supports one/two-way sphericity diagnostics; earlier interaction
196# corrections had bugs. Specify subject IDs and complete within-subject cells.
197```
198
199**What to do if sphericity violated** (repeated measures):
200- Prespecify a correction such as Greenhouse-Geisser; Pingouin rm_anova reports GG.
201- Do not infer Huynh-Feldt is automatically available from an epsilon threshold.
202- Use multivariate approach (MANOVA)
203
204---
205
206### Linear Regression
207
208**Assumptions**:
2091. **Mean specification**: Conditional mean is linear in fitted coefficients (can include justified nonlinear predictor terms)
2102. **Independence**: Residuals are independent
2113. **Homoscedasticity**: Constant variance of residuals
2124. **Normality**: Normal errors for exact small-sample conventional inference; fitted residuals are correlated projections, so residual Shapiro is only a screen
2135. **Identifiability**: Full-rank design; high collinearity affects precision but is not by itself bias
2146. **Exogeneity**: The conditional error mean is zero; residual plots do not establish causal identification
215
216**Diagnostic workflow**:
217
218**1. Linearity**:
219```python
220import matplotlib.pyplot as plt
221import seaborn as sns
222
223# Scatter plots of Y vs each X
224# Residuals vs. fitted values (should be randomly scattered)
225plt.scatter(fitted_values, residuals)
226plt.axhline(y=0, color='r', linestyle='--')
227```
228
229**2. Independence**:
230```python
231from statsmodels.stats.stattools import durbin_watson
232
233# Durbin-Watson test (for time series)
234dw_statistic = durbin_watson(residuals)
235# Meaningful row order is required; no universal 1.5-2.5 acceptance interval.
236# This statistic cannot establish independence, particularly for clustered data.
237```
238
239**3. Homoscedasticity**:
240```python
241# Breusch-Pagan test
242# Note: exog must include the constant column (e.g. sm.add_constant(X))
243from statsmodels.stats.diagnostic import het_breuschpagan
244_, p_value, _, _ = het_breuschpagan(residuals, exog)
245
246# Visual: Scale-location plot
247plt.scatter(fitted_values, np.sqrt(np.abs(std_residuals)))
248```
249
250**4. Normality of residuals**:
251```python
252# Q-Q plot of residuals
253stats.probplot(residuals, dist="norm", plot=plt)
254
255# Shapiro-Wilk test
256stats.shapiro(residuals)
257```
258
259**5. Multicollinearity**:
260```python
261from statsmodels.stats.outliers_influence import variance_inflation_factor
262
263# Calculate VIF for each predictor
264vif_data = pd.DataFrame()
265vif_data["feature"] = X.columns
266vif_data["VIF"] = [variance_inflation_factor(X.values, i) for i in range(len(X.columns))]
267
268# VIF > 10 indicates severe multicollinearity
269# VIF > 5 indicates moderate multicollinearity
270```
271
272**What to do if violated**:
273- **Non-linearity**: Add polynomial terms, use GAM, or transform variables
274- **Heteroscedasticity**: Transform Y, use WLS, use robust SE
275- **Non-normal residuals**: Transform Y, use robust methods, check for outliers
276- **Multicollinearity**: Examine precision and identification; dropping confounders can bias estimates. Regularization changes inference and must match the purpose.
277
278---
279
280### Logistic Regression
281
282**Assumptions**:
2831. **Independence**: Observations are independent
2842. **Linearity**: Linear relationship between log-odds and continuous predictors
2853. **No perfect multicollinearity**: Predictors not perfectly correlated
2864. **Information and identification**: Adequate events/non-events for parameters, effect sizes and precision; check separation and convergence. No fixed events-per-variable ratio guarantees valid inference.
287
288**Diagnostic workflow**:
289
290**1. Linearity of logit**:
291```python
292# Box-Tidwell test: Add interaction with log of continuous predictor
293# If interaction is significant, linearity violated
294```
295
296**2. Multicollinearity**:
297```python
298# Use VIF as in linear regression
299```
300
301**3. Influential observations**:
302```python
303# Cook's distance, DFBetas, leverage (statsmodels >= 0.10)
304# Do NOT use OLSInfluence on Logit/GLM results; use get_influence(),
305# which returns MLEInfluence (Logit) or GLMInfluence (GLM)
306influence = model.get_influence()
307cooks_d, cooks_p = influence.cooks_distance # tuple: (distances, approximate p-values)
308# Outside Gaussian linear models these F-based p-values are approximate.
309```
310
311**4. Model fit / calibration**:
312```python
313# Calibration curve: compare predicted probabilities to observed event rates
314# (e.g. sklearn.calibration.calibration_curve), plus the Brier score
315# Pseudo R-squared
316# Classification metrics (accuracy, AUC-ROC)
317# Note: the Hosmer-Lemeshow test is not implemented in scipy/statsmodels
318# and is sensitive to the choice of bins; prefer calibration curves
319```
320
321---
322
323## Outlier Detection
324
325**Methods**:
3261. **Visual**: Box plots, scatter plots
3272. **Statistical**:
328 - Z-scores: |z| > 3 suggests outlier
329 - IQR method: Values < Q1 - 1.5×IQR or > Q3 + 1.5×IQR
330 - Modified Z-score using median absolute deviation (robust to outliers)
331
332**For regression**:
333- **Leverage**: High leverage points (hat values)
334- **Influence**: Cook's distance > 4/n suggests influential point
335- **Outliers**: Studentized residuals > ±3
336
337**What to do**:
3381. Investigate data entry errors
3392. Consider if outliers are valid observations
3403. Report sensitivity analysis (results with and without outliers)
3414. Use robust methods if outliers are legitimate
342
343---
344
345## Sample Size Considerations
346
347### Design-specific planning
348
349Plan using the target effect or desired interval width, variance, prevalence, number of fitted parameters, clustering and attrition. Generic n=30/n=50 or events-per-variable thresholds do not establish power, robustness or model reliability. Simulate the actual planned estimator/design when closed-form assumptions do not apply.
350
351### Small Sample Considerations
352
353For small samples:
354- Assumptions become more critical
355- Use exact tests when available (Fisher's exact, exact logistic regression)
356- Consider non-parametric alternatives
357- Use permutation tests or bootstrap methods
358- Be conservative with interpretation
359
360---
361
362## Reporting Assumption Checks
363
364When reporting analyses, include:
365
3661. **Statement of assumptions checked**: List all assumptions tested
3672. **Methods used**: Describe visual and formal tests employed
3683. **Results of diagnostic tests**: Report test statistics and p-values
3694. **Assessment**: State evidence of departures and limits of the screens; never equate non-rejection with verified assumptions
3705. **Actions taken**: If violated, describe remedial actions (transformations, alternative tests, robust methods)
371
372**Example reporting statement**:
373> "Normality was assessed using Shapiro-Wilk tests and Q-Q plots. Data for Group A (W = 0.97, p = .18) and Group B (W = 0.96, p = .12) showed no significant departure from normality. Homogeneity of variance was assessed using Levene's test, which was non-significant (F(1, 58) = 1.23, p = .27), providing no detected departure from equal variances at this sample size. Non-rejection does not verify equality; the prespecified Welch test and design review were retained."
374
375## Current API sources
376
377Reviewed 2026-10-01: [SciPy Shapiro](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.shapiro.html) requires at least three observations and warns that n>5000 p-values may be inaccurate; [Levene](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.levene.html) defaults to median centering. [statsmodels Breusch-Pagan](https://www.statsmodels.org/stable/generated/statsmodels.stats.diagnostic.het_breuschpagan.html) defaults to the Koenker variant (`robust=True`), needs an intercept, and also returns the finite-sample F variant; report which one is used. [Durbin-Watson](https://www.statsmodels.org/stable/generated/statsmodels.stats.stattools.durbin_watson.html) is a statistic of adjacent residuals, not an independence certificate.

文件内容是平台检查时读出的文本,只供查看。平台不会运行包里的任何脚本或程序。