-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
feat: add stats/base/ndarray/variance
#9620
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
DivyanshuVortex
wants to merge
8
commits into
stdlib-js:develop
from
DivyanshuVortex:stats/base/variance
Closed
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
47f1a9a
feat(variance): add new package to stats/base/variance
DivyanshuVortex 032503b
Update package.json
DivyanshuVortex 9b71aeb
fix(bugs): fix bugs in the variance
DivyanshuVortex 079cbc2
Merge remote-tracking branch 'upstream/develop' into stats/base/variance
stdlib-bot d62aeda
style: add structure to repl
DivyanshuVortex d759330
Update test.ts
DivyanshuVortex 4004776
Update test.ts
DivyanshuVortex fd34c70
Update repl.txt
DivyanshuVortex File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
186 changes: 186 additions & 0 deletions
186
lib/node_modules/@stdlib/stats/base/ndarray/variance/README.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,186 @@ | ||
| <!-- | ||
|
|
||
| @license Apache-2.0 | ||
|
|
||
| Copyright (c) 2026 The Stdlib Authors. | ||
|
|
||
| Licensed under the Apache License, Version 2.0 (the "License"); | ||
| you may not use this file except in compliance with the License. | ||
| You may obtain a copy of the License at | ||
|
|
||
| http://www.apache.org/licenses/LICENSE-2.0 | ||
|
|
||
| Unless required by applicable law or agreed to in writing, software | ||
| distributed under the License is distributed on an "AS IS" BASIS, | ||
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| See the License for the specific language governing permissions and | ||
| limitations under the License. | ||
|
|
||
| --> | ||
|
|
||
| # variance | ||
|
|
||
| > Calculate the [variance][variance] of a one-dimensional ndarray. | ||
|
|
||
| <section class="intro"> | ||
|
|
||
| The population [variance][variance] of a finite size population of size `N` is given by | ||
|
|
||
| <!-- <equation class="equation" label="eq:population_variance" align="center" raw="\sigma^2 = \frac{1}{N} \sum_{i=0}^{N-1} (x_i - \mu)^2" alt="Equation for the population variance."> --> | ||
|
|
||
| ```math | ||
| \sigma^2 = \frac{1}{N} \sum_{i=0}^{N-1} (x_i - \mu)^2 | ||
| ``` | ||
|
|
||
| <!-- <div class="equation" align="center" data-raw-text="\sigma^2 = \frac{1}{N} \sum_{i=0}^{N-1} (x_i - \mu)^2" data-equation="eq:population_variance"> | ||
| <img src="https://cdn.jsdelivr.net/gh/stdlib-js/stdlib@08ca32895957967bd760a4fe02d61762432a0b72/lib/node_modules/@stdlib/stats/base/ndarray/variance/docs/img/equation_population_variance.svg" alt="Equation for the population variance."> | ||
| <br> | ||
| </div> --> | ||
|
|
||
| <!-- </equation> --> | ||
|
|
||
| where the population mean is given by | ||
|
|
||
| <!-- <equation class="equation" label="eq:population_mean" align="center" raw="\mu = \frac{1}{N} \sum_{i=0}^{N-1} x_i" alt="Equation for the population mean."> --> | ||
|
|
||
| ```math | ||
| \mu = \frac{1}{N} \sum_{i=0}^{N-1} x_i | ||
| ``` | ||
|
|
||
| <!-- <div class="equation" align="center" data-raw-text="\mu = \frac{1}{N} \sum_{i=0}^{N-1} x_i" data-equation="eq:population_mean"> | ||
| <img src="https://cdn.jsdelivr.net/gh/stdlib-js/stdlib@08ca32895957967bd760a4fe02d61762432a0b72/lib/node_modules/@stdlib/stats/base/ndarray/variance/docs/img/equation_population_mean.svg" alt="Equation for the population mean."> | ||
| <br> | ||
| </div> --> | ||
|
|
||
| <!-- </equation> --> | ||
|
|
||
| Often in the analysis of data, the true population [variance][variance] is not known _a priori_ and must be estimated from a sample drawn from the population distribution. If one attempts to use the formula for the population [variance][variance], the result is biased and yields an **uncorrected sample variance**. To compute a **corrected sample variance** for a sample of size `n`, | ||
|
|
||
| <!-- <equation class="equation" label="eq:corrected_sample_variance" align="center" raw="s^2 = \frac{1}{n-1} \sum_{i=0}^{n-1} (x_i - \bar{x})^2" alt="Equation for computing a corrected sample variance."> --> | ||
|
|
||
| ```math | ||
| s^2 = \frac{1}{n-1} \sum_{i=0}^{n-1} (x_i - \bar{x})^2 | ||
| ``` | ||
|
|
||
| <!-- <div class="equation" align="center" data-raw-text="s^2 = \frac{1}{n-1} \sum_{i=0}^{n-1} (x_i - \bar{x})^2" data-equation="eq:corrected_sample_variance"> | ||
| <img src="https://cdn.jsdelivr.net/gh/stdlib-js/stdlib@08ca32895957967bd760a4fe02d61762432a0b72/lib/node_modules/@stdlib/stats/base/ndarray/variance/docs/img/equation_corrected_sample_variance.svg" alt="Equation for computing a corrected sample variance."> | ||
| <br> | ||
| </div> --> | ||
|
|
||
| <!-- </equation> --> | ||
|
|
||
| where the sample mean is given by | ||
|
|
||
| <!-- <equation class="equation" label="eq:sample_mean" align="center" raw="\bar{x} = \frac{1}{n} \sum_{i=0}^{n-1} x_i" alt="Equation for the sample mean."> --> | ||
|
|
||
| ```math | ||
| \bar{x} = \frac{1}{n} \sum_{i=0}^{n-1} x_i | ||
| ``` | ||
|
|
||
| <!-- <div class="equation" align="center" data-raw-text="\bar{x} = \frac{1}{n} \sum_{i=0}^{n-1} x_i" data-equation="eq:sample_mean"> | ||
| <img src="https://cdn.jsdelivr.net/gh/stdlib-js/stdlib@08ca32895957967bd760a4fe02d61762432a0b72/lib/node_modules/@stdlib/stats/base/ndarray/variance/docs/img/equation_sample_mean.svg" alt="Equation for the sample mean."> | ||
| <br> | ||
| </div> --> | ||
|
|
||
| <!-- </equation> --> | ||
|
|
||
| The use of the term `n-1` is commonly referred to as Bessel's correction. Note, however, that applying Bessel's correction can increase the mean squared error between the sample variance and population variance. Depending on the characteristics of the population distribution, other correction factors (e.g., `n-1.5`, `n+1`, etc) can yield better estimators. | ||
|
|
||
| </section> | ||
|
|
||
| <!-- /.intro --> | ||
|
|
||
| <section class="usage"> | ||
|
|
||
| ## Usage | ||
|
|
||
| ```javascript | ||
| var variance = require( '@stdlib/stats/base/ndarray/variance' ); | ||
| ``` | ||
|
|
||
| #### variance( arrays ) | ||
|
|
||
| Computes the [variance][variance] of a one-dimensional ndarray. | ||
|
|
||
| ```javascript | ||
| var ndarray = require( '@stdlib/ndarray/base/ctor' ); | ||
| var scalar2ndarray = require( '@stdlib/ndarray/from-scalar' ); | ||
|
|
||
| var opts = { | ||
| 'dtype': 'generic' | ||
| }; | ||
|
|
||
| var xbuf = [ 1.0, -2.0, 2.0 ]; | ||
| var x = new ndarray( opts.dtype, xbuf, [ 3 ], [ 1 ], 0, 'row-major' ); | ||
| var correction = scalar2ndarray( 1.0, opts ); | ||
|
|
||
| var v = variance( [ x, correction ] ); | ||
| // returns ~4.3333 | ||
| ``` | ||
|
|
||
| The function has the following parameters: | ||
|
|
||
| - **arrays**: array-like object containing two elements: a one-dimensional input ndarray and a zero-dimensional ndarray specifying the degrees of freedom adjustment. Providing a non-zero degrees of freedom adjustment has the effect of adjusting the divisor during the calculation of the [variance][variance] according to `N-c` where `N` is the number of elements in the input ndarray and `c` corresponds to the provided degrees of freedom adjustment. When computing the [variance][variance] of a population, setting this parameter to `0` is the standard choice (i.e., the provided array contains data constituting an entire population). When computing the corrected sample [variance][variance], setting this parameter to `1` is the standard choice (i.e., the provided array contains data sampled from a larger population; this is commonly referred to as Bessel's correction). | ||
|
|
||
| </section> | ||
|
|
||
| <!-- /.usage --> | ||
|
|
||
| <section class="notes"> | ||
|
|
||
| ## Notes | ||
|
|
||
| - If provided an empty one-dimensional ndarray, the function returns `NaN`. | ||
| - If `N - c` is less than or equal to `0` (where `N` corresponds to the number of elements in the input ndarray and `c` corresponds to the provided degrees of freedom adjustment), the function returns `NaN`. | ||
|
|
||
| </section> | ||
|
|
||
| <!-- /.notes --> | ||
|
|
||
| <section class="examples"> | ||
|
|
||
| ## Examples | ||
|
|
||
| <!-- eslint no-undef: "error" --> | ||
|
|
||
| ```javascript | ||
| var discreteUniform = require( '@stdlib/random/array/discrete-uniform' ); | ||
| var ndarray = require( '@stdlib/ndarray/base/ctor' ); | ||
| var scalar2ndarray = require( '@stdlib/ndarray/from-scalar' ); | ||
| var ndarray2array = require( '@stdlib/ndarray/to-array' ); | ||
| var variance = require( '@stdlib/stats/base/ndarray/variance' ); | ||
|
|
||
| var opts = { | ||
| 'dtype': 'float64' | ||
| }; | ||
|
|
||
| var xbuf = discreteUniform( 10, -50, 50, opts ); | ||
| var x = new ndarray( opts.dtype, xbuf, [ xbuf.length ], [ 1 ], 0, 'row-major' ); | ||
| console.log( ndarray2array( x ) ); | ||
|
|
||
| var correction = scalar2ndarray( 1.0, opts ); | ||
| var v = variance( [ x, correction ] ); | ||
| console.log( v ); | ||
| ``` | ||
|
|
||
| </section> | ||
|
|
||
| <!-- /.examples --> | ||
|
|
||
| <!-- Section for related `stdlib` packages. Do not manually edit this section, as it is automatically populated. --> | ||
|
|
||
| <section class="related"> | ||
|
|
||
| </section> | ||
|
|
||
| <!-- /.related --> | ||
|
|
||
| <!-- Section for all links. Make sure to keep an empty line after the `section` element and another before the `/section` close. --> | ||
|
|
||
| <section class="links"> | ||
|
|
||
| [variance]: https://en.wikipedia.org/wiki/Variance | ||
|
|
||
| </section> | ||
|
|
||
| <!-- /.links --> |
112 changes: 112 additions & 0 deletions
112
lib/node_modules/@stdlib/stats/base/ndarray/variance/benchmark/benchmark.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,112 @@ | ||
| /** | ||
| * @license Apache-2.0 | ||
| * | ||
| * Copyright (c) 2026 The Stdlib Authors. | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| 'use strict'; | ||
|
|
||
| // MODULES // | ||
|
|
||
| var bench = require( '@stdlib/bench' ); | ||
| var uniform = require( '@stdlib/random/array/uniform' ); | ||
| var isnan = require( '@stdlib/math/base/assert/is-nan' ); | ||
| var pow = require( '@stdlib/math/base/special/pow' ); | ||
| var ndarray = require( '@stdlib/ndarray/base/ctor' ); | ||
| var scalar2ndarray = require( '@stdlib/ndarray/from-scalar' ); | ||
| var format = require( '@stdlib/string/format' ); | ||
| var pkg = require( './../package.json' ).name; | ||
| var variance = require( './../lib' ); | ||
|
|
||
|
|
||
| // VARIABLES // | ||
|
|
||
| var options = { | ||
| 'dtype': 'generic' | ||
| }; | ||
|
|
||
|
|
||
| // FUNCTIONS // | ||
|
|
||
| /** | ||
| * Creates a benchmark function. | ||
| * | ||
| * @private | ||
| * @param {PositiveInteger} len - array length | ||
| * @returns {Function} benchmark function | ||
| */ | ||
| function createBenchmark( len ) { | ||
| var correction; | ||
| var xbuf; | ||
| var x; | ||
|
|
||
| xbuf = uniform( len, -10.0, 10.0, options ); | ||
| x = new ndarray( options.dtype, xbuf, [ len ], [ 1 ], 0, 'row-major' ); | ||
| correction = scalar2ndarray( 1.0, options ); | ||
|
|
||
| return benchmark; | ||
|
|
||
| /** | ||
| * Benchmark function. | ||
| * | ||
| * @private | ||
| * @param {Benchmark} b - benchmark instance | ||
| */ | ||
| function benchmark( b ) { | ||
| var v; | ||
| var i; | ||
|
|
||
| b.tic(); | ||
| for ( i = 0; i < b.iterations; i++ ) { | ||
| v = variance( [ x, correction ] ); | ||
| if ( isnan( v ) ) { | ||
| b.fail( 'should not return NaN' ); | ||
| } | ||
| } | ||
| b.toc(); | ||
| if ( isnan( v ) ) { | ||
| b.fail( 'should not return NaN' ); | ||
| } | ||
| b.pass( 'benchmark finished' ); | ||
| b.end(); | ||
| } | ||
| } | ||
|
|
||
|
|
||
| // MAIN // | ||
|
|
||
| /** | ||
| * Main execution sequence. | ||
| * | ||
| * @private | ||
| */ | ||
| function main() { | ||
| var len; | ||
| var min; | ||
| var max; | ||
| var f; | ||
| var i; | ||
|
|
||
| min = 1; // 10^min | ||
| max = 6; // 10^max | ||
|
|
||
| for ( i = min; i <= max; i++ ) { | ||
| len = pow( 10, i ); | ||
| f = createBenchmark( len ); | ||
| bench( format( '%s:len=%d', pkg, len ), f ); | ||
| } | ||
| } | ||
|
|
||
| main(); |
43 changes: 43 additions & 0 deletions
43
...e_modules/@stdlib/stats/base/ndarray/variance/docs/img/equation_sample_mean.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
52 changes: 52 additions & 0 deletions
52
lib/node_modules/@stdlib/stats/base/ndarray/variance/docs/repl.txt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,52 @@ | ||
|
|
||
| {{alias}}( arrays ) | ||
| Computes the variance of a one-dimensional ndarray. | ||
|
|
||
| If provided an empty one-dimensional ndarray, the function returns `NaN`. | ||
|
|
||
| If `N - c` is less than or equal to `0` (where `N` corresponds to the number | ||
| of elements in the input ndarray and `c` corresponds to the provided degrees | ||
| of freedom adjustment), the function returns `NaN`. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| arrays: ArrayLikeObject<ndarray> | ||
| Array-like object containing two elements: a one-dimensional input | ||
| ndarray and a zero-dimensional ndarray specifying the degrees of freedom | ||
| adjustment. Providing a non-zero degrees of freedom adjustment has the | ||
| effect of adjusting the divisor during the calculation of the variance | ||
| according to `N-c` where `N` is the number of elements in the input | ||
| ndarray and `c` corresponds to the provided degrees of freedom | ||
| adjustment. When computing the variance of a population, setting this | ||
| parameter to `0` is the standard choice (i.e., the provided array | ||
| contains data constituting an entire population). When computing the | ||
| corrected sample variance, setting this parameter to `1` is the standard | ||
| choice (i.e., the provided array contains data sampled from a larger | ||
| population; this is commonly referred to as Bessel's correction). | ||
|
|
||
| Returns | ||
| ------- | ||
| out: number | ||
| The variance. | ||
|
|
||
| Examples | ||
| -------- | ||
| // Create input ndarray: | ||
| > var xbuf = [ 1.0, -2.0, 2.0 ]; | ||
| > var dt = 'generic'; | ||
| > var sh = [ xbuf.length ]; | ||
| > var st = [ 1 ]; | ||
| > var oo = 0; | ||
| > var ord = 'row-major'; | ||
| > var x = new {{alias:@stdlib/ndarray/ctor}}( dt, xbuf, sh, st, oo, ord ); | ||
|
|
||
| // Create correction ndarray: | ||
| > var opts = { 'dtype': dt }; | ||
| > var correction = {{alias:@stdlib/ndarray/from-scalar}}( 1.0, opts ); | ||
|
|
||
| // Compute the variance: | ||
| > {{alias}}( [ x, correction ] ) | ||
| ~4.3333 | ||
|
|
||
| See Also | ||
| -------- | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.