stats

package
v0.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 8, 2026 License: BSD-3-Clause Imports: 3 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package stats is the first ten minutes of a data problem: look at the numbers, split them, scale them, and check whether two columns move together.

It exists because Go's standard library has none of this, and a data scientist arriving from pandas or scikit-learn hits that wall immediately. Nothing here is novel; all of it is textbook. The value is that it is correct, documented about its edges, and has no dependencies.

The one opinion

Scalers are FITTED and then APPLIED. Standardiser and MinMaxScaler are computed from training data and then applied, unchanged, to validation and test data:

sc := stats.FitStandardiser(train)
trainZ := sc.Transform(train)
testZ := sc.Transform(test) // the TRAINING mean and sd, deliberately

Re-fitting on the test set leaks its distribution into the model and makes every score that follows too optimistic. That mistake is easy to make and impossible to see in the output, so the API makes the correct thing the obvious thing: there is no function that scales a slice in one step.

NaN

Functions here do NOT silently skip NaN. A NaN in the input produces a NaN in the output, because quietly dropping values changes the denominator and the caller is rarely told. Use DropNaN when that is what you mean.

Index

Constants

This section is empty.

Variables

View Source
var ErrEmpty = errors.New("stats: no data")

ErrEmpty is returned when a computation has no data to work with.

View Source
var ErrLengthMismatch = errors.New("stats: samples have different lengths")

ErrLengthMismatch is returned when two samples must be the same length.

View Source
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 DropNaN

func DropNaN(x []float64) (clean []float64, removed int)

DropNaN returns x without its NaN values, and how many were removed. The input is not modified.

func IQR

func IQR(x []float64) float64

IQR is the interquartile range, Q3 − Q1: a spread measure that a few extreme values cannot move, unlike the standard deviation.

func Max

func Max(x []float64) float64

Max returns the largest value, or NaN for an empty slice.

func Mean

func Mean(x []float64) float64

Mean is the arithmetic mean. It returns NaN for an empty slice, since the mean of nothing is not zero.

func Median

func Median(x []float64) float64

Median is the 0.5 quantile.

func Min

func Min(x []float64) float64

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

func Pearson(x, y []float64) (float64, error)

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 PopStdDev

func PopStdDev(x []float64) float64

PopStdDev is the population standard deviation.

func PopVariance

func PopVariance(x []float64) float64

PopVariance is the population variance, dividing by n.

func Quantile

func Quantile(x []float64, q float64) float64

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

func Spearman(x, y []float64) (float64, error)

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

func Split(x []float64, frac float64) (train, test []float64)

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

func SplitIndex(n int, frac float64) int

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 StdDev

func StdDev(x []float64) float64

StdDev is the sample standard deviation: the square root of Variance.

func Variance

func Variance(x []float64) float64

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 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

func RollingFolds(n, k int) []Fold

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

type MinMaxScaler struct {
	Min float64
	Max float64
	// contains filtered or unexported fields
}

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.

func (*MinMaxScaler) Inverse

func (s *MinMaxScaler) Inverse(z []float64) ([]float64, error)

Inverse maps scaled values back to the original units.

func (*MinMaxScaler) Transform

func (s *MinMaxScaler) Transform(x []float64) ([]float64, error)

Transform maps x onto [0,1] using the fitted range. Values outside the fitted range map outside [0,1]; see the type's documentation.

type Standardiser

type Standardiser struct {
	Mean   float64
	StdDev float64
	// contains filtered or unexported fields
}

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.

func (*Standardiser) Inverse

func (s *Standardiser) Inverse(z []float64) ([]float64, error)

Inverse undoes Transform, mapping standardised values back to the original units. Use it to report a prediction in the units a person understands.

func (*Standardiser) Transform

func (s *Standardiser) Transform(x []float64) ([]float64, error)

Transform applies the fitted scaling. It returns a new slice and does not modify x. An unfitted scaler returns ErrNotFitted rather than silently returning the input unchanged.

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

func Describe(x []float64) Summary

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL