Hypothesis testing and p-values
Understand hypothesis tests and p-values, interpret type I and II errors and test–interval duality, quantify false positive risk and use equivalence testing.
After this lesson you can
- Define test size, power, type I and type II errors and valid p-values.
- Explain test–confidence interval duality and distinguish one-sided and two-sided tests.
- Interpret p-values correctly and quantify false positive risk using prior prevalence and power.
- Apply two one-sided tests to assess equivalence with a prespecified margin.
Before you start
Motivation: did the new detector really improve?
Your team trained a new vulnerability-detector version and compares it with the current one on 40 repositories with known vulnerabilities. For each repository you measure the new-minus-old F1 difference in percentage points. (The data in this lesson are simulated: there is no real benchmark behind them.) The result is:
import numpy as np
from scipy import stats
rng = np.random.default_rng(1)
d = rng.normal(1.0, 4.0, 40) # diferencia de F1 (nueva menos antigua) en 40 repositorios; simulado, media real 1.0
r = stats.ttest_1samp(d, 0.0)
ic = r.confidence_interval(0.95)
print(f"media {d.mean():.3f} desviación {d.std(ddof=1):.3f} n = {d.size}")
print(f"t = {r.statistic:.3f} p bilateral = {r.pvalue:.4f}")
print(f"IC 95 %: [{ic.low:.3f}, {ic.high:.3f}]")The new version gains 1.01 points on average, but with deviation 3.77 across repositories that could be noise. The value is 0.0975. What do you conclude? Three tempting interpretations are all superficially defensible.
- “, so there is no improvement.” The 95 % interval is : it includes improvements of more than 2 points. Data that do not rule out zero are not evidence that the effect is zero.
- “, so there is a 90 % chance it improves.” A value is a probability about data assuming a hypothesis, not a probability of the hypothesis. This is the most widespread confusion in applied statistics.
- “With a one-sided test, : now it improves.” Same data, same model, opposite conclusion. This is legitimate only if “one-sided” was chosen before seeing the effect’s direction; choosing afterward is a trap doubling the false-positive rate.
This lesson builds a framework for answering without getting lost. It covers five questions:
- What is a test? Hypotheses, statistic, rejection region and level, and the two possible errors and which is controlled.
- What is (and is not) a value? Its exact definition, uniform distribution under the null, and misinterpretations catalogued in the ASA statement.
- How tests and intervals relate: a confidence interval is an inverted test, and a test is an interval read backward.
- What fraction of “significant” findings are false, and why that depends on things the value cannot see.
- How to demonstrate absence of a relevant effect: equivalence tests, which reverse the burden of proof.
We use a statistic’s sampling distribution, pivotal quantities, and confidence intervals from the previous lesson, and normal theory from lesson 2.
Anatomy of a hypothesis test
Start with a statistical model for data . A hypothesis is a claim about the parameter, that is, a subset of . A test compares two mutually exclusive, exhaustive hypotheses: null and alternative . A hypothesis is simple if it fixes one value (), otherwise composite.
The definition separates two worlds. For , is the probability of incorrectly rejecting: we want it small. For , is the probability of correctly rejecting: we want it large. A good test has power below in and rising toward 1 in .
The canonical example: the test
Let with known , and test against . The natural statistic is the standardized mean,
and we reject for large values: . If the true mean is , then with , so
increases in , so its supremum over occurs at boundary (where ): size is . For exactly , take , the standard normal’s quantile. With , .
When is unknown replace it with sample standard deviation ; the statistic becomes , which under follows Student’s with degrees of freedom (normal theory). It is a pivot under the null: its distribution has no unknown parameters, allowing calibration of the threshold. The general recipe has four ingredients:
| Ingredient | In the test | Requirement |
|---|---|---|
| Hypotheses | versus | Fixed before seeing data |
| Statistic | Large when is plausible | |
| Null distribution | if | Calculable without unknown parameters |
| Rejection region | Size |
The asymmetry between hypotheses is deliberate and central. is presumed until data make it untenable (the new detector is no better, the drug does not work, the estimator is unbiased), and the test makes erroneous rejection rare. The burden of proof lies with . Thus not rejecting is not accepting it: the data did not suffice to refute it, possibly because is true or because the test lacked power.
Two errors and the cost of the threshold
A test can err in two ways.
| true | true | |
|---|---|---|
| Reject | Type I error (false positive), probability | Correct, probability (power) |
| Do not reject | Correct | Type II error (false negative), probability |
Type I and type II errors have immediate expressions in terms of power: type I is for , bounded by level ; type II is for , which depends on the true alternative. While is a design decision, is not chosen: it follows from , , noise and actual effect size.
For the one-sided test the calculation is explicit. With standardized effect and ,
Four facts follow directly. Power rises with effect and , depending on them only through their product : doubling effect equals quadrupling data. It falls when a smaller is required, because grows. And as , power tends to : a tiny effect is indistinguishable from the null, the only thing that ought to be indistinguishable.
Three lessons from the interactive. Moving the threshold is not free. With and (), a one-sided test at has , at it rises to , and at to . Rarer false positives cost more missed real effects. Only data move the curve. With observations doubles and the same yields 97 % power. Effect size matters. Sample size for power 0.8 at is , i.e. 25 observations; detecting needs 619. Choosing before collecting data is covered in power and sample size.
The value
Fixing in advance gives a binary answer. But the same would reject at 5 % and 1 %, whereas would reject only at 5 %. The value summarizes this: the smallest level at which rejection would occur.
For the one-sided test, ; for two-sided, . In the motivating example is with 39 degrees of freedom: the upper tail gives and both tails .
A reading trap deserves attention. is a random variable: it changes from sample to sample. Its fundamental property is its distribution when is true.
Proof
(b) If is continuous, and hence . By the probability integral transform, when is continuous. Thus .
(a) Fix and write , a decreasing function. By definition , so . We show . The set is an upper ray with endpoint . If it contains , . Otherwise , because for all . Finally, rejecting when has probability at most under each .
∎This theorem makes values useful: under the null, it is uniform, so , and so on. This places any on a common scale regardless of statistic, model or sample size. The figure shows this by repeating the experiment thousands of times.
With and , rejection is 5 % at any . With binomial versus and , possible values near 0.05 are and : rejecting at is equivalent to rejecting at , and actual level is 1.07 %, not 5 %. This is part (a): may be strict, and with discrete statistics almost always is. The test is conservative: it never exceeds , at the cost of power. Increasing refines the grid of possible values and reduces the issue, though it never disappears entirely.
Fisher versus Neyman and Pearson
The value and level come from two traditions that competed for decades and are mixed without warning in modern practice.
| Fisher (years 20 to 50 of the twentieth century) | Neyman and Pearson (1933) | |
|---|---|---|
| Question | How compatible are these data with ? | What decision controls errors in the long run? |
| Tool | Exact value as a graded measure of discrepancy | Rejection region of prespecified size |
| Alternative | Not required | Essential: defines what makes a good region (power) |
| Guarantee | None over repetitions; evidence from one experiment | Error frequencies and over procedure repetitions |
| Result | “” | “Reject at level 0.05” |
Fisher presented as a convenient threshold for deviations deserving attention, and in his later work (Statistical Methods and Scientific Inference, 1956) insisted no fixed level suits every case and evidence strength must be evaluated for each experiment. Neyman and Pearson built decision theory: compare tests of equal size, choose the most powerful (Neyman–Pearson lemma), and interpret as the procedure’s error frequency, not that of a particular result. Modern practice is a hybrid: calculate like Fisher, compare with 0.05 like Neyman and Pearson, and say “significant” without specifying alternative or power.
The distinction matters for what can be claimed. Fixed is a property of the procedure: “if I apply this rule to many experiments where is true, 5 % will be errors.” It is not a probability about this experiment. A value measures discrepancy, not probability of correctness. When someone says “there is a 3 % chance the result is due to chance,” suspect an unwarranted jump between these statements.
One-sided versus two-sided
The alternative determines what counts as “extreme”. With only the right statistic tail counts; with both do, and for a symmetric statistic . At the same level, the two-sided threshold is stricter ( versus with ), so the two-sided test has less power in the direction of interest and more in the opposite direction. Here “izq” and “der” denote left and right tails.
The rule is easy to state and hard to follow: choose the alternative from the problem before seeing data. A one-sided test is legitimate if an effect in the other direction would lead to exactly the same decision as no effect (e.g. “deploy the new version only if it improves; if it worsens or stays equal, keep the old one”). If effects in either direction have their own consequences, use a two-sided test.
To see why choosing afterward is a trap, suppose you inspect the sign of and then test one-sided in that direction at level . Under reject when (positive sign) or (negative), i.e. . The probability is
With , rejection happens 10 % of the time under true , presented as 5 %. In the detector example, is valid only if “improvement” was chosen beforehand; otherwise the honest is .
Duality between tests and intervals
Confidence intervals and tests are the same theory presented differently. If a 95 % interval for excludes , reject at 5 %; if it contains it, do not reject. Conversely, values not rejected by a 5 % test form a 95 % interval.
Proof
(a) Let be true. Then occurs exactly when rejects true , with probability at most . Hence . (b) Read the same argument backward: .
∎This is test–confidence interval duality. In -value terms: if is the value of the test of , then
The function contains every interval at once, one per level: cut it with a horizontal line at . Two familiar examples follow immediately. Inverting the test gives ; inverting the test (the previous lesson’s pivot) gives .
Inversion has an often-overlooked practical consequence: the interval depends on the test inverted. With successes in Bernoulli trials there are three common two-sided tests of , each producing one of the previous lesson’s proportion intervals:
- Wald standardizes using estimated standard error at , independent of : inversion gives symmetric interval .
- Score standardizes using null standard error : inversion gives the Wilson interval.
- The exact test calculates binomial tails under (doubling the smaller): inversion gives Clopper–Pearson.
With initial values ( of ), the score sweep reproduces Wilson interval [0.181, 0.454], with endpoint differences below one ten-thousandth (the grid has 601 points and endpoints are refined by interpolation). Three observations to check. The three intervals invert distinct tests, not approximations to one test; they agree at large and diverge otherwise. With Wald is the point , because estimated standard error is 0: inverting that test yields zero length exactly when uncertainty is greatest. Wilson ( with ) and Clopper–Pearson () instead say something useful, on the scale of clinicians’ “rule of three” (, the one-sided 95 % upper bound: ). The exact interval is slightly wider than Wilson: the exact value is discrete and never touches , as in the previous figure, and the interval inherits that conservatism.
What a value is not
The American Statistical Association issued a 2016 statement on values (Wasserstein and Lazar) following widespread misuse of the 0.05 threshold. Its six principles, paraphrased:
- A value can indicate how incompatible data are with a specified statistical model.
- It does not measure the probability that the hypothesis is true, or that data arose “by chance alone”.
- Scientific conclusions and decisions should not rest solely on whether crosses a threshold.
- Correct inference requires complete, transparent reporting.
- A value or statistical significance does not measure effect size or result importance.
- By itself, a value is not a good measure of evidence about a model or hypothesis.
The second is most important and can be quantified. A level- test guarantees . The real question is the inverse, , and by Bayes’ theorem and conditional probability it cannot be answered without knowing how often tested hypotheses are true and test power. “Significativo” denotes a significant result.
This is Ioannidis’ (2005) argument for why so many published findings fail to replicate, and explains behavior of teams testing many ideas with a limited data budget. Try the following lab.
With and power 0.8 false positive risk is 36 %; with (one true hypothesis in 100) it is 86 %; with it falls to 5.9 %. Two more facts the figure shows. Power matters. With and power 0.2, not unusual in small studies, risk is 69 %: a low-power test not only misses real effects, but makes a greater fraction of its declarations false. Near the threshold is worse. Among results with and power 0.8, false positive risk is 77 %, because under a well-powered alternative values accumulate near 0, and under the null are uniform: a in that band is only 2.7 times likelier under than , while began nine times less likely.
You need not be Bayesian to draw the practical lesson: contextualize with prior plausibility of the hypothesis and test power; when many hypotheses are tested, error control changes completely, as in multiple comparisons and, for continually inspected data, sequential experiments. For scale: with 20 independent tests of true nulls, the chance of at least one is .
Significance versus relevance: demonstrating no relevant effect
A “nonsignificant” result does not prove no effect, and a “significant” one does not prove the effect matters. With pairs, a 0.6 ms latency difference (standard deviation 12 ms) gives ; it is real and irrelevant. With pairs, a 1.5 ms difference gives , without telling us whether latency worsened by 8 ms. Both share a root: the classical test asks “is the effect nonzero?”, rarely the question of interest.
When seeking to demonstrate absence of a relevant effect (the optimized analyzer is not slower, the quantized model does not lose accuracy, the new provider is equivalent), the structure demands reversing roles: if is presumed and the test protects against rejecting it in error, what you want to demonstrate must be . Fix an equivalence margin (smallest important difference, decided for business or domain reasons before the experiment) and test
Proof
(a) . If , rejecting requires rejecting , with probability at most because that test has level ; similarly for . This is an intersection–union test (Berger, 1982): the null is a union, rejected only when all components are rejected, so no multiplicity correction is needed. (Do not confuse this with Roy’s union–intersection tests, where the null is an intersection and rejecting one component suffices; those do require correction.) (b) Reject if , i.e. , and if , i.e. . Both together mean “the interval fits inside the zone”.
∎Result (b) bridges the previous section and gives a visual rule: to demonstrate equivalence at 5 %, inspect the 90 % interval, not the 95 % interval. (Initially surprising: 5 % is each one-sided test’s level, and each 95 % one-sided interval leaves 5 % in one tail.) The figure shows four combinations of classical and equivalence tests.
Four readings. Little data (, ms): neither significant () nor equivalent (); the 90 % interval leaves the zone. This is inconclusive, not “no difference”. Equivalence (, ): nonsignificant () and equivalent (), the desired claim. Trivial effect (, ): significant and equivalent simultaneously; the difference is nonzero and too small to matter. Worsens (, ): significant and not equivalent; the classical test works here. Two lessons: high does not prove equivalence, and low does not prove relevance. Practically, TOST concludes only if standard error is small relative to , and the figure computes the minimum for each case (34 pairs in the first, with the same and ).
Two technical points. First, TOST has size only in the limit: when is large relative to , actual probability of declaring equivalence at the boundary is well below (the test is conservative and nearly powerless). Second, margin is a substantive, not statistical, choice: justify it using domain reasons and fix it before seeing data. Lakens, Scheel and Isager (2018) call it the smallest effect size of interest. If only one direction matters (the new version is not worse by more than ), a single one-sided test against suffices: noninferiority.
Tests from scratch
Implement one-sample tests with minimal tools: the normal tail via math.erfc and the tail via regularized incomplete beta (the formula for ). Then compare them with scipy.stats.
import math
import numpy as np
from scipy import special, stats
def cola_normal(z):
"""P(Z >= z) para Z ~ N(0, 1)."""
return 0.5 * math.erfc(z / math.sqrt(2.0))
def cola_t(t, gl):
"""P(T >= t) para T ~ t de Student con gl grados de libertad."""
c = 0.5 * special.betainc(gl / 2.0, 0.5, gl / (gl + t * t))
return c if t >= 0 else 1.0 - c
def valor_p(cola, estadistico, alternativa):
"""Valor p a partir de la función de cola; alternativa: 'mayor', 'menor' o 'bilateral'."""
if alternativa == "mayor":
return cola(estadistico)
if alternativa == "menor":
return cola(-estadistico)
return min(1.0, 2.0 * cola(abs(estadistico)))
def contraste_z(x, mu0, sigma, alternativa="bilateral"):
z = math.sqrt(len(x)) * (np.mean(x) - mu0) / sigma
return z, valor_p(cola_normal, z, alternativa)
def contraste_t(x, mu0, alternativa="bilateral"):
n = len(x)
t = math.sqrt(n) * (np.mean(x) - mu0) / np.std(x, ddof=1)
return t, valor_p(lambda u: cola_t(u, n - 1), t, alternativa)
# los datos de la motivación (la celda anterior sigue viva en la sesión)
for alt in ("bilateral", "mayor", "menor"):
t, p = contraste_t(d, 0.0, alt)
ref = stats.ttest_1samp(d, 0.0, alternative={"bilateral": "two-sided", "mayor": "greater", "menor": "less"}[alt])
print(f"{alt:>9}: t = {t:.4f} p propio = {p:.6f} scipy = {ref.pvalue:.6f}")
print("con sigma = 4 conocida:", tuple(round(v, 4) for v in contraste_z(d, 0.0, 4.0)))Each test is a statistic plus the tail of its null distribution. All three values agree with scipy in every digit: the right-sided value is half the two-sided value because is symmetric, and the left-sided value is its complement. Now simulation checks whether tests deliver their promises: type I error rate and -value uniformity under true . Include an incorrect test using sample deviation but a normal rather than quantile (a widespread mistake), and centered exponential data, violating normality.
import matplotlib.pyplot as plt
rng = np.random.default_rng(10)
R = 20000
print(" n t con normales 'z con S' (error) t con datos exponenciales")
for n in (5, 10, 30):
x = rng.normal(0, 1, (R, n)) # H0 cierta: media 0
t = np.sqrt(n) * x.mean(1) / x.std(1, ddof=1)
p_t = 2 * stats.t.sf(np.abs(t), n - 1)
p_z = 2 * stats.norm.sf(np.abs(t))
e = rng.exponential(1.0, (R, n)) - 1.0 # H0 cierta: media 0, asimétrica
te = np.sqrt(n) * e.mean(1) / e.std(1, ddof=1)
p_e = 2 * stats.t.sf(np.abs(te), n - 1)
print(f"{n:>4} {np.mean(p_t <= .05):>14.4f} {np.mean(p_z <= .05):>17.4f} {np.mean(p_e <= .05):>25.4f}")
if n == 10:
p_t10, p_z10 = p_t, p_z
fig, ax = plt.subplots(1, 2, figsize=(9, 3.2), sharey=True)
ax[0].hist(p_t10, bins=20, range=(0, 1), density=True)
ax[0].set_title("t correcto, n = 10")
ax[1].hist(p_z10, bins=20, range=(0, 1), density=True, color="C3")
ax[1].set_title("'z con S', n = 10")
for a in ax:
a.axhline(1, color="gray", ls="--")
a.set_xlabel("valor p")
plt.show()The correct test rejects 5 % of the time for any and its histogram is flat. Using with a normal quantile inflates error: 11.9 % at and 8.1 % at , with too many small histogram values. Even the correct test on skewed data has actual size 9.8 % at : the null assumes normality, and approaches nominal slowly as grows. A test’s guarantee is only as good as its null distribution.
Finally, duality. Instead of , find endpoints of the region the test does not reject by solving with a root method.
from scipy.optimize import brentq
n, xbar, s = len(d), d.mean(), d.std(ddof=1)
def p_bilateral(mu0):
return valor_p(lambda u: cola_t(u, n - 1), np.sqrt(n) * (xbar - mu0) / s, "bilateral")
alfa = 0.05
inf = brentq(lambda m: p_bilateral(m) - alfa, xbar - 10 * s, xbar)
sup = brentq(lambda m: p_bilateral(m) - alfa, xbar, xbar + 10 * s)
tcrit = stats.t.ppf(1 - alfa / 2, n - 1)
print(f"intervalo por inversión: [{inf:.6f}, {sup:.6f}]")
print(f"fórmula xbar ± t s/√n: [{xbar - tcrit * s / np.sqrt(n):.6f}, {xbar + tcrit * s / np.sqrt(n):.6f}]")
rejilla = np.linspace(xbar - 3 * s, xbar + 3 * s, 2001)
no_rech = rejilla[[p_bilateral(m) > alfa for m in rejilla]]
print(f"rejilla de 2001 valores: no se rechazan los de [{no_rech.min():.3f}, {no_rech.max():.3f}]")
print(f"¿se rechaza mu0 = 0 al 5 %? p = {p_bilateral(0.0):.4f} -> 0 {'está fuera' if p_bilateral(0.0) <= alfa else 'está dentro'} del intervalo")The endpoints obtained as -value roots agree with the interval formula to all digits, and the grid stepping by 0.011 in finds them to that precision. This numerically demonstrates duality: the closed-form interval solves for the test. Since is inside , the two-sided 5 % test does not reject , consistent with .
TOST: demonstrating an optimization does not worsen latency
Second lab. We optimized the analyzer and want to show its latency differs from the original by no more than ms. Measure two independent groups and compare classical test and TOST on the same data. Data have true difference 0.4 ms and standard deviation 6 ms.
def tost_ind(x1, x2, bajo, alto):
"""TOST con dos muestras independientes y varianza común.
Devuelve (p_tost, p1, p2, diferencia, error estándar, grados de libertad)."""
n1, n2 = len(x1), len(x2)
gl = n1 + n2 - 2
dif = x1.mean() - x2.mean()
sp2 = ((n1 - 1) * x1.var(ddof=1) + (n2 - 1) * x2.var(ddof=1)) / gl
se = np.sqrt(sp2 * (1 / n1 + 1 / n2))
p1 = cola_t((dif - bajo) / se, gl) # H01: dif <= bajo
p2 = cola_t((alto - dif) / se, gl) # H02: dif >= alto
return max(p1, p2), p1, p2, dif, se, gl
def datos(n, semilla, dif=0.4, sd=6.0):
r = np.random.default_rng(semilla)
return r.normal(100 + dif, sd, n), r.normal(100, sd, n)
print(" n por grupo diferencia p clásico p TOST ¿equivalentes (margen ±3 ms)?")
for n, semilla in [(8, 7), (80, 5), (20000, 3)]:
a, b = datos(n, semilla)
p_clasico = stats.ttest_ind(a, b).pvalue
p_tost = tost_ind(a, b, -3.0, 3.0)[0]
print(f"{n:>11} {a.mean() - b.mean():>10.3f} {p_clasico:>9.4g} {p_tost:>6.4f} {'sí' if p_tost <= 0.05 else 'no demostrado'}")
# la equivalencia es el intervalo del 90 %: comprobación para n = 80
a, b = datos(80, 5)
p, p1, p2, dif, se, gl = tost_ind(a, b, -3.0, 3.0)
tc = stats.t.ppf(0.95, gl)
print(f"\nn = 80: IC 90 % = [{dif - tc * se:.3f}, {dif + tc * se:.3f}] dentro de (-3, 3): {-3 < dif - tc * se and dif + tc * se < 3}; p_TOST = {p:.4f}")Look at the first two rows. With 8 observations per group the difference is tiny and classical huge, but TOST cannot demonstrate equivalence: the interval is too wide to fit in . With 80 per group classical remains high and equivalence is now demonstrated (). The third row is the reverse: 20 000 per group detect a real difference of a few tenths of a millisecond (significant) and demonstrate it is irrelevant (equivalent). High alone cannot distinguish the first two rows.
We still need to check level. If the true difference lies exactly on the boundary (), TOST must declare equivalence with probability at most , and far below it when is large relative to .
from statsmodels.stats.weightstats import ttost_ind
def tasa_tost(n, sd, dif_real, R=4000, semilla=0):
r = np.random.default_rng(semilla)
a = r.normal(dif_real, sd, (R, n))
b = r.normal(0.0, sd, (R, n))
gl = 2 * n - 2
sp2 = (a.var(1, ddof=1) + b.var(1, ddof=1)) / 2
se = np.sqrt(sp2 * 2 / n)
dif = a.mean(1) - b.mean(1)
p = np.maximum(stats.t.sf((dif + 3) / se, gl), stats.t.sf((3 - dif) / se, gl))
return np.mean(p <= 0.05)
print("tasa de equivalencia declarada con diferencia real = 3 ms (frontera, H0 cierta):")
for n, sd in [(30, 3.0), (30, 6.0), (30, 12.0), (2000, 6.0)]:
print(f" n = {n:>4} por grupo, sd = {sd}: {tasa_tost(n, sd, 3.0):.4f}")
a, b = datos(80, 5)
sm = ttost_ind(a, b, -3.0, 3.0)
mio = tost_ind(a, b, -3.0, 3.0)
print(f"\nstatsmodels: p_TOST = {sm[0]:.6f} (p1 = {sm[1][1]:.6f}, p2 = {sm[2][1]:.2e})")
print(f"desde cero: p_TOST = {mio[0]:.6f} (p1 = {mio[1]:.6f}, p2 = {mio[2]:.2e})")With true difference at the boundary, is true and the rate of declared equivalence must not exceed 5 %. With small standard error relative to the rate approaches 5 % (0.0535 with ms and 0.0493 with ms, both within Monte Carlo error of about ); with and 30 observations per group it falls to 3.9 %, and with ( ms, on the order of ) it is exactly 0: the 90 % interval is wider than and cannot fit inside . The test remains level , but has no power. statsmodels agrees with our implementation.
Using libraries: scipy.stats and statsmodels
In practice nobody implements the test. What matters is knowing what choices each function hides. An instructive case is the exact binomial test’s two-sided value, because an asymmetric distribution has no unique definition of “both tails”.
from scipy.stats import binomtest, binom
from statsmodels.stats.proportion import proportion_confint
def p_duplicado(x, n, p0):
"""Duplica la cola más pequeña: la definición cuya inversión da Clopper-Pearson."""
return min(1.0, 2 * min(binom.cdf(x, n, p0), binom.sf(x - 1, n, p0)))
print(" x n p0 scipy (minlike) duplicando la cola")
for x, n, p0 in [(3, 20, 0.4), (2, 20, 0.3), (14, 40, 0.3), (9, 12, 0.5)]:
print(f"{x:>4} {n:>3} {p0:>5} {binomtest(x, n, p0).pvalue:>15.4f} {p_duplicado(x, n, p0):>17.4f}")
bt = binomtest(12, 40, 0.5)
print("\nIC 95 % de 12 éxitos en 40 ensayos:")
print(" scipy exact :", np.round(tuple(bt.proportion_ci(0.95, method="exact")), 4))
print(" statsmodels 'beta' :", np.round(proportion_confint(12, 40, 0.05, method="beta"), 4), "(Clopper-Pearson)")
print(" scipy wilson :", np.round(tuple(bt.proportion_ci(0.95, method="wilson")), 4))
print(" statsmodels 'normal' :", np.round(proportion_confint(12, 40, 0.05, method="normal"), 4), "(Wald)")scipy.stats.binomtest computes the two-sided value by summing probabilities of outcomes no more likely than observed (minimum-likelihood criterion), unlike doubling the smaller tail. At , , the values are 0.0224 and 0.0319, and the 3 % decision changes with definition. Its exact interval (method="exact") is Clopper–Pearson, the inversion of the doubled-tail version (hence agreement with proportion_confint(method="beta")), not minimum likelihood. A summary of library functions:
| Task | scipy.stats | statsmodels |
|---|---|---|
| One-sample , one- or two-sided | ttest_1samp(x, mu0, alternative=...) | DescrStatsW(x).ttest_mean(mu0, alternative=...) |
| Two-sample | ttest_ind(a, b, equal_var=...) | ttest_ind in stats.weightstats |
| Proportion test and CI | binomtest(k, n, p0).proportion_ci(method=...) | proportion_confint(k, n, method=...) |
| Equivalence | no direct function | ttost_ind, ttost_paired |
Common mistakes
Exercises
Step 1 of 4. How do you express in terms of and ?
More than one answer may be correct.
intervalo_invertido(x, n, alfa) to return the level- confidence interval for a proportion obtained by inverting the two-sided exact test (doubling the smaller tail, already implemented in pvalor_exacto): the set of with . Do not use the beta formula: find endpoints by bisection on the value. Then verify agreement with Clopper–Pearson, beta.ppf(alfa/2, x, n - x + 1) and beta.ppf(1 - alfa/2, x + 1, n - x).import numpy as np
from scipy.stats import binom
def pvalor_exacto(x, n, p0):
"""P-valor bilateral exacto de H0: p = p0, duplicando la cola más pequeña (máximo 1)."""
return min(1.0, 2 * min(binom.cdf(x, n, p0), binom.sf(x - 1, n, p0)))
def intervalo_invertido(x, n, alfa=0.05, tol=1e-10):
"""Devuelve (inferior, superior): los p0 en [0, 1] que el test NO rechaza al nivel alfa."""
# tu código: bisección en [0, x/n] para el extremo inferior y en [x/n, 1] para el superior
return 0.0, 1.0