Skip to content

tea_tasting.metrics.proportion #

Metrics for the analysis of proportions.

Proportion(column, *, method='auto', alternative=None, correction=None, equal_var=True) #

Bases: MetricBaseAggregated[ProportionResult]

Metric for the analysis of proportions.

Parameters:

Name Type Description Default
column str

Metric column name. Column values should be 0 or 1.

required
method Literal['auto', 'barnard', 'boschloo', 'fisher', 'log-likelihood', 'norm', 'pearson']

Statistical test used for calculation of p-value:

  • "auto": Barnard's exact test if the total number of observations is < 1000; or normal approximation otherwise.
  • "barnard": Barnard's exact test using the Wald statistic.
  • "boschloo": Boschloo's exact test. Also known as Barnard's exact test with p-value of Fisher's exact test as a statistic.
  • "fisher": Fisher's exact test.
  • "log-likelihood": G-test.
  • "norm": Normal approximation of the binomial distribution. Also known as two-sample proportion Z-test.
  • "pearson": Pearson's chi-squared test.
'auto'
alternative Literal['two-sided', 'greater', 'less'] | None

Alternative hypothesis:

  • "two-sided": the means are unequal,
  • "greater": the mean in the treatment variant is greater than the mean in the control variant,
  • "less": the mean in the treatment variant is less than the mean in the control variant.

G-test and Pearson's chi-squared test are always two-sided.

None
correction bool | None

If True, add continuity correction. Only for approximate methods: normal, G-test, and Pearson's chi-squared test. Defaults to the global config value (False).

None
equal_var bool

Defines whether equal variance is assumed. If True, pooled variance is used for the calculation of the standard error of the difference between two proportions. Only for normal approximation and for Barnard's exact test (in the Wald statistic). Default is True. Global config is ignored as pooled variance is optimal for proportion tests.

True
Parameter defaults

Defaults for parameters alternative and correction can be changed using the config_context and set_config functions. See the Global configuration reference for details.

References

Examples:

>>> import pyarrow as pa
>>> import pyarrow.compute as pc
>>> import tea_tasting as tt

>>> data = tt.make_users_data(seed=42, n_users=1000)
>>> data = data.append_column(
...     "has_order",
...     pc.greater(data["orders"], 0).cast(pa.int64()),
... )
>>> data
pyarrow.Table
user: int64
variant: int64
sessions: int64
orders: int64
revenue: double
has_order: int64
----
user: [[0,1,2,3,4,...,995,996,997,998,999]]
variant: [[1,0,1,1,0,...,0,1,0,1,0]]
sessions: [[1,2,1,2,2,...,1,2,4,2,2]]
orders: [[0,0,0,2,1,...,1,1,0,0,2]]
revenue: [[0,0,0,16.57,8.87,...,8.54,11.78,0,0,18.69]]
has_order: [[0,0,0,1,1,...,1,1,0,0,1]]
>>> experiment = tt.Experiment(
...     prop_users_with_orders=tt.Proportion("has_order"),
... )
>>> experiment.analyze(data)
                metric control treatment rel_effect_size rel_effect_size_ci pvalue
prop_users_with_orders   0.300     0.356             19%             [-, -] 0.0596

With specific statistical test:

>>> experiment = tt.Experiment(
...     prop_users_with_orders=tt.Proportion(
...         "has_order",
...         method="barnard",
...         equal_var=False,
...     ),
... )
>>> experiment.analyze(data)
                metric control treatment rel_effect_size rel_effect_size_ci pvalue
prop_users_with_orders   0.300     0.356             19%             [-, -] 0.0620
Source code in src/tea_tasting/metrics/proportion.py
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
def __init__(
    self,
    column: str,
    *,
    method: Literal[
        "auto",
        "barnard",
        "boschloo",
        "fisher",
        "log-likelihood",
        "norm",
        "pearson",
    ] = "auto",
    alternative: Literal["two-sided", "greater", "less"] | None = None,
    correction: bool | None = None,
    equal_var: bool = True,
) -> None:
    """Metric for the analysis of proportions.

    Args:
        column: Metric column name. Column values should be 0 or 1.
        method: Statistical test used for calculation of p-value:

            - `"auto"`: Barnard's exact test if the total number
                of observations is < 1000; or normal approximation otherwise.
            - `"barnard"`: Barnard's exact test using the Wald statistic.
            - `"boschloo"`: Boschloo's exact test.
                Also known as Barnard's exact test with
                p-value of Fisher's exact test as a statistic.
            - `"fisher"`: Fisher's exact test.
            - `"log-likelihood"`: G-test.
            - `"norm"`: Normal approximation of the binomial distribution.
                Also known as two-sample proportion Z-test.
            - `"pearson"`: Pearson's chi-squared test.

        alternative: Alternative hypothesis:

            - `"two-sided"`: the means are unequal,
            - `"greater"`: the mean in the treatment variant is greater than
                the mean in the control variant,
            - `"less"`: the mean in the treatment variant is less than the mean
                in the control variant.

            G-test and Pearson's chi-squared test are always two-sided.
        correction: If `True`, add continuity correction. Only for
            approximate methods: normal, G-test, and Pearson's chi-squared test.
            Defaults to the global config value (`False`).
        equal_var: Defines whether equal variance is assumed. If `True`,
            pooled variance is used for the calculation of the standard error
            of the difference between two proportions. Only for normal approximation
            and for Barnard's exact test (in the Wald statistic).
            Default is `True`. Global config is ignored as pooled variance is
            optimal for proportion tests.

    Parameter defaults:
        Defaults for parameters `alternative` and `correction`
        can be changed using the `config_context` and `set_config` functions.
        See the [Global configuration](https://tea-tasting.e10v.me/api/config/)
        reference for details.

    References:
        - [Barnard's test](https://en.wikipedia.org/wiki/Barnard%27s_test).
        - [Boschloo's test](https://en.wikipedia.org/wiki/Boschloo%27s_test).
        - [Fisher's exact test](https://en.wikipedia.org/wiki/Fisher%27s_exact_test).
        - [G-test](https://en.wikipedia.org/wiki/G-test).
        - [Two-proportion Z-test](https://en.wikipedia.org/wiki/Two-proportion_Z-test).
        - [Pearson's chi-squared test](https://en.wikipedia.org/wiki/Pearson%27s_chi-squared_test).

    Examples:
        ```pycon
        >>> import pyarrow as pa
        >>> import pyarrow.compute as pc
        >>> import tea_tasting as tt

        >>> data = tt.make_users_data(seed=42, n_users=1000)
        >>> data = data.append_column(
        ...     "has_order",
        ...     pc.greater(data["orders"], 0).cast(pa.int64()),
        ... )
        >>> data
        pyarrow.Table
        user: int64
        variant: int64
        sessions: int64
        orders: int64
        revenue: double
        has_order: int64
        ----
        user: [[0,1,2,3,4,...,995,996,997,998,999]]
        variant: [[1,0,1,1,0,...,0,1,0,1,0]]
        sessions: [[1,2,1,2,2,...,1,2,4,2,2]]
        orders: [[0,0,0,2,1,...,1,1,0,0,2]]
        revenue: [[0,0,0,16.57,8.87,...,8.54,11.78,0,0,18.69]]
        has_order: [[0,0,0,1,1,...,1,1,0,0,1]]
        >>> experiment = tt.Experiment(
        ...     prop_users_with_orders=tt.Proportion("has_order"),
        ... )
        >>> experiment.analyze(data)
                        metric control treatment rel_effect_size rel_effect_size_ci pvalue
        prop_users_with_orders   0.300     0.356             19%             [-, -] 0.0596

        ```

        With specific statistical test:

        ```pycon
        >>> experiment = tt.Experiment(
        ...     prop_users_with_orders=tt.Proportion(
        ...         "has_order",
        ...         method="barnard",
        ...         equal_var=False,
        ...     ),
        ... )
        >>> experiment.analyze(data)
                        metric control treatment rel_effect_size rel_effect_size_ci pvalue
        prop_users_with_orders   0.300     0.356             19%             [-, -] 0.0620

        ```
    """  # noqa: E501
    self.column = tea_tasting.utils.check_scalar(column, "column", typ=str)
    self.method = tea_tasting.utils.check_scalar(method, "method", typ=str, in_={
        "auto",
        "barnard",
        "boschloo",
        "fisher",
        "log-likelihood",
        "norm",
        "pearson",
    })
    self.alternative: Literal["two-sided", "greater", "less"] = (
        tea_tasting.utils.auto_check(alternative, "alternative")
        if alternative is not None
        else tea_tasting.config.get_config("alternative")
    )
    if self.alternative != "two-sided" and method in {"log-likelihood", "pearson"}:
        raise ValueError(
            f"The {method} method supports only two-sided alternative hypothesis.")
    self.correction = (
        tea_tasting.utils.auto_check(correction, "correction")
        if correction is not None
        else tea_tasting.config.get_config("correction")
    )
    self.equal_var = tea_tasting.utils.auto_check(equal_var, "equal_var")

aggr_cols property #

Columns to be aggregated for a metric analysis.

analyze(data, control, treatment, variant=None) #

Analyze a metric in an experiment.

Parameters:

Name Type Description Default
data IntoFrame | Table | dict[object, Aggregates]

Experimental data.

required
control object

Control variant.

required
treatment object

Treatment variant.

required
variant str | None

Variant column name.

None

Returns:

Type Description
R

Analysis result.

Source code in src/tea_tasting/metrics/base.py
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
def analyze(
    self,
    data: narwhals.typing.IntoFrame | ibis.expr.types.Table | dict[
        object, tea_tasting.aggr.Aggregates],
    control: object,
    treatment: object,
    variant: str | None = None,
) -> R:
    """Analyze a metric in an experiment.

    Args:
        data: Experimental data.
        control: Control variant.
        treatment: Treatment variant.
        variant: Variant column name.

    Returns:
        Analysis result.
    """
    tea_tasting.utils.check_scalar(variant, "variant", typ=str | None)
    aggr = aggregate_by_variants(
        data,
        aggr_cols=self.aggr_cols,
        variant=variant,
    )
    return self.analyze_aggregates(
        control=aggr[control],
        treatment=aggr[treatment],
    )

analyze_aggregates(control, treatment) #

Analyze a metric in an experiment using aggregated statistics.

Parameters:

Name Type Description Default
control Aggregates

Control data.

required
treatment Aggregates

Treatment data.

required

Returns:

Type Description
ProportionResult

Analysis result.

Source code in src/tea_tasting/metrics/proportion.py
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
def analyze_aggregates(
    self,
    control: tea_tasting.aggr.Aggregates,
    treatment: tea_tasting.aggr.Aggregates,
) -> ProportionResult:
    """Analyze a metric in an experiment using aggregated statistics.

    Args:
        control: Control data.
        treatment: Treatment data.

    Returns:
        Analysis result.
    """
    control = control.with_zero_div()
    treatment = treatment.with_zero_div()
    p_contr = control.mean(self.column)
    p_treat = treatment.mean(self.column)
    n_contr = control.count()
    n_treat = treatment.count()

    method = self.method
    if method == "auto":
        method = "barnard" if n_contr + n_treat < _MAX_EXACT_THRESHOLD else "norm"

    if method != "norm":
        data = np.empty(shape=(2, 2), dtype=np.int64)
        data[0, 0] = round(n_treat * p_treat)
        data[0, 1] = round(n_contr * p_contr)
        data[1, 0] = n_treat - data[0, 0]
        data[1, 1] = n_contr - data[0, 1]

    if method == "barnard":
        pvalue = scipy.stats.barnard_exact(
            data,  # type: ignore
            alternative=self.alternative,
            pooled=self.equal_var,
        ).pvalue
    elif method == "boschloo":
        pvalue = scipy.stats.boschloo_exact(
            data, alternative=self.alternative).pvalue  # type: ignore
    elif method == "fisher":
        pvalue = scipy.stats.fisher_exact(data, alternative=self.alternative).pvalue  # type: ignore
    elif method in {"log-likelihood", "pearson"}:
        if np.any(data.sum(axis=0) == 0) or np.any(data.sum(axis=1) == 0):  # type: ignore
            pvalue = float("nan")
        else:
            pvalue = scipy.stats.chi2_contingency(
                data,  # type: ignore
                correction=self.correction,
                lambda_=self.method,
            ).pvalue  # type: ignore
    else:  # norm
        pvalue = _2sample_proportion_ztest(
            p_contr=p_contr,
            p_treat=p_treat,
            n_contr=n_contr,
            n_treat=n_treat,
            alternative=self.alternative,
            correction=self.correction,
            equal_var=self.equal_var,
        )

    return ProportionResult(
        control=p_contr,
        treatment=p_treat,
        effect_size=p_treat - p_contr,
        rel_effect_size=p_treat/p_contr - 1,
        pvalue=pvalue,
    )

ProportionResult #

Bases: NamedTuple

Result of the analysis of proportions.

Attributes:

Name Type Description
control float

Proportion in control.

treatment float

Proportion in treatment.

effect_size float

Absolute effect size. Difference between the two proportions.

rel_effect_size float

Relative effect size. Difference between the two proportions, divided by the control proportion.

pvalue float

P-value.

SampleRatio(ratio=1, *, method='auto', correction=None) #

Bases: MetricBaseAggregated[SampleRatioResult]

Metric for sample ratio mismatch check.

Parameters:

Name Type Description Default
ratio float | int | dict[object, float | int]

Expected ratio of the number of observations in the treatment relative to the control.

1
method Literal['auto', 'binom', 'norm']

Statistical test used for calculation of p-value:

  • "auto": Exact binomial test if the total number of observations is < 1000; or normal approximation otherwise.
  • "binom": Exact binomial test.
  • "norm": Normal approximation of the binomial distribution.
'auto'
correction bool | None

If True, add continuity correction. Only for normal approximation. Defaults to the global config value (False).

None

Examples:

>>> import tea_tasting as tt

>>> experiment = tt.Experiment(
...     sample_ratio=tt.SampleRatio(),
... )
>>> data = tt.make_users_data(seed=42)
>>> result = experiment.analyze(data)
>>> result.with_keys(("metric", "control", "treatment", "pvalue"))
      metric control treatment pvalue
sample_ratio    2023      1977  0.467

Different expected ratio:

>>> experiment = tt.Experiment(
...     sample_ratio=tt.SampleRatio(0.5),
... )
>>> data = tt.make_users_data(seed=42)
>>> result = experiment.analyze(data)
>>> result.with_keys(("metric", "control", "treatment", "pvalue"))
      metric control treatment    pvalue
sample_ratio    2023      1977 2.27e-103
Source code in src/tea_tasting/metrics/proportion.py
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
def __init__(
    self,
    ratio: float | int | dict[object, float | int] = 1,
    *,
    method: Literal["auto", "binom", "norm"] = "auto",
    correction: bool | None = None,
) -> None:
    """Metric for sample ratio mismatch check.

    Args:
        ratio: Expected ratio of the number of observations in the treatment
            relative to the control.
        method: Statistical test used for calculation of p-value:

            - `"auto"`: Exact binomial test if the total number
                of observations is < 1000; or normal approximation otherwise.
            - `"binom"`: Exact binomial test.
            - `"norm"`: Normal approximation of the binomial distribution.

        correction: If `True`, add continuity correction.
            Only for normal approximation.
            Defaults to the global config value (`False`).

    Examples:
        ```pycon
        >>> import tea_tasting as tt

        >>> experiment = tt.Experiment(
        ...     sample_ratio=tt.SampleRatio(),
        ... )
        >>> data = tt.make_users_data(seed=42)
        >>> result = experiment.analyze(data)
        >>> result.with_keys(("metric", "control", "treatment", "pvalue"))
              metric control treatment pvalue
        sample_ratio    2023      1977  0.467

        ```

        Different expected ratio:

        ```pycon
        >>> experiment = tt.Experiment(
        ...     sample_ratio=tt.SampleRatio(0.5),
        ... )
        >>> data = tt.make_users_data(seed=42)
        >>> result = experiment.analyze(data)
        >>> result.with_keys(("metric", "control", "treatment", "pvalue"))
              metric control treatment    pvalue
        sample_ratio    2023      1977 2.27e-103

        ```
    """
    if isinstance(ratio, dict):
        for val in ratio.values():
            tea_tasting.utils.auto_check(val, "ratio")
    else:
        tea_tasting.utils.auto_check(ratio, "ratio")
    self.ratio = ratio

    self.method = tea_tasting.utils.check_scalar(
        method, "method", typ=str, in_={"auto", "binom", "norm"})
    self.correction = (
        tea_tasting.utils.auto_check(correction, "correction")
        if correction is not None
        else tea_tasting.config.get_config("correction")
    )

aggr_cols property #

Columns to be aggregated for a metric analysis.

analyze(data, control, treatment, variant=None) #

Perform a sample ratio mismatch check.

Parameters:

Name Type Description Default
data IntoFrame | Table | dict[object, Aggregates]

Experimental data.

required
control object

Control variant.

required
treatment object

Treatment variant.

required
variant str | None

Variant column name.

None

Returns:

Type Description
SampleRatioResult

Analysis result.

Source code in src/tea_tasting/metrics/proportion.py
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
def analyze(
    self,
    data: narwhals.typing.IntoFrame | ibis.expr.types.Table | dict[
        object, tea_tasting.aggr.Aggregates],
    control: object,
    treatment: object,
    variant: str | None = None,
) -> SampleRatioResult:
    """Perform a sample ratio mismatch check.

    Args:
        data: Experimental data.
        control: Control variant.
        treatment: Treatment variant.
        variant: Variant column name.

    Returns:
        Analysis result.
    """
    tea_tasting.utils.check_scalar(variant, "variant", typ=str | None)
    aggr = tea_tasting.metrics.aggregate_by_variants(
        data,
        aggr_cols=self.aggr_cols,
        variant=variant,
    )

    k = aggr[treatment].count()
    n = k + aggr[control].count()

    r = (
        self.ratio
        if isinstance(self.ratio, float | int)
        else self.ratio[treatment] / self.ratio[control]
    )
    p = r / (1 + r)

    if (
        self.method == "binom" or
        (self.method == "auto" and n < _MAX_EXACT_THRESHOLD)
    ):
        pvalue = scipy.stats.binomtest(k=int(k), n=int(n), p=p).pvalue
    else:  # norm
        d = abs(k - n*p)
        if self.correction and d > 0:
            d = max(d - 0.5, 0)
        z = d / math.sqrt(n * p * (1 - p))
        pvalue = 2 * scipy.stats.norm.sf(z)

    return SampleRatioResult(
        control=n - k,
        treatment=k,
        pvalue=pvalue,  # type: ignore
    )

analyze_aggregates(control, treatment) #

Stub method for compatibility with the base class.

Source code in src/tea_tasting/metrics/proportion.py
453
454
455
456
457
458
459
def analyze_aggregates(
    self,
    control: tea_tasting.aggr.Aggregates,
    treatment: tea_tasting.aggr.Aggregates,
) -> SampleRatioResult:
    """Stub method for compatibility with the base class."""
    raise NotImplementedError

SampleRatioResult #

Bases: NamedTuple

Result of the sample ratio mismatch check.

Attributes:

Name Type Description
control float

Number of observations in control.

treatment float

Number of observations in treatment.

pvalue float

P-value.