Documentation
¶
Index ¶
- Constants
- Variables
- func Adjust(cs []Correlation, alpha float64)
- func BenjaminiHochberg(p []float64, alpha float64) (q []float64, reject []bool)
- func CorrelationPValue(r float64, n int) float64
- func DropNaN(x []float64) (clean []float64, removed int)
- func IQR(x []float64) float64
- func Max(x []float64) float64
- func Mean(x []float64) float64
- func Median(x []float64) float64
- func Min(x []float64) float64
- func Pearson(x, y []float64) (float64, error)
- func PopStdDev(x []float64) float64
- func PopVariance(x []float64) float64
- func Quantile(x []float64, q float64) float64
- func Spearman(x, y []float64) (float64, error)
- func Split(x []float64, frac float64) (train, test []float64)
- func SplitIndex(n int, frac float64) int
- func StdDev(x []float64) float64
- func TwoSidedP(t float64, df int) float64
- func Variance(x []float64) float64
- type Correlation
- type Fold
- type MinMaxScaler
- type Standardiser
- type Summary
- type TrendTest
Examples ¶
Constants ¶
const DefaultAlpha = 0.05
DefaultAlpha is the conventional significance level and false discovery rate: 0.05.
const MinCorrelationSamples = 20
MinCorrelationSamples is the number of aligned observations Correlate needs before it reports anything.
Twenty is where a bare |r| >= 0.5 rule's false-positive rate on independent noise falls to about the nominal two-sided 5% (it is roughly 50% at n = 4, 31% at n = 6 and 20% at n = 8). With df = 18 the t-test still has useful power: a true |ρ| near 0.6 is detected at α = 0.05 about 80% of the time. Lowering it does not find more relationships; it invents them.
Variables ¶
var ErrEmpty = errors.New("stats: no data")
ErrEmpty is returned when a computation has no data to work with.
var ErrLengthMismatch = errors.New("stats: samples have different lengths")
ErrLengthMismatch is returned when two samples must be the same length.
var ErrNotFitted = errors.New("stats: scaler has not been fitted")
ErrNotFitted is returned by a scaler that has not been fitted to any data.
Functions ¶
func Adjust ¶ added in v0.6.0
func Adjust(cs []Correlation, alpha float64)
Adjust applies Benjamini–Hochberg at alpha across every correlation in cs, setting each Q and Significant in place. Use it when one analysis tests many pairs: k series give k(k-1)/2 tests, and a per-test 5% error rate compounds.
func BenjaminiHochberg ¶ added in v0.6.0
BenjaminiHochberg controls the false discovery rate across a family of m tests at level alpha. It returns, aligned with p, the adjusted q-values and whether each hypothesis is rejected (q <= alpha).
The q-values use the step-up form q(i) = min over j >= i of (m/j)·p(j), clamped to 1, which keeps them monotone in p. An alpha outside (0, 1] is replaced by DefaultAlpha.
Example ¶
package main
import (
"fmt"
"github.com/org-runink/runi/stats"
)
func main() {
p := []float64{0.001, 0.008, 0.039, 0.041, 0.042, 0.06}
_, keep := stats.BenjaminiHochberg(p, 0.05)
fmt.Println(keep)
}
Output: [true true false false false false]
func CorrelationPValue ¶ added in v0.6.0
CorrelationPValue is the two-sided p-value for a Pearson r on n paired observations, under the null that the true correlation is zero:
t = r·sqrt(n-2)/sqrt(1-r²), df = n-2
It returns 1 (no evidence) when n < 3 or r is NaN, and 0 for |r| = 1.
func DropNaN ¶
DropNaN returns x without its NaN values, and how many were removed. The input is not modified.
func IQR ¶
IQR is the interquartile range, Q3 − Q1: a spread measure that a few extreme values cannot move, unlike the standard deviation.
func Mean ¶
Mean is the arithmetic mean. It returns NaN for an empty slice, since the mean of nothing is not zero.
func Min ¶
Min and Max return the smallest and largest value. Both return NaN for an empty slice, and propagate a NaN present in the input.
func Pearson ¶
Pearson is the linear correlation coefficient between x and y, in [-1,1].
It measures LINEAR association only: a perfect parabola through the origin has a Pearson correlation near zero. Reach for Spearman when the relationship may be monotonic but not straight.
func PopVariance ¶
PopVariance is the population variance, dividing by n.
func Quantile ¶
Quantile returns the q-th quantile of x for q in [0,1], using linear interpolation between order statistics — the same definition as NumPy's default and R's type 7, so a number computed here matches one computed there.
It does not modify x: the data is copied before sorting.
func Spearman ¶
Spearman is the rank correlation: Pearson applied to the ranks, with ties given their average rank. It detects any monotonic relationship, straight or not.
func Split ¶
Split cuts x into a training and a test part at SplitIndex, preserving order. The returned slices share x's backing array; copy them before modifying either one.
func SplitIndex ¶
SplitIndex returns the index at which to cut a series so that `frac` of it is training data, for an ORDERED split.
Use this for time series and anything else where order carries information. Shuffling a time series before splitting lets the model see the future, which inflates every score that follows and is the single most common way a forecasting result turns out to be wrong.
It returns 0 when there is not enough data to leave at least one observation on each side.
func TwoSidedP ¶ added in v0.6.0
TwoSidedP returns P(|T| >= |t|) for T distributed Student-t with df degrees of freedom, by the identity P(|T| >= |t|) = I_{df/(df+t²)}(df/2, 1/2), where I is the regularised incomplete beta function. It returns 1 for df < 1 or a NaN t, and 0 for an infinite t.
func Variance ¶
Variance is the SAMPLE variance, dividing by n-1. Use PopVariance when the slice is the whole population rather than a sample from it. Fewer than two values gives NaN.
Types ¶
type Correlation ¶ added in v0.6.0
type Correlation struct {
R float64 `json:"r"` // Pearson r over the aligned window
N int `json:"n"` // aligned observations r was computed on
P float64 `json:"p"` // two-sided p-value of r against ρ = 0, n-2 df
// Q is the Benjamini–Hochberg adjusted p-value, set by Adjust. Zero until
// a family correction has been applied.
Q float64 `json:"q,omitempty"`
// Significant is q <= alpha once Adjust has run, otherwise p <= DefaultAlpha.
Significant bool `json:"significant"`
}
Correlation is a Pearson coefficient together with the evidence that makes it a finding rather than a coincidence.
func Correlate ¶ added in v0.6.0
func Correlate(a, b []float64) (c Correlation, ok bool)
Correlate returns the Pearson correlation of a and b over their overlapping leading window (the first min(len(a), len(b)) values), with its sample size and two-sided p-value.
ok is false when the overlap is below MinCorrelationSamples, or when r is undefined because either series is constant over the window. A caller that ignores ok gets a zero Correlation, which is not significant.
type Fold ¶
type Fold struct {
TrainStart, TrainEnd int // [TrainStart, TrainEnd)
TestStart, TestEnd int // [TestStart, TestEnd)
}
Fold is one split of a cross-validation: the index ranges to train on and to validate against.
func RollingFolds ¶
RollingFolds returns k expanding-window folds over n ordered observations: train on everything up to a point, validate on what comes next, then move the point forward.
This is cross-validation for data with an order. Standard k-fold shuffles, which for a time series means training on Thursday to predict Wednesday — the scores look excellent and mean nothing. Each fold here only ever trains on data that precedes its validation window.
It returns nil when n is too small to make k folds that each have something to train on and something to test.
type MinMaxScaler ¶
MinMaxScaler rescales a column onto [0,1] by its observed range.
It is the right choice when a bounded input is required and the wrong choice when outliers matter: one extreme value compresses everything else toward a single point. Standardiser is more robust to that; neither is robust to a value outside the fitted range, which Transform will map outside [0,1] rather than clip. Clipping silently would hide that the new data does not look like the training data, which is usually the most useful thing to know.
func FitMinMax ¶
func FitMinMax(x []float64) *MinMaxScaler
FitMinMax computes the range of x. A constant column maps to zero.
type Standardiser ¶
Standardiser rescales a column to zero mean and unit standard deviation, z = (x − mean) / sd.
Fit it on training data and apply it, unchanged, everywhere else. Its fields are exported so a fitted scaler can be stored alongside a model and reloaded with it — a model is only valid for the scaling it was trained under.
func FitStandardiser ¶
func FitStandardiser(x []float64) *Standardiser
FitStandardiser computes the mean and sample standard deviation of x.
A constant column has zero spread and cannot be standardised; its scaler leaves values unchanged rather than dividing by zero, so a constant feature becomes a column of zeros after centring instead of a column of NaNs that poisons everything downstream.
type Summary ¶
type Summary struct {
N int
NaN int // values that were NaN, excluded from every figure below
Mean float64
StdDev float64 // sample standard deviation
Min float64
Q1 float64
Median float64
Q3 float64
Max float64
}
Summary is what Describe reports: the shape of a column at a glance.
func Describe ¶
Describe summarises a column, the way you would look at it first.
Unlike the rest of this package, Describe DOES exclude NaN — and tells you how many it excluded in Summary.NaN, so the omission is visible rather than silent. N counts the values actually used.
type TrendTest ¶ added in v0.6.0
type TrendTest struct {
Slope float64 `json:"slope"`
// StdErr is the standard error of the slope. It is 0 when there is no
// residual variance to estimate it from — too few points, or an exact
// line — and NaN when the series contains one, because a missing value
// makes the spread genuinely unknown rather than zero. See Trend.
StdErr float64 `json:"std_err"`
T float64 `json:"t"`
P float64 `json:"p"` // two-sided p-value against slope = 0, n-2 df
N int `json:"n"`
}
TrendTest is an ordinary-least-squares slope of a series against its index, with the test of that slope against zero.
func Trend ¶ added in v0.6.0
Trend fits y against its index (0, 1, 2, …) by ordinary least squares and tests the slope against zero. P is 1 when the series is too short for a residual variance (n < 3) or is constant; an exact non-flat line has P = 0.
A slope is never "rising" just because it is not exactly zero: on noise the fitted slope is essentially never zero. Use Rising and Falling, which ask the test.
A NaN anywhere in y propagates: Slope, StdErr and T come back NaN and P comes back 1, so Rising and Falling are both false. Trend does not drop or interpolate missing values, because which of those is right depends on what the gap means, and it is not a decision this function can make for the caller. Clean the series first, or check the result with math.IsNaN. The one thing Trend will not do is report a defined standard error for a series it could not measure.
Example ¶
package main
import (
"fmt"
"github.com/org-runink/runi/stats"
)
func main() {
weekly := []float64{12, 14, 13, 15, 17, 16, 18, 20, 19, 21}
t := stats.Trend(weekly)
fmt.Printf("slope %.2f per week, rising: %v\n", t.Slope, t.Rising(stats.DefaultAlpha))
}
Output: slope 0.96 per week, rising: true