packages

stats

On this page

Statistics on core's Array and List.

stats covers what a first statistics course does and a good part of what comes after: summaries, probability distributions, random samples, hypothesis tests, regression and the bootstrap. Each function takes any sequence of numbers (a Vector<f64>, a List, a fixed array, a range), and the results are plain structs whose fields you read by name.

#Tutorial

#Summaries

mean, median, var, std, quantile and the rest take the data and return a number. Descriptive statistics never throw: an empty input gives NaN, as in NumPy. stats::nan:: has the same functions skipping NaN values.

nabi
let x = [5.1, 4.9, 5.6, 5.8, 6.0, 5.4, 5.2, 5.7];
println(f"mean {stats::mean(x):.4}, median {stats::median(x):.2}");
println(f"var {stats::var(x, ddof: 1):.4}, std {stats::std(x, ddof: 1):.4}");
println(f"90th percentile {(try stats::quantile(x, 0.9)):.3}");
println(f"skew {stats::skew(x):.3}");

let gaps = [1.0, f64::NAN, 3.0];
println(f"{stats::mean(gaps)} {stats::nan::mean(gaps)}");
text
mean 5.4625, median 5.50
var 0.1427, std 0.3777
90th percentile 5.860
skew -0.097
NaN 2

quantile interpolates as NumPy does by default; the method: argument picks any of the Hyndman and Fan definitions when a field expects another.

#Distributions

A distribution is a value: Normal::new(100.0, 15.0) is the normal with mean 100 and standard deviation 15. Continuous distributions have pdf, cdf, sf (one minus the cdf, accurate in the tail), ppf (the inverse cdf) and interval; discrete ones have pmf instead of pdf.

nabi
use stats::{Binomial, Continuous, Discrete, Normal};

let iq = try Normal::new(100.0, 15.0);
println(f"P(IQ > 130) = {iq.sf:.4}");
println(f"middle 95%: {iq.interval}");
println(f"97.5th percentile {iq.ppf:.2}");

let coin = try Binomial::new(10, 0.5);
println(f"P(7 heads of 10) = {coin.pmf(7):.4}, P(at most 7) = {coin.cdf(7):.4}");
text
P(IQ > 130) = 0.0228
middle 95%: [70.6005402318992, 129.3994597681008]
97.5th percentile 129.40
P(7 heads of 10) = 0.1172, P(at most 7) = 0.9453

#Random samples

A Sampler is a seeded random number generator: the same seed gives the same draws on every machine, which makes a simulation repeatable. d.samples(ref g, n) draws n values from d.

nabi
use stats::{Continuous, Distribution, Normal, Sampler};

let g = Sampler::seed(7);
let d = try Normal::new(10.0, 2.0);
let xs = d.samples(ref g, 10000);
println(f"{xs.len()} draws: mean {stats::mean(xs):.2}, std {stats::std(xs, ddof: 1):.2}");

let fitted = try Normal::fit(xs);
println(f"fitted mean {fitted.mean():.2}");
text
10000 draws: mean 10.00, std 1.99
fitted mean 10.00

fit estimates a distribution's parameters by maximum likelihood; most distributions in the package have one.

#Hypothesis tests

A test returns its statistic and p-value. The t-tests also return the estimate and its standard error, so the confidence interval is one more call (ci). Here a drug trial: did the treated group's blood pressure fall more than the control group's?

nabi
let control = [-2.1, 0.5, -1.0, 1.3, -0.4, 0.8, -1.7, 0.2, -0.6, 1.1];
let treated = [-6.3, -4.1, -7.5, -2.9, -5.2, -3.8, -6.9, -4.4, -5.8, -3.1];

let t = try stats::ttest_ind(treated, control);
println(f"difference {t.estimate:.2} mmHg, 95% interval {t.ci}");
println(f"p = {t.pvalue:.2e}, significant at 1%: {t.result().rejects}");

// Are the treated values plausibly normal? Shapiro-Wilk.
let sw = try stats::shapiro(treated);
println(f"Shapiro-Wilk p = {sw.pvalue:.3}");

// The same question without assuming normality.
let u = try stats::mannwhitneyu(treated, control);
println(f"Mann-Whitney p = {u.pvalue:.2e}");
text
difference -4.81 mmHg, 95% interval [-6.131505142918329, -3.48849485708167]
p = 7.45e-7, significant at 1%: true
Shapiro-Wilk p = 0.696
Mann-Whitney p = 1.83e-4

The package also has paired and one-sample t-tests, chi-squared tests of fit and of contingency tables, Fisher's exact test, Kolmogorov-Smirnov, Wilcoxon, one-way ANOVA (f_oneway) and the correlation tests. Each takes alternative: for a one-sided test.

#Regression

stats::ols fits y = b0 + b1 x1 + ... by least squares and reports what a regression table does: coefficients, standard errors, t statistics, p-values, R². Each row of x is one observation, each column one predictor; the intercept is added for you.

nabi
use core::array::{Matrix, Vector};

// Fuel use (l/100 km) against mass (tonnes) and engine size (litres).
let x: Matrix<f64> = [[1.1, 1.2], [1.3, 1.4], [1.4, 1.6], [1.5, 2.0], [1.7, 2.0], [1.8, 2.5], [2.0, 3.0], [2.2, 3.0]];
let y: Vector<f64> = [5.2, 5.9, 6.3, 7.1, 7.4, 8.3, 9.2, 9.6];

let fit = try stats::ols(x, y);
for (k, name) in ["intercept", "mass", "engine"].enumerate() {
    println(f"{name:>9}: {fit.coef[k]:>6.3} (se {fit.se[k]:.3}, p {fit.p[k]:.3})");
}
println(f"R^2 {fit.r2:.4}");

let next: Matrix<f64> = [[1.6, 1.8]];
println(f"predicted for a 1.6 t car with a 1.8 l engine: {(try fit.predict(next))[0]:.2}");
text
intercept:  1.684 (se 0.155, p 0.000)
     mass:  1.807 (se 0.259, p 0.001)
   engine:  1.319 (se 0.138, p 0.000)
R^2 0.9991
predicted for a 1.6 t car with a 1.8 l engine: 6.95

stats::logistic fits a logistic regression for a yes/no outcome, and stats::polyfit a polynomial in one variable.

#The bootstrap

When no formula gives the uncertainty of a statistic, the bootstrap estimates it by recomputing the statistic on many resamples of the data. stats::bootstrap takes the data and the statistic as a function and returns the estimate, its standard error and a confidence interval (BCa by default).

nabi
use core::array::Vector;

let incomes = [21.0, 23.5, 25.0, 26.0, 28.5, 30.0, 31.0, 34.0, 38.0, 45.0, 60.0, 120.0];
let b = try stats::bootstrap(incomes, |v: Vector<f64>| -> f64 { stats::median(v) }, resamples: 2000, seed: 1);
println(f"median {b.estimate}, se {b.se:.2}, 95% interval {b.ci}");
text
median 30.5, se 4.09, 95% interval [25, 38]

#Notation

With the ops feature (on by default) some of this reads like a statistics text: 95pct is the number 0.95, m ± h is an interval, and g ~ d draws from d.

nabi
use stats::{Distribution, Normal, Sampler};

let g = Sampler::seed(42);
let xs = g ~ (try Normal::new(10.0, 2.0)).iid(1000);
let ci = stats::mean(xs) ± 1.96 * stats::sem(xs);
println(f"{ci} contains 10: {10.0 in ci}");
println(95pct);
text
[9.886659540274959, 10.129771738653204] contains 10: true
0.95

#What next

  • Signals and spectra: FFT and filters.
  • The modules below list every distribution, test and option.

Modules

  • axis Statistics along one axis of an array: each lane along axis is reduced to one value, giving an array of one rank less (NumPy's axis= argument).
  • descriptive Descriptive statistics of one set of values: location, spread and shape.
  • dist Probability distributions as types.
  • hypothesis Hypothesis tests.
  • nan NaN-aware statistics: the same as the plain ones on the values that are not NaN (NumPy's nanmean, ...).
  • ops Notation for statistics (feature ops, on by default): g ~ d a draw from distribution d with the Sampler g; with d.iid(n), n draws ("distributed as", level of ==) y ~ x the least-squares fit of y on x with an intercept, as R's lm(y ~ x); a Result, since operators cannot throw m ± h the interval [m - h, m + h] (level of +) 95pct the number 0.95, for confidence levels ~ has a second spelling, ∼ (U+223C TILDE OPERATOR).
  • regress Regression: ordinary and weighted least squares with inference, polynomial fits and logistic regression.
  • special The special functions behind the distributions, from the special package.

Re-exports

descriptive::order::{QuantileMethod, iqr, max, median, min, mode, percentile, quantile, quantiles, range}Source

pub use descriptive::order::{QuantileMethod, iqr, max, median, min, mode, percentile, quantile, quantiles, range}
  • QuantileMethod How a quantile between two order statistics is chosen.
  • iqr The interquartile range q(0.75) - q(0.25) (type 7).
  • max The largest value; NaN when empty or a value is NaN.
  • median The median (the mean of the middle two for an even count); NaN when empty or a value is NaN.
  • min The smallest value; NaN when empty or a value is NaN.
  • mode The most frequent value and its count; the smallest of several equally frequent ones (SciPy's mode).
  • percentile The p-th percentile, 0 <= p <= 100: quantile(x, p / 100).
  • quantile The q-quantile, 0 <= q <= 1, by method (default Linear).
  • quantiles The quantiles at each of qs, by one sort (O(n log n)).
  • range max - min (NumPy's ptp); NaN when empty or a value is NaN.

descriptive::{Summary, describe, kurtosis, mean, moment, sem, skew, std, sum, var, wmean, zscore}Source

pub use descriptive::{Summary, describe, kurtosis, mean, moment, sem, skew, std, sum, var, wmean, zscore}
  • Summary A summary of a set of values: count, mean, spread, quartiles and shape.
  • describe The Summary of the values: one copy and a sort.
  • kurtosis The kurtosis m4 / m2^2, minus 3 by default (fisher: true, the excess kurtosis, 0 for a normal sample in the limit); with bias: false the unbiased estimator G2 of the k-statistics (SciPy's kurtosis).
  • mean The arithmetic mean, by pairwise summation (O(n)); NaN when empty.
  • moment The k-th central moment sum((x - mean)^k) / n (1 gives 0, 2 the population variance); NaN when empty.
  • sem The standard error of the mean, std(x, ddof) / sqrt(n), with ddof = 1 by default (SciPy's sem).
  • skew The skewness m3 / m2^1.5 of the central moments; with bias: false the adjusted Fisher-Pearson coefficient G1 = g1 sqrt(n (n - 1)) / (n - 2) (SciPy's skew).
  • std The standard deviation, sqrt(var(x, ddof)).
  • sum The sum of the values, by pairwise summation (O(n), error O(eps log n) of the sum of magnitudes); 0 when empty.
  • var The variance sum((x - mean)^2) / (n - ddof) (corrected two-pass, Chan, Golub and LeVeque 1983).
  • wmean The weighted mean sum(w x) / sum(w).
  • zscore The z-scores (x - mean) / std(x, ddof) of every element, in the shape of a.

dist::{Bernoulli, Beta, Binomial, Cauchy, ChiSquared, Continuous, Discrete, Distribution, Exponential, FisherF, Gamma, Geometric, Iid, Laplace, LogNormal, Multinomial, MultivariateNormal, NegativeBinomial, Normal, Poisson, StudentT, Uniform, Weibull}Source

pub use dist::{Bernoulli, Beta, Binomial, Cauchy, ChiSquared, Continuous, Discrete, Distribution, Exponential, FisherF, Gamma, Geometric, Iid, Laplace, LogNormal, Multinomial, MultivariateNormal, NegativeBinomial, Normal, Poisson, StudentT, Uniform, Weibull}
  • Bernoulli The Bernoulli distribution: 1 with probability p, else 0.
  • Beta The beta distribution with shapes a, b > 0 on [0, 1].
  • Binomial The binomial distribution: the number of successes in n >= 0 independent trials of probability p.
  • Cauchy The Cauchy (Lorentz) distribution with location x0 and scale gamma > 0: Student's t with one degree of freedom, shifted and scaled.
  • ChiSquared The chi-squared distribution with k > 0 degrees of freedom (Gamma(k / 2, 2)); k need not be an integer.
  • Continuous A distribution on the real line with a density.
  • Discrete A distribution on the integers.
  • Distribution Something to draw random values from.
  • Exponential The exponential distribution with rate lambda > 0 (mean 1 / lambda; SciPy's expon(scale=1/lambda)).
  • FisherF The F distribution with d1, d2 > 0 degrees of freedom: the ratio of two scaled chi-squared variables.
  • Gamma The gamma distribution with shape k > 0 and scale theta > 0 (mean k theta).
  • Geometric The geometric distribution on 1, 2, 3, ...: the number of trials of probability p up to and including the first success (SciPy's geom).
  • Iid n independent copies of d: a draw is d.samples(g, n).
  • Laplace The Laplace distribution with location mu and scale b > 0: density e^(-|x - mu| / b) / (2 b).
  • LogNormal The log-normal distribution: X = e^Y with Y ~ N(mu, sigma^2) (SciPy's lognorm(s=sigma, scale=e^mu)).
  • Multinomial The multinomial distribution: the counts in each of k categories after n independent draws with probabilities p.
  • MultivariateNormal The multivariate normal distribution with mean mu and covariance sigma (symmetric positive definite), through its Cholesky factor sigma = L L^T (linalg): the density by one triangular solve and ln det sigma = 2 sum ln L_ii, a draw as mu + L z.
  • NegativeBinomial The negative binomial distribution: the number of failures before the r-th success in trials of probability p (SciPy's nbinom; r > 0 need not be an integer).
  • Normal The normal (Gaussian) distribution with mean mu and standard deviation sigma > 0.
  • Poisson The Poisson distribution with mean lambda >= 0.
  • StudentT Student's t distribution with nu > 0 degrees of freedom (not necessarily an integer).
  • Uniform The uniform distribution on [a, b], a < b.
  • Weibull The Weibull distribution with shape k > 0 and scale lambda > 0: P(X > x) = e^(-(x / lambda)^k) (SciPy's weibull_min).

hypothesis::{Alternative, Anova, Contingency, TTest, TestResult, chi2_contingency, chisquare, f_oneway, fisher_exact, kendalltau, ks_2samp, kstest, mannwhitneyu, pearsonr, shapiro, spearmanr, ttest_1samp, ttest_ind, ttest_rel, wilcoxon}Source

pub use hypothesis::{Alternative, Anova, Contingency, TTest, TestResult, chi2_contingency, chisquare, f_oneway, fisher_exact, kendalltau, ks_2samp, kstest, mannwhitneyu, pearsonr, shapiro, spearmanr, ttest_1samp, ttest_ind, ttest_rel, wilcoxon}
  • Alternative Which way the alternative hypothesis points.
  • Anova The outcome of a one-way ANOVA: F, its p-value and the two degrees of freedom.
  • Contingency The chi-squared test of independence in a contingency table: its statistic, p-value, degrees of freedom (r - 1)(c - 1) and the expected counts under independence.
  • TTest The outcome of a t-test: the t statistic, its p-value and degrees of freedom, the estimate (a mean or a difference of means) and its standard error, from which ci gives a confidence interval.
  • TestResult The outcome of a test: the statistic, its p-value and, for tests with a t, chi-squared or similar reference distribution, the degrees of freedom.
  • chi2_contingency Pearson's chi-squared test of independence of the rows and columns of a table of counts.
  • chisquare Pearson's goodness-of-fit test of observed counts against expected ones: sum((o - e)^2 / e) on k - 1 - ddof degrees of freedom.
  • f_oneway The one-way ANOVA F-test that k >= 2 groups share one mean (SciPy's f_oneway).
  • fisher_exact Fisher's exact test of independence in a 2 x 2 table [[a, b], [c, d]]: with the margins fixed, a is hypergeometric.
  • kendalltau Kendall's tau-b and the p-value of tau = 0: exact (the distribution of inversions of a random permutation) for up to 33 pairs without ties, else the normal approximation with the tie-corrected variance of Kendall (1970) (SciPy's kendalltau).
  • ks_2samp The two-sample Kolmogorov-Smirnov test that x and y come from one distribution.
  • kstest The one-sample Kolmogorov-Smirnov test of x against the continuous distribution d.
  • mannwhitneyu The Mann-Whitney U test that x and y come from one distribution against a shift (SciPy's mannwhitneyu).
  • pearsonr Pearson's r and the p-value of r = 0 for normal data (the t-test on n - 2 degrees of freedom; SciPy's pearsonr).
  • shapiro The Shapiro-Wilk test that x comes from a normal distribution, 3 <= n <= 5000.
  • spearmanr Spearman's rho and the p-value of rho = 0 by the same t approximation (SciPy's spearmanr).
  • ttest_1samp The one-sample t-test of mean(x) = popmean: t = (mean - popmean) / (s / sqrt(n)) on n - 1 degrees of freedom.
  • ttest_ind The two-sample t-test of equal means.
  • ttest_rel The paired t-test: the one-sample test of the differences x - y against 0.
  • wilcoxon The Wilcoxon signed-rank test that the values x are symmetric about 0, or with y that the differences x - y of paired samples are.

regress::{Logistic, Ols, logistic, ols, polyfit, polyval, wls}Source

pub use regress::{Logistic, Ols, logistic, ols, polyfit, polyval, wls}
  • Logistic A fitted logistic regression P(y = 1 | x) = 1 / (1 + e^-(x b)).
  • Ols A fitted linear model y = X b + e: coefficients, their standard errors, t statistics and p-values, the fit's R^2, the residuals.
  • logistic Logistic regression of 0/1 outcomes y on the columns of x by Newton's method in its IRLS form (McCullagh and Nelder 1989): each step solves X^T W X d = X^T (y - mu) by Cholesky (linalg), from b = 0, until no coefficient moves more than tol (relative) or max_iter steps.
  • ols Ordinary least squares y = X b + e by Householder QR (linalg): coefficients from R b = Q^T y, covariance sigma^2 R^-1 R^-T, so X^T X is never formed.
  • polyfit The least-squares polynomial of degree deg through the points (x, y): coefficients rising, `c[0] + c[1] x + ...
  • polyval The polynomial with rising coefficients c at each element of x (Horner's rule), in the shape of x.
  • wls Weighted least squares: minimizes sum w_i (y_i - x_i b)^2 (OLS on rows scaled by sqrt(w)), with weights >= 0, e.g.

Structs

ValuesSource

pub struct Values

A contiguous copy of some data as f64, in row-major order: what Sample::values gives.

nabi
use stats::Sample;

let v = [3.0, 1.0].values();
assert(v.len() == 2 && v.to_vector()[0] == 3.0);
  • pub fn len(self) -> usize§

    Source

    The number of values.

    nabi
    use stats::Sample;
    
    assert([1.0, 2.0, 3.0].values().len() == 3);
    
  • pub fn is_empty(self) -> bool§

    Source

    Whether there are none.

  • pub fn to_vector(self) -> Vector<f64>§

    Source

    The values as a new rank-1 array.

    nabi
    use stats::Sample;
    
    let v = [1, 2].values().to_vector();
    assert(v[1] == 2.0);
    
Trait implementations 1

HistogramSource

pub struct Histogram

Counts of values in bins: counts[i] values fell in [edges[i], edges[i + 1]), the last bin closed on the right.

  • pub counts: Array<i64, 1>§

    Source

    The number of values in each bin.

  • pub edges: Vector<f64>§

    Source

    The len(counts) + 1 bin edges, rising.

  • pub fn len(self) -> usize§

    Source

    The number of bins.

  • pub fn density(self) -> Vector<f64>§

    Source

    The density in each bin: count / (total * width), which integrates to 1 over the range.

    nabi
    let h = try stats::histogram([1.0, 2.0, 3.0, 4.0], stats::Bins::Count(2));
    assert(h.density()[0] == 1.0 / 3.0);
    
  • pub fn centers(self) -> Vector<f64>§

    Source

    The midpoints of the bins.

    nabi
    let h = try stats::histogram([0.0, 1.0, 2.0, 4.0], stats::Bins::Count(2));
    assert(h.centers().to_list() == [1.0, 3.0]);
    

IntervalSource

pub struct Interval

The closed interval [lo, hi]. x in i (or x ∈ i) tests membership.

nabi
use stats::Interval;

let i = Interval { lo: 1.0, hi: 3.0 };
assert(2.0 in i && !(4.0 in i));
assert(i.mid() == 2.0 && i.width() == 2.0);
assert(f"{i}" == "[1, 3]");
  • pub lo: f64§

    Source

    The lower end.

  • pub hi: f64§

    Source

    The upper end.

  • pub fn around(mid: f64, half: f64) -> Interval§

    Source

    [mid - half, mid + half].

    nabi
    assert(stats::Interval::around(5.0, 1.5).lo == 3.5);
    
  • pub fn width(self) -> f64§

    Source

    hi - lo.

    nabi
    assert(stats::Interval { lo: 1.0, hi: 4.0 }.width() == 3.0);
    
  • pub fn mid(self) -> f64§

    Source

    The midpoint.

    nabi
    assert(stats::Interval { lo: 1.0, hi: 4.0 }.mid() == 2.5);
    
Trait implementations 2
  • impl ops::Contains<f64> for Interval
  • impl Display for Interval

BootstrapSource

pub struct Bootstrap

The outcome of bootstrap.

  • pub estimate: f64§

    Source

    The statistic of the sample itself.

  • pub se: f64§

    Source

    The standard deviation of the replicates (ddof = 1).

  • pub bias: f64§

    Source

    mean(replicates) - estimate.

  • The confidence interval.

  • pub replicates: Vector<f64>§

    Source

    The statistic of each resample.

SamplerSource

pub struct Sampler

A seeded Xoshiro256++ generator for g ~ d, which advances g as d.sample(ref g) does. It is an Rng, so the method forms take it too. A copy continues the same stream on its own.

nabi
use stats::{Distribution, Normal, Sampler};

let g = Sampler::seed(42);
let a = Normal::standard().sample(ref g);
let b = Normal::standard().sample(ref g);
assert(a != b);
  • pub fn seed(seed: u64) -> Sampler§

    Source

    The stream of Xoshiro256PlusPlus::seed(seed).

    nabi
    use std::random::Rng;
    
    let a = stats::Sampler::seed(1);
    let b = stats::Sampler::seed(1);
    assert(a.next_u64() == b.next_u64());
    
  • pub fn from_os() -> Sampler§

    Source

    A stream seeded from the operating system.

Trait implementations 1
  • impl Rng for Sampler

Enums

CorrMethodSource

pub enum CorrMethod

How corr measures association.

  • Pearson§

    Source

    Pearson's r (linear).

  • Spearman§

    Source

    Spearman's rho (monotone, on ranks).

  • Kendall§

    Source

    Kendall's tau-b (concordance of pairs).

TiesSource

pub enum Ties

How rankdata ranks equal values (SciPy's method).

nabi
use stats::Ties;

let x = [10.0, 20.0, 10.0, 30.0];
assert(stats::rankdata(x)[0] == 1.5);
assert(stats::rankdata(x, Ties::Min)[2] == 1.0);
assert(stats::rankdata(x, Ties::Dense)[3] == 3.0);
  • Average§

    Source

    The mean of the ranks the group spans (the default).

  • The lowest rank of the group.

  • The highest rank of the group.

  • Ranks 1, 2, 3, ... over the distinct values.

  • Ordinal§

    Source

    Distinct ranks in order of appearance.

StatsErrorSource

pub enum StatsError

What went wrong in a statistics call.

nabi
use stats::StatsError;

let e = try {
    _ = try stats::Normal::new(0.0, -1.0);
    StatsError::NotFinite { what: "" }
} catch e: StatsError { e };
assert(f"{e}".contains("sigma"));
  • TooFew§

    Source

    Fewer values than the statistic needs: need of what, got given.

  • InvalidParameter§

    Source

    A distribution parameter out of its range; what names it and the range.

  • InvalidArgument§

    Source

    An argument out of its range (a probability above 1, an axis past the rank, a negative weight); what says which.

  • ShapeMismatch§

    Source

    Operands whose lengths or shapes do not fit; what names both.

  • NotFinite§

    Source

    The input holds NaN or an infinity where the method cannot take one.

  • Singular§

    Source

    A design matrix without full column rank (collinear columns), or a singular covariance.

  • NoConvergence§

    Source

    An iteration did not converge in iterations steps.

Trait implementations 2
  • impl Display for StatsError
  • impl Error for StatsError

BinsSource

pub enum Bins

How histogram and bin_edges choose the bins. The rules are NumPy's, with the same results: each gives a bin width, and the range is cut into ceil(range / width) equal bins.

nabi
use stats::Bins;

let x = [1.0, 2.0, 2.0, 3.0, 4.0];
assert((try stats::bin_edges(x, Bins::Count(3))).len() == 4);
assert((try stats::histogram(x, Bins::Width(1.0))).counts[1] == 2);
  • Count(usize)§

    Source

    This many equal bins over the data's range.

  • Width(f64)§

    Source

    Bins of this width from the minimum.

  • Edges(Vector<f64>)§

    Source

    These edges, rising (bins [e0, e1), ..., [e_n-1, e_n]).

  • The smaller width of Sturges and Fd (NumPy's default estimator "auto").

  • Sturges§

    Source

    range / (log2(n) + 1): for small, roughly normal data.

  • Scott (1979): (24 sqrt(pi) / n)^(1/3) * std.

  • Freedman and Diaconis (1981): 2 iqr / n^(1/3); robust to outliers.

  • range / sqrt(n).

  • range / (2 n^(1/3)).

  • Doane (1976): Sturges corrected for skewness.

BootMethodSource

pub enum BootMethod

How bootstrap turns the replicates into an interval.

  • Percentile§

    Source

    The quantiles of the replicates.

  • The percentile interval reflected about the estimate (2 theta - q), the "basic" bootstrap.

  • Bias-corrected and accelerated (Efron 1987): the percentile interval shifted by the median bias of the replicates and scaled by the jackknife acceleration. Second-order accurate; the default.

Traits

SampleSource

pub trait Sample

The data a statistic reads: List<T> and Array<T, N> of any rank for T in f64, f32, i64, i32 and usize, fixed arrays and i64 ranges (what linalg::AsVector<f64> takes, plus any rank). Values are taken in row-major order and converted to f64.

nabi
use core::array::Matrix;

let m: Matrix<f64> = [[1, 2], [3, 4]];
assert(stats::mean(m) == 2.5);
assert(stats::mean([1, 2, 3, 6]) == 3.0);
assert(stats::mean([1.5f32, 2.5f32]) == 2.0);
assert(stats::mean(1..5) == 2.5);
  • fn values(self) -> Values§

    Source

    The values as a contiguous f64 copy.

Functions

corrSource

pub fn corr(x: Matrix<f64>, method: CorrMethod = CorrMethod::Pearson) throws (StatsError) -> Matrix<f64>

The correlation matrix of the columns of x by method (default Pearson). The diagonal is 1 (NaN for a constant column).

nabi
use core::array::Matrix;
use stats::CorrMethod;

let x: Matrix<f64> = [[1, 1], [2, 4], [3, 9], [4, 16]];
assert((try stats::corr(x, CorrMethod::Spearman))[0, 1] == 1.0);

covSource

pub fn cov(x: Matrix<f64>, ddof: usize = 1) throws (StatsError) -> Matrix<f64>

The covariance matrix of the columns of x (rows are observations, as pandas' DataFrame.cov; NumPy's cov(x, rowvar=False)), dividing by n - ddof (default 1, the unbiased estimate). The columns are centered by their means (two-pass), then Xc^T Xc is one linalg product. O(n p^2). Throws TooFew when n <= ddof.

nabi
use core::array::Matrix;

let x: Matrix<f64> = [[1, 2], [2, 4], [3, 7]];
let c = try stats::cov(x);
assert(c[0, 0] == 1.0 && c[0, 1] == 2.5 && c[1, 1] == 6.333333333333333);

kendallSource

pub fn kendall<X: Sample, Y: Sample>(x: X, y: Y) throws (StatsError) -> f64

Kendall's tau-b: (concordant - discordant) / sqrt((n0 - n1) (n0 - n2)), which corrects for ties in either sample. Knight's algorithm, O(n log n).

nabi
let t = try stats::kendall([12.0, 2.0, 1.0, 12.0, 2.0], [1.0, 4.0, 7.0, 1.0, 0.0]);
assert((t + 0.4714045207910316).abs() < 1e-15);

pearsonSource

pub fn pearson<X: Sample, Y: Sample>(x: X, y: Y) throws (StatsError) -> f64

Pearson's correlation coefficient. NaN when either sample is constant. Throws ShapeMismatch for unequal lengths, TooFew below 2 pairs.

nabi
assert(try stats::pearson([1.0, 2.0, 3.0], [2.0, 4.0, 6.5]) > 0.99);
assert(try stats::pearson([1.0, 2.0, 3.0], [3.0, 2.0, 1.0]) == -1.0);

rankdataSource

pub fn rankdata<X: Sample>(x: X, ties: Ties = Ties::Average) -> Vector<f64>

The ranks of the values, 1 for the smallest, ties by ties (default Average, the mid-rank). O(n log n). SciPy: rankdata.

nabi
let r = stats::rankdata([3.0, 1.0, 2.0]);
assert(r[0] == 3.0 && r[1] == 1.0);

spearmanSource

pub fn spearman<X: Sample, Y: Sample>(x: X, y: Y) throws (StatsError) -> f64

Spearman's rank correlation: Pearson's r of the mid-ranks.

nabi
assert(try stats::spearman([1.0, 2.0, 3.0, 4.0], [1.0, 4.0, 9.0, 16.0]) == 1.0);

bin_edgesSource

pub fn bin_edges<X: Sample>(x: X, bins: Bins = Bins::Auto) throws (StatsError) -> Vector<f64>

The bin edges histogram would use for x (NaN and infinities ignored). Throws InvalidArgument for an empty count, a width that is not positive, or edges that do not rise.

nabi
let e = try stats::bin_edges([0.0, 1.0, 2.0, 3.0, 4.0], stats::Bins::Sturges);
assert(e.len() == 5 && e[0] == 0.0 && e[4] == 4.0);

histogramSource

pub fn histogram<X: Sample>(x: X, bins: Bins = Bins::Auto) throws (StatsError) -> Histogram

The histogram of x over bins (default Auto): values outside the edges and NaN are not counted; the last bin includes its right edge. Bins of equal width are found by arithmetic, explicit edges by binary search. O(n log bins).

nabi
use core::array::Array;

let h = try stats::histogram([1.0, 2.0, 2.0, 3.0, 4.0], stats::Bins::Count(3));
assert(h.counts == Array::<i64, 1>::from([1, 2, 2]));

bootstrapSource

pub fn bootstrap<X: Sample>(x: X, stat: fn(Vector<f64>) -> f64, resamples: usize = 9999, level: f64 = 0.95, method: BootMethod = BootMethod::Bca, seed: u64 = 0) throws (StatsError) -> Bootstrap

A bootstrap confidence interval at level for stat of the sample x: resamples resamples with replacement drawn from a Xoshiro256++ stream seeded with seed (so the result repeats), the interval by method (default BCa, which also evaluates stat on the n leave-one-out samples). Throws TooFew below 2 values, InvalidArgument for a level outside (0, 1) or fewer than 2 resamples.

nabi
use core::array::Vector;

let x = [2.1, 3.4, 1.9, 5.6, 4.4, 3.3, 2.8, 4.1, 3.9, 2.5];
let b = try stats::bootstrap(x, |v: Vector<f64>| -> f64 { stats::mean(v) }, 2000, 95pct);
assert(b.estimate in b.ci && b.ci.lo > 2.5 && b.ci.hi < 4.3);