|
SummaryStatistics
but handles n-tuple values instead of scalar values. It can also compute the
full covariance matrix for the input data.
</p>
<p>
Neither <code>DescriptiveStatistics nor SummaryStatistics
is
thread-safe. <a href="../apidocs/org/apache/commons/math/stat/descriptive/SynchronizedDescriptiveStatistics.html">
SynchronizedDescriptiveStatistics</a> and
<a href="../apidocs/org/apache/commons/math/stat/descriptive/SynchronizedSummaryStatistics.html">
SynchronizedSummaryStatistics</a>, respectively, provide thread-safe versions for applications that
require concurrent access to statistical aggregates by multiple threads.
<a href="../apidocs/org/apache/commons/math/stat/descriptive/SynchronizedMultiVariateSummaryStatistics.html">
SynchronizedMultivariateSummaryStatistics</a> provides threadsafe MultivariateSummaryStatistics.
</p>
<p>
There is also a utility class,
<a href="../apidocs/org/apache/commons/math/stat/StatUtils.html">
StatUtils</a>, that provides static methods for computing statistics
directly from double[] arrays.
</p>
<p>
Here are some examples showing how to compute Descriptive statistics.
<dl>
<dt>Compute summary statistics for a list of double values
<br>DescriptiveStatistics
aggregate
(values are stored in memory):
<source>
// Get a DescriptiveStatistics instance
DescriptiveStatistics stats = new DescriptiveStatistics();
// Add the data from the array
for( int i = 0; i < inputArray.length; i++) {
stats.addValue(inputArray[i]);
}
// Compute some statistics
double mean = stats.getMean();
double std = stats.getStandardDeviation();
double median = stats.getMedian();
</source>
</dd>
<dd>Using the SummaryStatistics
aggregate (values are
<strong>not stored in memory):
<source>
// Get a SummaryStatistics instance
SummaryStatistics stats = new SummaryStatistics();
// Read data from an input stream,
// adding values and updating sums, counters, etc.
while (line != null) {
line = in.readLine();
stats.addValue(Double.parseDouble(line.trim()));
}
in.close();
// Compute the statistics
double mean = stats.getMean();
double std = stats.getStandardDeviation();
//double median = stats.getMedian(); <-- NOT AVAILABLE
</source>
</dd>
<dd>Using the StatUtils
utility class:
<source>
// Compute statistics directly from the array
// assume values is a double[] array
double mean = StatUtils.mean(values);
double std = StatUtils.variance(values);
double median = StatUtils.percentile(50);
// Compute the mean of the first three values in the array
mean = StatUtils.mean(values, 0, 3);
</source>
</dd>
<dt>Maintain a "rolling mean" of the most recent 100 values from
an input stream</dt>
<br>DescriptiveStatistics
instance with
window size set to 100
<source>
// Create a DescriptiveStats instance and set the window size to 100
DescriptiveStatistics stats = new DescriptiveStatistics();
stats.setWindowSize(100);
// Read data from an input stream,
// displaying the mean of the most recent 100 observations
// after every 100 observations
long nLines = 0;
while (line != null) {
line = in.readLine();
stats.addValue(Double.parseDouble(line.trim()));
if (nLines == 100) {
nLines = 0;
System.out.println(stats.getMean());
}
}
in.close();
</source>
</dd>
<dt>Compute statistics in a thread-safe manner
<br/>
<dd>Use a SynchronizedDescriptiveStatistics
instance
<source>
// Create a SynchronizedDescriptiveStatistics instance and
// use as any other DescriptiveStatistics instance
DescriptiveStatistics stats = new SynchronizedDescriptiveStatistics();
</source>
</dd>
<dt>Compute statistics for multiple samples and overall statistics concurrently
<br/>
<dd>There are two ways to do this using AggregateSummaryStatistics.
The first is to use an <code>AggregateSummaryStatistics instance to accumulate
overall statistics contributed by <code>SummaryStatistics instances created using
<a href="../apidocs/org/apache/commons/math/stat/descriptive/AggregateSummaryStatistics.html#createContributingStatistics()">
AggregateSummaryStatistics.createContributingStatistics()</a>:
<source>
// Create a AggregateSummaryStatistics instance to accumulate the overall statistics
// and AggregatingSummaryStatistics for the subsamples
AggregateSummaryStatistics aggregate = new AggregateSummaryStatistics();
SummaryStatistics setOneStats = aggregate.createContributingStatistics();
SummaryStatistics setTwoStats = aggregate.createContributingStatistics();
// Add values to the subsample aggregates
setOneStats.addValue(2);
setOneStats.addValue(3);
setTwoStats.addValue(2);
setTwoStats.addValue(4);
...
// Full sample data is reported by the aggregate
double totalSampleSum = aggregate.getSum();
</source>
The above approach has the disadvantages that the <code>addValue calls must be synchronized on the
<code>SummaryStatistics instance maintained by the aggregate and each value addition updates the
aggregate as well as the subsample. For applications that can wait to do the aggregation until all values
have been added, a static
<a href="../apidocs/org/apache/commons/math/stat/descriptive/AggregateSummaryStatistics.html#aggregate(java.util.Collection)">
aggregate</a> method is available, as shown in the following example.
This method should be used when aggregation needs to be done across threads.
<source>
// Create SummaryStatistics instances for the subsample data
SummaryStatistics setOneStats = new SummaryStatistics();
SummaryStatistics setTwoStats = new SummaryStatistics();
// Add values to the subsample SummaryStatistics instances
setOneStats.addValue(2);
setOneStats.addValue(3);
setTwoStats.addValue(2);
setTwoStats.addValue(4);
...
// Aggregate the subsample statistics
Collection<SummaryStatistics> aggregate = new ArrayList<SummaryStatistics>();
aggregate.add(setOneStats);
aggregate.add(setTwoStats);
StatisticalSummary aggregatedStats = AggregateSummaryStatistics.aggregate(aggregate);
// Full sample data is reported by aggregatedStats
double totalSampleSum = aggregatedStats.getSum();
</source>
</dd>
</dl>
</p>
</subsection>
<subsection name="1.3 Frequency distributions">
<p>
<a href="../apidocs/org/apache/commons/math/stat/Frequency.html">
org.apache.commons.math.stat.descriptive.Frequency</a>
provides a simple interface for maintaining counts and percentages of discrete
values.
</p>
<p>
Strings, integers, longs and chars are all supported as value types,
as well as instances of any class that implements <code>Comparable.
The ordering of values used in computing cumulative frequencies is by
default the <i>natural ordering, but this can be overriden by supplying a
<code>Comparator to the constructor. Adding values that are not
comparable to those that have already been added results in an
<code>IllegalArgumentException.
</p>
<p>
Here are some examples.
<dl>
<dt>Compute a frequency distribution based on integer values
<br>slope
are
available as well as ANOVA, r-square and Pearson's r statistics.
</p>
<p>
Observations (x,y pairs) can be added to the model one at a time or they
can be provided in a 2-dimensional array. The observations are not stored
in memory, so there is no limit to the number of observations that can be
added to the model.
</p>
<p>
<strong>Usage Notes: [n,k]
matrix whose k
columns are called
<b>regressors, b is k-vector
of regression parameters and u
is an n-vector
of <b>error terms or residuals. The notation is quite standard in literature,
cf eg <a href="http://www.econ.queensu.ca/ETM">Davidson and MacKinnon, Econometrics Theory and Methods, 2004.
</p>
<p>
Two implementations are provided: <a href="../apidocs/org/apache/commons/math/stat/regression/OLSMultipleLinearRegression.html">
org.apache.commons.math.stat.regression.OLSMultipleLinearRegression</a> and
<a href="../apidocs/org/apache/commons/math/stat/regression/GLSMultipleLinearRegression.html">
org.apache.commons.math.stat.regression.GLSMultipleLinearRegression</a>
</p>
<p>
Observations (x,y and covariance data matrices) can be added to the model via the <code>addData(double[] y, double[][] x, double[][] covariance) method.
The observations are stored in memory until the next time the addData method is invoked.
</p>
<p>
<strong>Usage Notes: addData(double[] y, double[][] x, double[][] covariance)
method and
<code>IllegalArgumentException is thrown when inappropriate.
</li>
<li> Only the GLS regressions require the covariance matrix, so in the OLS regression it is ignored and can be safely
inputted as <code>null.
</ul>
</p>
<p>
Here are some examples.
<dl>
<dt>OLS regression
<br>MultipleLinearRegression
interface:
<source>
double[] beta = regression.estimateRegressionParameters();
double[] residuals = regression.estimateResiduals();
double[][] parametersVariance = regression.estimateRegressionParametersVariance();
double regressandVariance = regression.estimateRegressandVariance();
</source>
</dd>
<dt>GLS regression
<br>MultipleLinearRegression
interface as
the OLS regression.
</dd>
</dl>
</p>
</subsection>
<subsection name="1.6 Rank transformations">
<p>
Some statistical algorithms require that input data be replaced by ranks.
The <a href="../apidocs/org/apache/commons/math/stat/ranking/package-summary.html">
org.apache.commons.math.stat.ranking</a> package provides rank transformation.
<a href="../apidocs/org/apache/commons/math/stat/ranking/RankingAlgorithm.html">
RankingAlgorithm</a> defines the interface for ranking.
<a href="../apidocs/org/apache/commons/math/stat/ranking/NaturalRanking.html">
NaturalRanking</a> provides an implementation that has two configuration options.
<ul>
<li>
Ties strategy</a> deterimines how ties in the source data are handled by the ranking
<li>
NaN strategy</a> determines how NaN values in the source data are handled.
</ul>
</p>
<p>
Examples:
<source>
NaturalRanking ranking = new NaturalRanking(NaNStrategy.MINIMAL,
TiesStrategy.MAXIMUM);
double[] data = { 20, 17, 30, 42.3, 17, 50,
Double.NaN, Double.NEGATIVE_INFINITY, 17 };
double[] ranks = ranking.rank(exampleData);
</source>
results in <code>ranks containing {6, 5, 7, 8, 5, 9, 2, 2, 5}.
<source>
new NaturalRanking(NaNStrategy.REMOVED,TiesStrategy.SEQUENTIAL).rank(exampleData);
</source>
returns <code>{5, 2, 6, 7, 3, 8, 1, 4}.
</p>
<p>
The default <code>NaNStrategy is NaNStrategy.MAXIMAL. This makes NaN
values larger than any other value (including <code>Double.POSITIVE_INFINITY). The
default <code>TiesStrategy is TiesStrategy.AVERAGE,
which assigns tied
values the average of the ranks applicable to the sequence of ties. See the
<a href="../apidocs/org/apache/commons/math/stat/ranking/NaturalRanking.html">
NaturalRanking</a> for more examples and
TiesStrategy</a> and NaNStrategy
for details on these configuration options.
</p>
</subsection>
<subsection name="1.7 Covariance and correlation">
<p>
The <a href="../apidocs/org/apache/commons/math/stat/correlation/package-summary.html">
org.apache.commons.math.stat.correlation</a> package computes covariances
and correlations for pairs of arrays or columns of a matrix.
<a href="../apidocs/org/apache/commons/math/stat/correlation/Covariance.html">
Covariance</a> computes covariances,
<a href="../apidocs/org/apache/commons/math/stat/correlation/PearsonsCorrelation.html">
PearsonsCorrelation</a> provides Pearson's Product-Moment correlation coefficients and
<a href="../apidocs/org/apache/commons/math/stat/correlation/SpearmansCorrelation.html">
SpearmansCorrelation</a> computes Spearman's rank correlation.
</p>
<p>
<strong>Implementation Notes
<ul>
<li>
Unbiased covariances are given by the formula <br>X
and E(Y)
is the mean of the <code>Y values. Non-bias-corrected estimates use
<code>n in place of n - 1.
Whether or not covariances are
bias-corrected is determined by the optional parameter, "biasCorrected," which
defaults to <code>true.
</li>
<li>
<a href="../apidocs/org/apache/commons/math/stat/correlation/PearsonsCorrelation.html">
PearsonsCorrelation</a> computes correlations defined by the formula E(Y)
are means of X
and Y
and <code>s(X), s(Y)
are standard deviations.
</li>
<li>
<a href="../apidocs/org/apache/commons/math/stat/correlation/SpearmansCorrelation.html">
SpearmansCorrelation</a> applies a rank transformation to the input data and computes Pearson's
correlation on the ranked data. The ranking algorithm is configurable. By default,
<a href="../apidocs/org/apache/commons/math/stat/ranking/NaturalRanking.html">
NaturalRanking</a> with default strategies for handling ties and NaN values is used.
</li>
</ul>
</p>
<p>
<strong>Examples:
<dl>
<dt>Covariance of 2 arrays
<br>y
, use:
<source>
new Covariance().covariance(x, y)
</source>
For non-bias-corrected covariances, use
<source>
covariance(x, y, false)
</source>
</dd>
<br>data
can be computed using
<source>
new Covariance().computeCovarianceMatrix(data)
</source>
The i-jth entry of the returned matrix is the unbiased covariance of the ith and jth
columns of <code>data. As above, to get non-bias-corrected covariances,
use
<source>
computeCovarianceMatrix(data, false)
</source>
</dd>
<br>y
, use:
<source>
new PearsonsCorrelation().correlation(x, y)
</source>
</dd>
<br>data
can be computed using
<source>
new PearsonsCorrelation().computeCorrelationMatrix(data)
</source>
The i-jth entry of the returned matrix is the Pearson's product-moment correlation between the
ith and jth columns of <code>data.
</dd>
<br>RealMatrix.
Then the matrix of standard errors is
<source>
correlation.getCorrelationStandardErrors();
</source>
The formula used to compute the standard error is <br/>
<code>SEr = ((1 - r2) / (n - 2))1/2y
:
<source>
new SpearmansCorrelation().correlation(x, y)
</source>
This is equivalent to
<source>
RankingAlgorithm ranking = new NaturalRanking();
new PearsonsCorrelation().correlation(ranking.rank(x), ranking.rank(y))
</source>
</dd>
<br>t-
,
<code>Chi-Square and One-Way ANOVA
tests. The
interfaces are
<a href="../apidocs/org/apache/commons/math/stat/inference/TTest.html">
TTest</a>,
<a href="../apidocs/org/apache/commons/math/stat/inference/ChiSquareTest.html">
ChiSquareTest</a>, and
<a href="../apidocs/org/apache/commons/math/stat/inference/OneWayAnova.html">
OneWayAnova</a> with provided implementations
<a href="../apidocs/org/apache/commons/math/stat/inference/TTestImpl.html">
TTestImpl</a>,
<a href="../apidocs/org/apache/commons/math/stat/inference/ChiSquareTestImpl.html">
ChiSquareTestImpl</a> and
<a href="../apidocs/org/apache/commons/math/stat/inference/OneWayAnovaImpl.html">
OneWayAnovaImpl</a>, respectively.
The
<a href="../apidocs/org/apache/commons/math/stat/inference/TestUtils.html">
TestUtils</a> class provides static methods to get test instances or
to compute test statistics directly. The examples below all use the
static methods in <code>TestUtils to execute tests. To get
test object instances, either use e.g.,
<code>TestUtils.getTTest() or use the implementation constructors
directly, e.g.,
<code>new TTestImpl().
</p>
<p>
<strong>Implementation Notes
<ul>
<li>Both one- and two-sample t-tests are supported. Two sample tests
can be either paired or unpaired and the unpaired two-sample tests can
be conducted under the assumption of equal subpopulation variances or
without this assumption. When equal variances is assumed, a pooled
variance estimate is used to compute the t-statistic and the degrees
of freedom used in the t-test equals the sum of the sample sizes minus 2.
When equal variances is not assumed, the t-statistic uses both sample
variances and the
<a href="http://www.itl.nist.gov/div898/handbook/prc/section3/gifs/nu3.gif">
Welch-Satterwaite approximation</a> is used to compute the degrees
of freedom. Methods to return t-statistics and p-values are provided in each
case, as well as boolean-valued methods to perform fixed significance
level tests. The names of methods or methods that assume equal
subpopulation variances always start with "homoscedastic." Test or
test-statistic methods that just start with "t" do not assume equal
variances. See the examples below and the API documentation for
more details.</li>
<li>The validity of the p-values returned by the t-test depends on the
assumptions of the parametric t-test procedure, as discussed
<a href="http://www.basic.nwu.edu/statguidefiles/ttest_unpaired_ass_viol.html">
here</a>
<li>p-values returned by t-, chi-square and Anova tests are exact, based
on numerical approximations to the t-, chi-square and F distributions in the
<code>distributions package.
<li>p-values returned by t-tests are for two-sided tests and the boolean-valued
methods supporting fixed significance level tests assume that the hypotheses
are two-sided. One sided tests can be performed by dividing returned p-values
(resp. critical values) by 2.</li>
<li>Degrees of freedom for chi-square tests are integral values, based on the
number of observed or expected counts (number of observed counts - 1)
for the goodness-of-fit tests and (number of columns -1) * (number of rows - 1)
for independence tests.</li>
</ul>
</p>
<p>
<strong>Examples:
<dl>
<dt>One-sample t
tests
<br>mu.
</dd>
<dd>To perform the test using a fixed significance level, use:
<source>
TestUtils.tTest(mu, observed, alpha);
</source>
where <code>0 < alpha < 0.5 is the significance level of
the test. The boolean value returned will be <code>true iff the
null hypothesis can be rejected with confidence <code>1 - alpha.
To test, for example at the 95% level of confidence, use
<code>alpha = 0.05
</dd>
<br>sample2
is zero.
<p>
To compute the t-statistic:
<source>
TestUtils.pairedT(sample1, sample2);
</source>
</p>
<p>
To compute the p-value:
<source>
TestUtils.pairedTTest(sample1, sample2);
</source>
</p>
<p>
To perform a fixed significance level test with alpha = .05:
<source>
TestUtils.pairedTTest(sample1, sample2, .05);
</source>
</p>
The last example will return <code>true iff the p-value
returned by <code>TestUtils.pairedTTest(sample1, sample2)
is less than <code>.05
</dd>
<dd>Example 2: unpaired, two-sided, two-sample t-test using
<code>StatisticalSummary instances, without assuming that
subpopulation variances are equal.
<p>
First create the <code>StatisticalSummary instances. Both
<code>DescriptiveStatistics and SummaryStatistics
implement this interface. Assume that <code>summary1 and
<code>summary2 are SummaryStatistics
instances,
each of which has had at least 2 values added to the (virtual) dataset that
it describes. The sample sizes do not have to be the same -- all that is required
is that both samples have at least 2 elements.
</p>
<p>Note: The SummaryStatistics
class does
not store the dataset that it describes in memory, but it does compute all
statistics necessary to perform t-tests, so this method can be used to
conduct t-tests with very large samples. One-sample tests can also be
performed this way.
(See <a href="#1.2 Descriptive statistics">Descriptive statistics for details
on the <code>SummaryStatistics class.)
</p>
<p>
To compute the t-statistic:
<source>
TestUtils.t(summary1, summary2);
</source>
</p>
<p>
To compute the p-value:
<source>
TestUtils.tTest(sample1, sample2);
</source>
</p>
<p>
To perform a fixed significance level test with alpha = .05:
<source>
TestUtils.tTest(sample1, sample2, .05);
</source>
</p>
<p>
In each case above, the test does not assume that the subpopulation
variances are equal. To perform the tests under this assumption,
replace "t" at the beginning of the method name with "homoscedasticT"
</p>
</dd>
<br>double[]
array of expected counts, use:
<source>
long[] observed = {10, 9, 11};
double[] expected = {10.1, 9.8, 10.3};
System.out.println(TestUtils.chiSquare(expected, observed));
</source>
the value displayed will be
<code>sum((expected[i] - observed[i])^2 / expected[i])
</dd>
<dd> To get the p-value associated with the null hypothesis that
<code>observed conforms to expected
use:
<source>
TestUtils.chiSquareTest(expected, observed);
</source>
</dd>
<dd> To test the null hypothesis that observed
conforms to
<code>expected with alpha
siginficance level
(equiv. <code>100 * (1-alpha)% confidence) where
0 < alpha < 1 </code> use:
<source>
TestUtils.chiSquareTest(expected, observed, alpha);
</source>
The boolean value returned will be <code>true
iff the null hypothesis
can be rejected with confidence <code>1 - alpha.
</dd>
<dd>To compute a chi-square statistic statistic associated with a
<a href="http://www.itl.nist.gov/div898/handbook/prc/section4/prc45.htm">
chi-square test of independence</a> based on a two-dimensional (long[][])
<code>counts array viewed as a two-way table, use:
<source>
TestUtils.chiSquareTest(counts);
</source>
The rows of the 2-way table are
<code>count[0], ... , count[count.length - 1]. j
divided by the total count.
</dd>
<dd>To compute the p-value associated with the null hypothesis that
the classifications represented by the counts in the columns of the input 2-way
table are independent of the rows, use:
<source>
TestUtils.chiSquareTest(counts);
</source>
</dd>
<dd>To perform a chi-square test of independence with alpha
siginficance level (equiv. <code>100 * (1-alpha)% confidence)
where <code>0 < alpha < 1 use:
<source>
TestUtils.chiSquareTest(counts, alpha);
</source>
The boolean value returned will be <code>true iff the null
hypothesis can be rejected with confidence <code>1 - alpha.
</dd>
<br>TestUtils
methods:
<source>
double fStatistic = TestUtils.oneWayAnovaFValue(classes); // F-value
double pValue = TestUtils.oneWayAnovaPValue(classes); // P-value
</source>
To test perform a One-Way Anova test with signficance level set at 0.01
(so the test will, assuming assumptions are met, reject the null
hypothesis incorrectly only about one in 100 times), use
<source>
TestUtils.oneWayAnovaTest(classes, 0.01); // returns a boolean
// true means reject null hypothesis
</source>
</dd>
</dl>
</p>
</subsection>
</section>
</body>
</document>
Here is a short list of links related to this Commons Math stat.xml source code file:
Commons Math example source code file (stat.xml)
The Commons Math stat.xml source code<?xml version="1.0"?> <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You 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. --> <?xml-stylesheet type="text/xsl" href="./xdoc.xsl"?> <!-- $Revision: 925895 $ $Date: 2010-03-21 17:05:20 -0400 (Sun, 21 Mar 2010) $ --> <document url="stat.html"> <properties> <title>The Commons Math User Guide - Statistics </properties> <body> <section name="1 Statistics"> <subsection name="1.1 Overview"> <p> The statistics package provides frameworks and implementations for basic Descriptive statistics, frequency distributions, bivariate regression, and t-, chi-square and ANOVA test statistics. </p> <p> <a href="#a1.2_Descriptive_statistics">Descriptive statistics | Aggregate | Statistics Included | Values stored? | |
---|---|---|---|---|
<a href="../apidocs/org/apache/commons/math/stat/descriptive/DescriptiveStatistics.html"> DescriptiveStatistics</a> | min, max, mean, geometric mean, n, sum, sum of squares, standard deviation, variance, percentiles, skewness, kurtosis, median</td> | Yes | Yes | |
<a href="../apidocs/org/apache/commons/math/stat/descriptive/SummaryStatistics.html"> SummaryStatistics</a> | min, max, mean, geometric mean, n, sum, sum of squares, standard deviation, variance</td> | No | No |
... this post is sponsored by my books ... | |
![]() #1 New Release! |
![]() FP Best Seller |
Copyright 1998-2024 Alvin Alexander, alvinalexander.com
All Rights Reserved.
A percentage of advertising revenue from
pages under the /java/jwarehouse
URI on this website is
paid back to open source projects.