`import "github.com/gonum/stat"`

This repository is no longer maintained. Development has moved to https://github.com/gonum/gonum.

Package stat provides generalized statistical functions.

- func Bhattacharyya(p, q []float64) float64
- func CDF(q float64, c CumulantKind, x, weights []float64) float64
- func ChiSquare(obs, exp []float64) float64
- func CircularMean(x, weights []float64) float64
- func Correlation(x, y, weights []float64) float64
- func CorrelationMatrix(corr *mat64.SymDense, x mat64.Matrix, weights []float64) *mat64.SymDense
- func Covariance(x, y, weights []float64) float64
- func CovarianceMatrix(cov *mat64.SymDense, x mat64.Matrix, weights []float64) *mat64.SymDense
- func CrossEntropy(p, q []float64) float64
- func Entropy(p []float64) float64
- func ExKurtosis(x, weights []float64) float64
- func GeometricMean(x, weights []float64) float64
- func HarmonicMean(x, weights []float64) float64
- func Hellinger(p, q []float64) float64
- func Histogram(count, dividers, x, weights []float64) []float64
- func JensenShannon(p, q []float64) float64
- func KolmogorovSmirnov(x, xWeights, y, yWeights []float64) float64
- func KullbackLeibler(p, q []float64) float64
- func LinearRegression(x, y, weights []float64, origin bool) (alpha, beta float64)
- func Mahalanobis(x, y *mat64.Vector, chol *mat64.Cholesky) float64
- func Mean(x, weights []float64) float64
- func MeanStdDev(x, weights []float64) (mean, std float64)
- func MeanVariance(x, weights []float64) (mean, variance float64)
- func Mode(x, weights []float64) (val float64, count float64)
- func Moment(moment float64, x, weights []float64) float64
- func MomentAbout(moment float64, x []float64, mean float64, weights []float64) float64
- func Quantile(p float64, c CumulantKind, x, weights []float64) float64
- func RNoughtSquared(x, y, weights []float64, beta float64) float64
- func ROC(n int, y []float64, classes []bool, weights []float64) (tpr, fpr []float64)
- func RSquared(x, y, weights []float64, alpha, beta float64) float64
- func RSquaredFrom(estimates, values, weights []float64) float64
- func Skew(x, weights []float64) float64
- func SortWeighted(x, weights []float64)
- func SortWeightedLabeled(x []float64, labels []bool, weights []float64)
- func StdDev(x, weights []float64) float64
- func StdErr(std, sampleSize float64) float64
- func StdScore(x, mean, std float64) float64
- func Variance(x, weights []float64) float64
- type CC
- func (c *CC) CanonicalCorrelations(x, y mat64.Matrix, weights []float64) error
- func (c *CC) Corrs(dst []float64) []float64
- func (c *CC) Left(dst *mat64.Dense, spheredSpace bool) *mat64.Dense
- func (c *CC) Right(dst *mat64.Dense, spheredSpace bool) *mat64.Dense
- type CumulantKind
- type PC

- CC
- CircularMean
- Correlation
- Covariance
- Entropy
- ExKurtosis
- GeometricMean
- HarmonicMean
- Histogram
- KullbackLeibler
- Mean
- ROC (AUC)
- ROC (Unweighted)
- ROC (Weighted)
- StdDev
- StdErr
- Variance

doc.go pca_cca.go roc.go stat.go statmat.go

Bhattacharyya computes the distance between the probability distributions p and q given by:

-\ln ( \sum_i \sqrt{p_i q_i} )

The lengths of p and q must be equal. It is assumed that p and q sum to 1.

❖

func CDF(q float64, c CumulantKind, x, weights []float64) float64

CDF returns the empirical cumulative distribution function value of x, that is the fraction of the samples less than or equal to q. The exact behavior is determined by the CumulantKind. CDF is theoretically the inverse of the Quantile function, though it may not be the actual inverse for all values q and CumulantKinds.

The x data must be sorted in increasing order. If weights is nil then all of the weights are 1. If weights is not nil, then len(x) must equal len(weights).

CumulantKind behaviors:

- Empirical: Returns the lowest fraction for which q is greater than or equal to that fraction of samples

ChiSquare computes the chi-square distance between the observed frequences 'obs' and expected frequences 'exp' given by:

\sum_i (obs_i-exp_i)^2 / exp_i

The lengths of obs and exp must be equal.

CircularMean returns the circular mean of the dataset.

atan2(\sum_i w_i * sin(alpha_i), \sum_i w_i * cos(alpha_i))

If weights is nil then all of the weights are 1. If weights is not nil, then len(x) must equal len(weights).

Code:

x := []float64{0, 0.25 * math.Pi, 0.75 * math.Pi} weights := []float64{1, 2, 2.5} cmean := CircularMean(x, weights) fmt.Printf("The circular mean is %.5f.\n", cmean)

Output:

The circular mean is 1.37037.

Correlation returns the weighted correlation between the samples of x and y with the given means.

sum_i {w_i (x_i - meanX) * (y_i - meanY)} / (stdX * stdY)

The lengths of x and y must be equal. If weights is nil then all of the weights are 1. If weights is not nil, then len(x) must equal len(weights).

Code:

x := []float64{8, -3, 7, 8, -4} y := []float64{10, 5, 6, 3, -1} w := []float64{2, 1.5, 3, 3, 2} fmt.Println("Correlation computes the degree to which two datasets move together") fmt.Println("about their mean. For example, x and y above move similarly.") c := Correlation(x, y, w) fmt.Printf("Correlation is %.5f\n", c)

Output:

Correlation computes the degree to which two datasets move together about their mean. For example, x and y above move similarly. Correlation is 0.59915

CorrelationMatrix returns the correlation matrix calculated from a matrix of data, x, using a two-pass algorithm.

If weights is not nil the weighted correlation of x is calculated. weights must have length equal to the number of rows in input data matrix and must not contain negative elements. If corr is not nil it must either be zero-sized or have the same number of columns as the input data matrix. corr will be used as the destination for the correlation data. If corr is nil, a new mat64.SymDense is allocated for the destination.

Covariance returns the weighted covariance between the samples of x and y.

sum_i {w_i (x_i - meanX) * (y_i - meanY)} / (sum_j {w_j} - 1)

The lengths of x and y must be equal. If weights is nil then all of the weights are 1. If weights is not nil, then len(x) must equal len(weights).

Code:

fmt.Println("Covariance computes the degree to which datasets move together") fmt.Println("about their mean.") x := []float64{8, -3, 7, 8, -4} y := []float64{10, 2, 2, 4, 1} cov := Covariance(x, y, nil) fmt.Printf("Cov = %.4f\n", cov) fmt.Println("If datasets move perfectly together, the variance equals the covariance") y2 := []float64{12, 1, 11, 12, 0} cov2 := Covariance(x, y2, nil) varX := Variance(x, nil) fmt.Printf("Cov2 is %.4f, VarX is %.4f", cov2, varX)

Output:

Covariance computes the degree to which datasets move together about their mean. Cov = 13.8000 If datasets move perfectly together, the variance equals the covariance Cov2 is 37.7000, VarX is 37.7000

CovarianceMatrix returns the covariance matrix (also known as the variance-covariance matrix) calculated from a matrix of data, x, using a two-pass algorithm.

If weights is not nil the weighted covariance of x is calculated. weights must have length equal to the number of rows in input data matrix and must not contain negative elements. If cov is not nil it must either be zero-sized or have the same number of columns as the input data matrix. cov will be used as the destination for the covariance data. If cov is nil, a new mat64.SymDense is allocated for the destination.

CrossEntropy computes the cross-entropy between the two distributions specified in p and q.

Entropy computes the Shannon entropy of a distribution or the distance between two distributions. The natural logarithm is used.

- sum_i (p_i * log_e(p_i))

Code:

p := []float64{0.05, 0.1, 0.9, 0.05} entP := Entropy(p) q := []float64{0.2, 0.4, 0.25, 0.15} entQ := Entropy(q) r := []float64{0.2, 0, 0, 0.5, 0, 0.2, 0.1, 0, 0, 0} entR := Entropy(r) s := []float64{0, 0, 1, 0} entS := Entropy(s) fmt.Println("Entropy is a measure of the amount of uncertainty in a distribution") fmt.Printf("The second bin of p is very likely to occur. It's entropy is %.4f\n", entP) fmt.Printf("The distribution of q is more spread out. It's entropy is %.4f\n", entQ) fmt.Println("Adding buckets with zero probability does not change the entropy.") fmt.Printf("The entropy of r is: %.4f\n", entR) fmt.Printf("A distribution with no uncertainty has entropy %.4f\n", entS)

Output:

Entropy is a measure of the amount of uncertainty in a distribution The second bin of p is very likely to occur. It's entropy is 0.6247 The distribution of q is more spread out. It's entropy is 1.3195 Adding buckets with zero probability does not change the entropy. The entropy of r is: 1.2206 A distribution with no uncertainty has entropy 0.0000

ExKurtosis returns the population excess kurtosis of the sample. The kurtosis is defined by the 4th moment of the mean divided by the squared variance. The excess kurtosis subtracts 3.0 so that the excess kurtosis of the normal distribution is zero. If weights is nil then all of the weights are 1. If weights is not nil, then len(x) must equal len(weights).

Code:

fmt.Println(`Kurtosis is a measure of the 'peakedness' of a distribution, and the excess kurtosis is the kurtosis above or below that of the standard normal distribution`) x := []float64{5, 4, -3, -2} kurt := ExKurtosis(x, nil) fmt.Printf("ExKurtosis = %.5f\n", kurt) weights := []float64{1, 2, 3, 5} wKurt := ExKurtosis(x, weights) fmt.Printf("Weighted ExKurtosis is %.4f", wKurt)

Output:

Kurtosis is a measure of the 'peakedness' of a distribution, and the excess kurtosis is the kurtosis above or below that of the standard normal distribution ExKurtosis = -5.41200 Weighted ExKurtosis is -0.6779

GeometricMean returns the weighted geometric mean of the dataset

\prod_i {x_i ^ w_i}

This only applies with positive x and positive weights. If weights is nil then all of the weights are 1. If weights is not nil, then len(x) must equal len(weights).

Code:

x := []float64{8, 2, 9, 15, 4} weights := []float64{2, 2, 6, 7, 1} mean := Mean(x, weights) gmean := GeometricMean(x, weights) logx := make([]float64, len(x)) for i, v := range x { logx[i] = math.Log(v) } expMeanLog := math.Exp(Mean(logx, weights)) fmt.Printf("The arithmetic mean is %.4f, but the geometric mean is %.4f.\n", mean, gmean) fmt.Printf("The exponential of the mean of the logs is %.4f\n", expMeanLog)

Output:

The arithmetic mean is 10.1667, but the geometric mean is 8.7637. The exponential of the mean of the logs is 8.7637

HarmonicMean returns the weighted harmonic mean of the dataset

\sum_i {w_i} / ( sum_i {w_i / x_i} )

This only applies with positive x and positive weights. If weights is nil then all of the weights are 1. If weights is not nil, then len(x) must equal len(weights).

Code:

x := []float64{8, 2, 9, 15, 4} weights := []float64{2, 2, 6, 7, 1} mean := Mean(x, weights) hmean := HarmonicMean(x, weights) fmt.Printf("The arithmetic mean is %.5f, but the harmonic mean is %.4f.\n", mean, hmean)

Output:

The arithmetic mean is 10.16667, but the harmonic mean is 6.8354.

Hellinger computes the distance between the probability distributions p and q given by:

\sqrt{ 1 - \sum_i \sqrt{p_i q_i} }

The lengths of p and q must be equal. It is assumed that p and q sum to 1.

Histogram sums up the weighted number of data points in each bin. The weight of data point x[i] will be placed into count[j] if dividers[j] <= x < dividers[j+1]. The "span" function in the floats package can assist with bin creation.

The following conditions on the inputs apply:

- The count variable must either be nil or have length of one less than dividers. - The values in dividers must be sorted (use the sort package). - The x values must be sorted. - If weights is nil then all of the weights are 1. - If weights is not nil, then len(x) must equal len(weights).

Code:

x := make([]float64, 101) for i := range x { x[i] = 1.1 * float64(i) // x data ranges from 0 to 110 } dividers := []float64{0, 7, 20, 100, 1000} fmt.Println(`Histogram counts the amount of data in the bins specified by the dividers. In this data set, there are 7 data points less than 7 (between dividers[0] and dividers[1]), 12 data points between 7 and 20 (dividers[1] and dividers[2]), and 0 data points above 1000. Since dividers has length 5, there will be 4 bins.`) hist := Histogram(nil, dividers, x, nil) fmt.Printf("Hist = %v\n", hist) fmt.Println() fmt.Println("For ease, the floats Span function can be used to set the dividers") nBins := 10 dividers = make([]float64, nBins+1) min := floats.Min(x) max := floats.Max(x) // Increase the maximum divider so that the maximum value of x is contained // within the last bucket. max += 1 floats.Span(dividers, min, max) // Span includes the min and the max. Trim the dividers to create 10 buckets hist = Histogram(nil, dividers, x, nil) fmt.Printf("Hist = %v\n", hist) fmt.Println() fmt.Println(`Histogram also works with weighted data, and allows reusing of the count field in order to avoid extra garbage`) weights := make([]float64, len(x)) for i := range weights { weights[i] = float64(i + 1) } Histogram(hist, dividers, x, weights) fmt.Printf("Weighted Hist = %v\n", hist)

Output:

Histogram counts the amount of data in the bins specified by the dividers. In this data set, there are 7 data points less than 7 (between dividers[0] and dividers[1]), 12 data points between 7 and 20 (dividers[1] and dividers[2]), and 0 data points above 1000. Since dividers has length 5, there will be 4 bins. Hist = [7 12 72 10] For ease, the floats Span function can be used to set the dividers Hist = [11 10 10 10 10 10 10 10 10 10] Histogram also works with weighted data, and allows reusing of the count field in order to avoid extra garbage Weighted Hist = [66 165 265 365 465 565 665 765 865 965]

JensenShannon computes the JensenShannon divergence between the distributions p and q. The Jensen-Shannon divergence is defined as

m = 0.5 * (p + q) JS(p, q) = 0.5 ( KL(p, m) + KL(q, m) )

Unlike Kullback-Liebler, the Jensen-Shannon distance is symmetric. The value is between 0 and ln(2).

KolmogorovSmirnov computes the largest distance between two empirical CDFs. Each dataset x and y consists of sample locations and counts, xWeights and yWeights, respectively.

x and y may have different lengths, though len(x) must equal len(xWeights), and len(y) must equal len(yWeights). Both x and y must be sorted.

Special cases are:

= 0 if len(x) == len(y) == 0 = 1 if len(x) == 0, len(y) != 0 or len(x) != 0 and len(y) == 0

KullbackLeibler computes the Kullback-Leibler distance between the distributions p and q. The natural logarithm is used.

sum_i(p_i * log(p_i / q_i))

Note that the Kullback-Leibler distance is not symmetric; KullbackLeibler(p,q) != KullbackLeibler(q,p)

Code:

```
p := []float64{0.05, 0.1, 0.9, 0.05}
q := []float64{0.2, 0.4, 0.25, 0.15}
s := []float64{0, 0, 1, 0}
klPQ := KullbackLeibler(p, q)
klPS := KullbackLeibler(p, s)
klPP := KullbackLeibler(p, p)
fmt.Println("Kullback-Leibler is one measure of the difference between two distributions")
fmt.Printf("The K-L distance between p and q is %.4f\n", klPQ)
fmt.Println("It is impossible for s and p to be the same distribution, because")
fmt.Println("the first bucket has zero probability in s and non-zero in p. Thus,")
fmt.Printf("the K-L distance between them is %.4f\n", klPS)
fmt.Printf("The K-L distance between identical distributions is %.4f\n", klPP)
// Kullback-Leibler is one measure of the difference between two distributions
// The K-L distance between p and q is 0.8900
// It is impossible for s and p to be the same distribution, because
// the first bucket has zero probability in s and non-zero in p. Thus,
// the K-L distance between them is +Inf
// The K-L distance between identical distributions is 0.0000
```

LinearRegression computes the best-fit line

y = alpha + beta*x

to the data in x and y with the given weights. If origin is true, the regression is forced to pass through the origin.

Specifically, LinearRegression computes the values of alpha and beta such that the total residual

\sum_i w[i]*(y[i] - alpha - beta*x[i])^2

is minimized. If origin is true, then alpha is forced to be zero.

The lengths of x and y must be equal. If weights is nil then all of the weights are 1. If weights is not nil, then len(x) must equal len(weights).

Mahalanobis computes the Mahalanobis distance

D = sqrt((x-y)^T * Σ^-1 * (x-y))

between the vectors x and y given the cholesky decomposition of Σ. Mahalanobis returns NaN if the linear solve fails.

See https://en.wikipedia.org/wiki/Mahalanobis_distance for more information.

Mean computes the weighted mean of the data set.

sum_i {w_i * x_i} / sum_i {w_i}

If weights is nil then all of the weights are 1. If weights is not nil, then len(x) must equal len(weights).

Code:

x := []float64{8.2, -6, 5, 7} mean := Mean(x, nil) fmt.Printf("The mean of the samples is %.4f\n", mean) w := []float64{2, 6, 3, 5} weightedMean := Mean(x, w) fmt.Printf("The weighted mean of the samples is %.4f\n", weightedMean) x2 := []float64{8.2, 8.2, -6, -6, -6, -6, -6, -6, 5, 5, 5, 7, 7, 7, 7, 7} mean2 := Mean(x2, nil) fmt.Printf("The mean of x2 is %.4f\n", mean2) fmt.Println("The weights act as if there were more samples of that number")

Output:

The mean of the samples is 3.5500 The weighted mean of the samples is 1.9000 The mean of x2 is 1.9000 The weights act as if there were more samples of that number

MeanStdDev returns the sample mean and standard deviation

MeanVariance computes the sample mean and variance, where the mean and variance are

\sum_i w_i * x_i / (sum_i w_i) \sum_i w_i (x_i - mean)^2 / (sum_i w_i - 1)

respectively. If weights is nil then all of the weights are 1. If weights is not nil, then len(x) must equal len(weights).

Mode returns the most common value in the dataset specified by x and the given weights. Strict float64 equality is used when comparing values, so users should take caution. If several values are the mode, any of them may be returned.

Moment computes the weighted n^th moment of the samples,

E[(x - μ)^N]

No degrees of freedom correction is done. If weights is nil then all of the weights are 1. If weights is not nil, then len(x) must equal len(weights).

MomentAbout computes the weighted n^th weighted moment of the samples about the given mean \mu,

E[(x - μ)^N]

No degrees of freedom correction is done. If weights is nil then all of the weights are 1. If weights is not nil, then len(x) must equal len(weights).

❖

func Quantile(p float64, c CumulantKind, x, weights []float64) float64

Quantile returns the sample of x such that x is greater than or equal to the fraction p of samples. The exact behavior is determined by the CumulantKind, and p should be a number between 0 and 1. Quantile is theoretically the inverse of the CDF function, though it may not be the actual inverse for all values p and CumulantKinds.

The x data must be sorted in increasing order. If weights is nil then all of the weights are 1. If weights is not nil, then len(x) must equal len(weights).

CumulantKind behaviors:

- Empirical: Returns the lowest value q for which q is greater than or equal to the fraction p of samples

RNoughtSquared returns the coefficient of determination defined as

R₀^2 = \sum_i w[i]*(beta*x[i])^2 / \sum_i w[i]*y[i]^2

for the line

y = beta*x

and the data in x and y with the given weights. RNoughtSquared should only be used for best-fit lines regressed through the origin.

ROC returns paired false positive rate (FPR) and true positive rate (TPR) values corresponding to n cutoffs spanning the relative (or receiver) operator characteristic (ROC) curve obtained when y is treated as a binary classifier for classes with weights.

Cutoffs are equally spaced from eps less than the minimum value of y to the maximum value of y, including both endpoints meaning that the resulting ROC curve will always begin at (0,0) and end at (1,1).

The input y must be sorted, and SortWeightedLabeled can be used in order to sort y together with classes and weights.

For a given cutoff value, observations corresponding to entries in y greater than the cutoff value are classified as false, while those below (or equal to) the cutoff value are classified as true. These assigned class labels are compared with the true values in the classes slice and used to calculate the FPR and TPR.

If weights is nil, all weights are treated as 1.

When n is zero all possible cutoffs are calculated, resulting in fpr and tpr having length one greater than the number of unique values in y. When n is greater than one fpr and tpr will be returned with length n. ROC will panic if n is equal to one or less than 0.

More details about ROC curves are available at https://en.wikipedia.org/wiki/Receiver_operating_characteristic

Code:

```
y := []float64{0.1, 0.35, 0.4, 0.8}
classes := []bool{true, false, true, false}
tpr, fpr := stat.ROC(0, y, classes, nil)
// compute Area Under Curve
auc := integrate.Trapezoidal(fpr, tpr)
fmt.Printf("true positive rate: %v\n", tpr)
fmt.Printf("false positive rate: %v\n", fpr)
fmt.Printf("auc: %v\n", auc)
```

Output:

true positive rate: [0 0.5 0.5 1 1] false positive rate: [0 0 0.5 0.5 1] auc: 0.75

Code:

y := []float64{0, 3, 5, 6, 7.5, 8} classes := []bool{true, false, true, false, false, false} weights := []float64{4, 1, 6, 3, 2, 2} tpr, fpr := stat.ROC(0, y, classes, weights) fmt.Printf("true positive rate: %v\n", tpr) fmt.Printf("false positive rate: %v\n", fpr)

Output:

true positive rate: [0 0.4 0.4 1 1 1 1] false positive rate: [0 0 0.125 0.125 0.5 0.75 1]

Code:

y := []float64{0, 3, 5, 6, 7.5, 8} classes := []bool{true, false, true, false, false, false} tpr, fpr := stat.ROC(0, y, classes, nil) fmt.Printf("true positive rate: %v\n", tpr) fmt.Printf("false positive rate: %v\n", fpr)

Output:

true positive rate: [0 0.5 0.5 1 1 1 1] false positive rate: [0 0 0.25 0.25 0.5 0.75 1]

RSquared returns the coefficient of determination defined as

R^2 = 1 - \sum_i w[i]*(y[i] - alpha - beta*x[i])^2 / \sum_i w[i]*(y[i] - mean(y))^2

for the line

y = alpha + beta*x

and the data in x and y with the given weights.

RSquaredFrom returns the coefficient of determination defined as

R^2 = 1 - \sum_i w[i]*(estimate[i] - value[i])^2 / \sum_i w[i]*(value[i] - mean(values))^2

and the data in estimates and values with the given weights.

The lengths of estimates and values must be equal. If weights is nil then all of the weights are 1. If weights is not nil, then len(values) must equal len(weights).

Skew computes the skewness of the sample data. If weights is nil then all of the weights are 1. If weights is not nil, then len(x) must equal len(weights).

SortWeighted rearranges the data in x along with their corresponding weights so that the x data are sorted. The data is sorted in place. Weights may be nil, but if weights is non-nil then it must have the same length as x.

SortWeightedLabeled rearranges the data in x along with their corresponding weights and boolean labels so that the x data are sorted. The data is sorted in place. Weights and labels may be nil, if either is non-nil it must have the same length as x.

StdDev returns the sample standard deviation.

Code:

x := []float64{8, 2, -9, 15, 4} stdev := StdDev(x, nil) fmt.Printf("The standard deviation of the samples is %.4f\n", stdev) weights := []float64{2, 2, 6, 7, 1} weightedStdev := StdDev(x, weights) fmt.Printf("The weighted standard deviation of the samples is %.4f\n", weightedStdev)

Output:

The standard deviation of the samples is 8.8034 The weighted standard deviation of the samples is 10.5733

StdErr returns the standard error in the mean with the given values.

Code:

x := []float64{8, 2, -9, 15, 4} weights := []float64{2, 2, 6, 7, 1} mean := Mean(x, weights) stdev := StdDev(x, weights) nSamples := floats.Sum(weights) stdErr := StdErr(stdev, nSamples) fmt.Printf("The standard deviation is %.4f and there are %g samples, so the mean\nis likely %.4f ± %.4f.", stdev, nSamples, mean, stdErr)

Output:

The standard deviation is 10.5733 and there are 18 samples, so the mean is likely 4.1667 ± 2.4921.

StdScore returns the standard score (a.k.a. z-score, z-value) for the value x with the givem mean and standard deviation, i.e.

(x - mean) / std

Variance computes the weighted sample variance:

\sum_i w_i (x_i - mean)^2 / (sum_i w_i - 1)

If weights is nil then all of the weights are 1. If weights is not nil, then len(x) must equal len(weights).

Code:

x := []float64{8, 2, -9, 15, 4} variance := Variance(x, nil) fmt.Printf("The variance of the samples is %.4f\n", variance) weights := []float64{2, 2, 6, 7, 1} weightedVariance := Variance(x, weights) fmt.Printf("The weighted variance of the samples is %.4f\n", weightedVariance)

Output:

The variance of the samples is 77.5000 The weighted variance of the samples is 111.7941

❖

```
type CC struct {
// contains filtered or unexported fields
}
```

CC is a type for computing the canonical correlations of a pair of matrices. The results of the canonical correlation analysis are only valid if the call to CanonicalCorrelations was successful.

Code:

package main import ( "fmt" "log" "github.com/gonum/floats" "github.com/gonum/matrix/mat64" "github.com/gonum/stat" ) // symView is a helper for getting a View of a SymDense. type symView struct { sym *mat64.SymDense i, j, r, c int } func (s symView) Dims() (r, c int) { return s.r, s.c } func (s symView) At(i, j int) float64 { if i < 0 || s.r <= i { panic("i out of bounds") } if j < 0 || s.c <= j { panic("j out of bounds") } return s.sym.At(s.i+i, s.j+j) } func (s symView) T() mat64.Matrix { return mat64.Transpose{s} } func main() { // This example is directly analogous to Example 3.5 on page 87 of // Koch, Inge. Analysis of multivariate and high-dimensional data. // Vol. 32. Cambridge University Press, 2013. ISBN: 9780521887939 // bostonData is the Boston Housing Data of Harrison and Rubinfeld (1978) n, _ := bostonData.Dims() var xd, yd = 7, 4 // The variables (columns) of bostonData can be partitioned into two sets: // those that deal with environmental/social variables (xdata), and those // that contain information regarding the individual (ydata). Because the // variables can be naturally partitioned in this way, these data are // appropriate for canonical correlation analysis. The columns (variables) // of xdata are, in order: // per capita crime rate by town, // proportion of non-retail business acres per town, // nitric oxide concentration (parts per 10 million), // weighted distances to Boston employment centres, // index of accessibility to radial highways, // pupil-teacher ratio by town, and // proportion of blacks by town. xdata := bostonData.Slice(0, n, 0, xd) // The columns (variables) of ydata are, in order: // average number of rooms per dwelling, // proportion of owner-occupied units built prior to 1940, // full-value property-tax rate per $10000, and // median value of owner-occupied homes in $1000s. ydata := bostonData.Slice(0, n, xd, xd+yd) // For comparison, calculate the correlation matrix for the original data. var cor mat64.SymDense stat.CorrelationMatrix(&cor, bostonData, nil) // Extract just those correlations that are between xdata and ydata. var corRaw = symView{sym: &cor, i: 0, j: xd, r: xd, c: yd} // Note that the strongest correlation between individual variables is 0.91 // between the 5th variable of xdata (index of accessibility to radial // highways) and the 3rd variable of ydata (full-value property-tax rate per // $10000). fmt.Printf("corRaw = %.4f", mat64.Formatted(corRaw, mat64.Prefix(" "))) // Calculate the canonical correlations. var cc stat.CC err := cc.CanonicalCorrelations(xdata, ydata, nil) if err != nil { log.Fatal(err) } // Unpack cc. ccors := cc.Corrs(nil) pVecs := cc.Left(nil, true) qVecs := cc.Right(nil, true) phiVs := cc.Left(nil, false) psiVs := cc.Right(nil, false) // Canonical Correlation Matrix, or the correlations between the sphered // data. var corSph mat64.Dense corSph.Clone(pVecs) col := make([]float64, xd) for j := 0; j < yd; j++ { mat64.Col(col, j, &corSph) floats.Scale(ccors[j], col) corSph.SetCol(j, col) } corSph.Product(&corSph, qVecs.T()) fmt.Printf("\n\ncorSph = %.4f", mat64.Formatted(&corSph, mat64.Prefix(" "))) // Canonical Correlations. Note that the first canonical correlation is // 0.95, stronger than the greatest correlation in the original data, and // much stronger than the greatest correlation in the sphered data. fmt.Printf("\n\nccors = %.4f", ccors) // Left and right eigenvectors of the canonical correlation matrix. fmt.Printf("\n\npVecs = %.4f", mat64.Formatted(pVecs, mat64.Prefix(" "))) fmt.Printf("\n\nqVecs = %.4f", mat64.Formatted(qVecs, mat64.Prefix(" "))) // Canonical Correlation Transforms. These can be useful as they represent // the canonical variables as linear combinations of the original variables. fmt.Printf("\n\nphiVs = %.4f", mat64.Formatted(phiVs, mat64.Prefix(" "))) fmt.Printf("\n\npsiVs = %.4f", mat64.Formatted(psiVs, mat64.Prefix(" "))) }

CanonicalCorrelations returns a CC which can provide the results of canonical correlation analysis of the input data x and y, columns of which should be interpretable as two sets of measurements on the same observations (rows). These observations are optionally weighted by weights.

Canonical correlation analysis finds associations between two sets of variables on the same observations by finding linear combinations of the two sphered datasets that maximize the correlation between them.

Some notation: let Xc and Yc denote the centered input data matrices x and y (column means subtracted from each column), let Sx and Sy denote the sample covariance matrices within x and y respectively, and let Sxy denote the covariance matrix between x and y. The sphered data can then be expressed as Xc * Sx^{-1/2} and Yc * Sy^{-1/2} respectively, and the correlation matrix between the sphered data is called the canonical correlation matrix, Sx^{-1/2} * Sxy * Sy^{-1/2}. In cases where S^{-1/2} is ambiguous for some covariance matrix S, S^{-1/2} is taken to be E * D^{-1/2} * E^T where S can be eigendecomposed as S = E * D * E^T.

The canonical correlations are the correlations between the corresponding pairs of canonical variables and can be obtained with c.Corrs(). Canonical variables can be obtained by projecting the sphered data into the left and right eigenvectors of the canonical correlation matrix, and these eigenvectors can be obtained with c.Left(m, true) and c.Right(m, true) respectively. The canonical variables can also be obtained directly from the centered raw data by using the back-transformed eigenvectors which can be obtained with c.Left(m, false) and c.Right(m, false) respectively.

The first pair of left and right eigenvectors of the canonical correlation matrix can be interpreted as directions into which the respective sphered data can be projected such that the correlation between the two projections is maximized. The second pair and onwards solve the same optimization but under the constraint that they are uncorrelated (orthogonal in sphered space) to previous projections.

CanonicalCorrelations will panic if the inputs x and y do not have the same number of rows.

The slice weights is used to weight the observations. If weights is nil, each weight is considered to have a value of one, otherwise the length of weights must match the number of observations (rows of both x and y) or CanonicalCorrelations will panic.

More details can be found at https://en.wikipedia.org/wiki/Canonical_correlation or in Chapter 3 of Koch, Inge. Analysis of multivariate and high-dimensional data. Vol. 32. Cambridge University Press, 2013. ISBN: 9780521887939

Corrs returns the canonical correlations, using dst if it is not nil. If dst is not nil and len(dst) does not match the number of columns in the y input matrix, Corrs will panic.

Left returns the left eigenvectors of the canonical correlation matrix if spheredSpace is true. If spheredSpace is false it returns these eigenvectors back-transformed to the original data space. If dst is not nil it must either be zero-sized or be an xd×yd matrix where xd and yd are the number of variables in the input x and y matrices. dst will be used as the destination for the vector data. If dst is nil, a new mat64.Dense is allocated for the destination.

Right returns the right eigenvectors of the canonical correlation matrix if spheredSpace is true. If spheredSpace is false it returns these eigenvectors back-transformed to the original data space. If dst is not nil it must either be zero-sized or be an yd×yd matrix where yd is the number of variables in the input y matrix. dst will be used as the destination for the vector data. If dst is nil, a new mat64.Dense is allocated for the destination.

CumulantKind specifies the behavior for calculating the empirical CDF or Quantile

❖

const ( // Empirical treats the distribution as the actual empirical distribution. Empirical CumulantKind = 1 )

❖

```
type PC struct {
// contains filtered or unexported fields
}
```

PC is a type for computing and extracting the principal components of a matrix. The results of the principal components analysis are only valid if the call to PrincipalComponents was successful.

PrincipalComponents performs a weighted principal components analysis on the matrix of the input data which is represented as an n×d matrix a where each row is an observation and each column is a variable.

PrincipalComponents centers the variables but does not scale the variance.

The weights slice is used to weight the observations. If weights is nil, each weight is considered to have a value of one, otherwise the length of weights must match the number of observations or PrincipalComponents will panic.

PrincipalComponents returns whether the analysis was successful.

Vars returns the column variances of the principal component scores, b * vecs, where b is a matrix with centered columns. Variances are returned in descending order. If dst is not nil it is used to store the variances and returned. Vars will panic if the receiver has not successfully performed a principal components analysis or dst is not nil and the length of dst is not min(n, d).

Vectors returns the component direction vectors of a principal components analysis. The vectors are returned in the columns of a d×min(n, d) matrix. If dst is not nil it must either be zero-sized or be a d×min(n, d) matrix. dst will be used as the destination for the direction vector data. If dst is nil, a new mat64.Dense is allocated for the destination.

Path | Synopsis |
---|---|

combin | Package combin implements routines involving combinatorics (permutations, combinations, etc.). |

distmat | This repository is no longer maintained. |

distmv | This repository is no longer maintained. |

distuv | This repository is no longer maintained. |

samplemv | This repository is no longer maintained. |

sampleuv | This repository is no longer maintained. |

Package stat imports 6 packages (graph) and is imported by 31 packages. Updated 2018-11-25. Refresh now. Tools for package owners.