stats-ci
Description
Stats-ci provides some basic functions to compute confidence intervals of sample data. This includes the following:
- confidence intervals around the mean for numerical data,
- confidence intervals around a quantile (e.g., median) for arbitrary ordered data,
- confidence intervals for proportions.
- confidence intervals for comparisons (paired or unpaired observations).
Not included yet but planned are:
- confidence intervals for regression parameters.
- confidence intervals for other statistics (e.g., variance, etc.)
- Chi square test
Motivation
The motivation behind creating this crate came both from the recurring need of confidence intervals in personal projects and also out of frustration from having to look up the formulas each time. I reckoned that I might not be alone in this situation and that such a crate could prove useful to some.
Disclaimer
NB: As probably obvious from the 0.0.x version number, this crate is not currently in a finished state and any commit can possibly introduce breaking changes. At this point, I am making no particular efforts to preserve backward compatibility. Therefore, please use at your own risks at least until version 0.1 or above.
I am far from being a statistician and I will gladly welcome any advice or corrections. I only made a feeble attempt at numerical statibility (e.g., kahan sum, log-sum-exp). In any case, please be circumspect about the results obtained from this crate for the time being.
Usage
Add the most recent release to your Cargo.toml (check the latest version number on crates.io and replace { latest version } below):
[]
= "{ latest version }"
Features
The crate has two features:
approx(default) enables approximate comparison between intervals. Adds the dependency to the crateapprox.serdefeature adds the crateserdeas a dependency and provides serialization and deserialization for bothConfidenceandInterval, as well as the incremental states for intervals on the mean.
= { = "{ latest version }", = ["serde"] }
Examples
You can find more detailed information and additional examples from this crate's API documentation.
C.I. for the Mean
The crate provides functions to compute confidence intervals for the mean of floating-point (f32 or f64) data.
The functions are generic and can be used with any type that implements the Float trait from the crate num-traits.
The crate provides three functions to compute confidence intervals for the mean of floating-point data:
mean::Arithmetic::cicomputes the confidence interval for the arithmetic mean.mean::Geometric::cicomputes the confidence interval for the geometric meanmean::Harmonic::cicomputes the confidence interval for the harmonic mean
use *;
let data = ;
// 1. create a statistics object
let mut stats = new;
// 2. add data
stats.extend?;
// 3. define a confidence level
let confidence = new_two_sided;
// 4. compute the confidence interval over the mean for some
// confidence level
let ci = stats.ci_mean?;
// 5. get and print other statistics on the sample data
println!;
// mean: 53.67
println!;
// std_dev: 28.097613040716794
println!; // ci (two-sided 95%): [48.09482399055084, 59.24517600944916]
println!; // low: 48.09482399055084
println!; // high: 59.24517600944916
// 6. compute other confidence intervals
// (almost no additional perfomance cost)
println!; // upper one-sided 90% ci: [50.04495430416555,->)
println!; // lower one-sided 80% ci: (<-,56.044998597990755]
let ci = stats.ci_mean?;
println!; // ci: [48.09482399055084,->)
println!; // low: 48.09482399055084
println!; // high: inf
println!; // high: Some(48.09482399055084)
println!; // high: None
// get statistics for other means (harmonic)
let stats = from_iter?;
let ci = stats.ci_mean?;
println!;
// harmonic mean: 30.03131315633959
println!;
// ci: [23.614092539460778, 41.23786064976718]
// get statistics for other means (geometric)
let stats = from_iter?;
let ci = stats.ci_mean?;
println!;
// geometric mean: 43.7268032829256
println!;
// ci: [37.731050052007795, 50.675327686564806]
// incremental/intermediate statistics also work
let mut stats = from_iter?;
let ci = stats.ci_mean?;
// a. confidence interval from the original data
println!;
// incr ci: [48.09482399055084, 59.24517600944916]
// b. confidence interval after adding 10 additional data points
for _ in 0..10
let ci = stats.ci_mean?;
println!;
// incr ci: [87.80710255546494, 191.59289744453503]
// parallel computation of the confidence interval
use *;
let state = data
.clone
.par_iter
.map
.reduce;
println!;
// parallel ci: [48.09482399055084, 59.24517600944916]
Incremental statistics is useful in at least three common scenarios:
- when you have a stream of data and don't want to keep all values.
- when you want to continue collecting data until you have sufficient statistical significance (e.g., interval shorter than some width relative to the mean).
- when you want to compute the confidence intervals of several confidence levels in a single pass through the data.
C.I. for Quantiles
Depending on the type of data and measurements, it is sometimes inappropriate to compute the mean of the data because that value makes little sense. For instance, consider a communication system and suppose that we want to find an upper bound on message delays such that, with 90% confidence, at least 95% of messages are delivered within this bound. Then, the value of interest is the lower one-sided confidence interval of the 95th percentile with 90% confidence (quantile=.95, condidence level=0.9).
In a different context, if the data is an ordered sequence of strings, it might make sense to compute an interval around the median of the data, but the mean cannot be computed.
use *;
let quantile = 0.5; // median
let data = ;
let confidence = new_two_sided;
let ci = ci?;
assert_eq!;
let confidence = new_two_sided;
let ci = ci?;
assert_eq!;
let data = ;
let confidence = new_two_sided;
let ci = ci?;
println!; // ci: [E, L]
C.I. for Proportions
Confidence intervals for proportions are often used in the context of A/B testing or when measuring the success/failure rate of a system. It is also useful when running Monte-Carlo simulations to estimate the winning chances of a player in a game.
This crate uses the Wilson score interval to compute the confidence interval for a proportion, which is more stable than the standard normal approximation but results in slightly more conservative intervals.
use *;
let confidence = new_two_sided;
let data = ;
let ci = ci_if?;
println!; // ci: [0.2992980081982124, 0.7007019918017876]
assert!;
let population = 500;
let successes = 421;
let ci = ci?;
println!; // ci: [0.8074376489887337, 0.8713473021355645]
assert!;
Contributing
I will gladly and carefully consider any constructive comments that you have to offer. In particular, I will be considering constructive feedback both on the interface and the calculations with the following priorities correctness, code readability, genericity, efficiency.
Currently, the following are on my TODO list:
- [feature] confidence intervals for regression parameters.
- [stats] review/fix statistical tests
- [API] remove
unwrap()and reduce panicking code - [Refactoring] restructure error results
References
- Raj Jain. The Art of Computer Systems Performance Analysis: Techniques for Experimental Design, Measurement, Simulation, and Modeling, John Wiley & Sons, 1991.
- Wikipedia - Confidence interval
- Wikipedia - Binomial proportion confidence interval
- Wikipedia article on normal approximation interval
- Dransfield R.D., Brightwell R. (2012) Avoiding and Detecting Statistical Malpractice (or "How to Get On Top of Statistics): Design & Analysis for Biologists, with R. InfluentialPoints, UK online
- idem. Chapter Confidence intervals of proportions and rates
- Francis J. DiTraglia. Blog post: The Wilson Confidence Interval for a Proportion. Feb 2022.
- Nilan Noris. "The standard errors of the geometric and harmonic means and their application to index numbers." Ann. Math. Statist. 11(4): 445-448 (December, 1940). DOI: 10.1214/aoms/1177731830 JSTOR
- PennState. Stat 500. Online
License
Licensed under either of
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.
Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.