tabular

package
v0.8.1 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2026 License: MIT Imports: 11 Imported by: 0

README

tabular

A standard-library-only, single-predictor ordinary least squares workflow for small tabular experiments. Import github.com/Alifarid0011/gobook/tabular from GoBook v0.2.0 or later. This package does not implement scikit-learn parity, multiple regression, preprocessing, cross-validation, or GPU training.

data, err := tabular.ReadCSV(reader, "hours", "score")
// Check err after each call; the runnable notebook does so.
train, heldout, err := tabular.Split(data, 6)
model, err := tabular.Fit(train)
defer model.Close()
predicted, err := model.Predict(heldout.X)
metrics, err := tabular.Evaluate(heldout.Y, predicted)

Run the complete synthetic CSV example (including fit, honest held-out metrics, JSON round-trip, and close):

go test ./tabular -run Example -v

Open ../examples/tabular.gobook.json for the full notebook, including os.Create("model.json"), tabular.Load from os.Open, and predictions.csv. The dependency is pinned to GoBook v0.2.0. Its metrics are computed from its synthetic fixture when run; they are not evidence about real-world predictive performance.

Split(data, trainCount) makes independent copies of the first trainCount rows and the remaining rows. It is deterministic and preserves order; it does not claim to produce a random or representative sample. For randomly sampled experiments, shuffle paired rows externally using a recorded procedure before splitting. For time series, consider whether this simple regression is appropriate at all. Fit only the training data; evaluate only held-out predictions. Dataset slices remain caller-owned and must not be mutated during calls. Fit retains no training data.

ReadCSV requires distinct named predictor/response columns, unique nonempty headers, matching record widths, finite numeric values, and at least one data row. It ignores unselected columns. Standard CSV quoting and embedded newlines apply; blank records are errors, including trailing blank records. Missing and invalid observations are errors, with row and column context; there is no imputation. Bound untrusted CSV readers externally (for example through a limited upload). Fit additionally requires at least two rows and a varying predictor.

Fit uses centered, scaled float64 arithmetic with compensated sums. The persisted model keeps the training origins, scales, centered means and normalized slope to avoid rebuilding a potentially unstable intercept. Ordinary fit and prediction use float64; prediction falls back to 256-bit standard-library arithmetic only when intermediate operations overflow. This is floating-point numerical software: rounding and conditioning still matter, and numerically degenerate predictors or unrepresentable slopes/predictions are errors. No accuracy promise extends beyond float64 precision. Benchmark the supplied BenchmarkFit and BenchmarkPredict on your own machine with go test ./tabular -bench . -benchmem.

Evaluate(actual, predicted) returns MAE, RMSE, and R². MAE and RMSE retain the response's units. R² can be negative; with constant actual values it is 1 for exactly correct predictions and 0 otherwise. Nonfinite values, empty or mismatched slices, overflow, and numerically unresolved response variation are errors. The metric accumulations are scaled to avoid squaring large raw values.

model.Save(io.Writer) and tabular.Load(io.Reader) leave stream ownership with the caller; check write, flush and close errors. The JSON schema is gobook.ols, version 1, with numeric x_origin, y_origin, x_scale, y_scale, x_mean, y_mean, and slope parameters. Its prediction formula is:

y_origin + y_scale * (y_mean + slope * ((x - x_origin)/x_scale - x_mean))

Load accepts at most 64 KiB including whitespace, rejects unsupported schemas/versions, unknown/missing/duplicate/null fields, invalid scales, nonfinite parameters, and trailing content. The schema version is independent of the GoBook release version. Round-tripping preserves the fitted float64 representation and predictions.

Model fields are private. Do not copy a Model. Predict, Save and Close are safe to call concurrently; Close waits for an active call, clears state, and makes later prediction or save fail. Repeated close succeeds. An uninitialized zero Model cannot predict or save. This lifecycle is explicit even though the current model owns only memory.

Documentation

Overview

Package tabular implements a small, deterministic, single-predictor OLS workflow. All observations must be finite. No rows are silently dropped or imputed.

Example
d, _ := ReadCSV(strings.NewReader("x,y\n1,3\n2,5\n3,7\n4,9\n5,11\n"), "x", "y")
train, test, _ := Split(d, 3)
model, _ := Fit(train)
defer model.Close()
predicted, _ := model.Predict(test.X)
score, _ := Evaluate(test.Y, predicted)
var saved bytes.Buffer
_ = model.Save(&saved)
restored, _ := Load(&saved)
defer restored.Close()
again, _ := restored.Predict(test.X)
fmt.Printf("held-out predictions: %v; restored: %v\n", predicted, again)
fmt.Printf("MAE %.1f RMSE %.1f R2 %.1f\n", score.MAE, score.RMSE, score.R2)
Output:
held-out predictions: [9 11]; restored: [9 11]
MAE 0.0 RMSE 0.0 R2 1.0

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Split

func Split(d Dataset, trainCount int) (Dataset, Dataset, error)

Split copies the first trainCount rows into training data and the remaining rows into held-out data. It preserves order and never shuffles. Both are nonempty. Choose or shuffle row order externally when sequential holdout is inappropriate.

Types

type Dataset

type Dataset struct{ X, Y []float64 }

Dataset pairs one numeric predictor X with a numeric response Y. Callers own the slices and must not mutate them during a function call.

func ReadCSV

func ReadCSV(r io.Reader, predictor, target string) (Dataset, error)

ReadCSV extracts two distinct named numeric columns. Other columns are ignored. Headers must be nonempty and unique; every row must match the header width. Blank records are errors; quoted embedded newlines are supported. Values follow strconv.ParseFloat syntax; missing and nonfinite values are errors. The caller is responsible for bounding the reader for untrusted CSV input.

type Metrics

type Metrics struct {
	MAE  float64 `json:"mae"`
	RMSE float64 `json:"rmse"`
	R2   float64 `json:"r2"`
}

Metrics reports mean absolute error, root mean squared error and coefficient of determination. For constant actual values, R2 is 1 for exact predictions, otherwise 0. Other R2 values may be negative.

func Evaluate

func Evaluate(actual, predicted []float64) (Metrics, error)

Evaluate scores held-out actual values against predictions, without fitting. All values must be finite and slices must be nonempty with equal lengths.

type Model

type Model struct {
	// contains filtered or unexported fields
}

Model is a fitted single-predictor ordinary least squares model. It must not be copied. Predict, Save and Close may be called concurrently. The zero value is unusable. Close is idempotent and invalidates further Predict and Save calls.

func Fit

func Fit(d Dataset) (*Model, error)

Fit learns from d only. It requires at least two observations and a varying predictor. Scaled centered sums with compensated accumulation limit float64 overflow and rounding error. Numerically degenerate or unrepresentable slopes are rejected. No training slices are retained.

func Load

func Load(r io.Reader) (*Model, error)

Load reads one model of at most 64 KiB, including whitespace. Missing, unknown, duplicate, nonfinite or invalid fields and trailing JSON are rejected. The caller owns and closes r. Version 1 describes scaled centered float64 OLS.

func (*Model) Close

func (m *Model) Close() error

Close releases the fitted state. It is safe to call repeatedly.

func (*Model) Predict

func (m *Model) Predict(x []float64) ([]float64, error)

Predict returns fresh predictions. Empty, nonfinite, or unrepresentable inputs produce an error and no partial output. Extreme overflowing intermediates use a bounded-precision fallback; ordinary observations use float64 arithmetic.

func (*Model) Save

func (m *Model) Save(w io.Writer) error

Save writes a schema-versioned JSON model. The caller owns and closes w.

Jump to

Keyboard shortcuts

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