regressio 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +325 -0
- package/dist/index.cjs +2505 -0
- package/dist/index.d.cts +545 -0
- package/dist/index.d.ts +545 -0
- package/dist/index.js +2502 -0
- package/package.json +68 -0
package/README.md
ADDED
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
# regressio
|
|
2
|
+
|
|
3
|
+
Zero-dependency TypeScript regression, classification & statistics library with full statistical outputs, diagnostics, and preprocessing. Ships with an optional Rust/WASM engine for accelerated linear algebra.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
bun add regressio
|
|
9
|
+
# or
|
|
10
|
+
npm install regressio
|
|
11
|
+
# or
|
|
12
|
+
pnpm add regressio
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Quick Start
|
|
16
|
+
|
|
17
|
+
```typescript
|
|
18
|
+
import { LinearRegression } from 'regressio';
|
|
19
|
+
|
|
20
|
+
const model = new LinearRegression();
|
|
21
|
+
model.fit([1, 2, 3, 4, 5], [2.1, 3.9, 6.2, 7.8, 10.1]);
|
|
22
|
+
|
|
23
|
+
console.log(model.coefficients); // [2.02]
|
|
24
|
+
console.log(model.intercept); // 0.06
|
|
25
|
+
console.log(model.predict([6])); // [12.18]
|
|
26
|
+
console.log(model.summary()); // R-style formatted summary table
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## Models
|
|
30
|
+
|
|
31
|
+
### Regression
|
|
32
|
+
|
|
33
|
+
| Model | Class | What it does |
|
|
34
|
+
|-------|-------|--------------|
|
|
35
|
+
| **OLS** | `LinearRegression` | Fits a linear relationship between features and target using Ordinary Least Squares solved via QR decomposition. The foundational regression method. |
|
|
36
|
+
| **Polynomial** | `PolynomialRegression` | Fits non-linear curves by expanding a single feature into polynomial terms (x, x², x³, ...) then applying OLS. |
|
|
37
|
+
| **Ridge (L2)** | `RidgeRegression` | Adds an L2 penalty (sum of squared coefficients) to OLS to handle multicollinearity and prevent overfitting. Shrinks coefficients toward zero but never exactly to zero. |
|
|
38
|
+
| **Lasso (L1)** | `LassoRegression` | Adds an L1 penalty (sum of absolute coefficients) via coordinate descent. Forces some coefficients to exactly zero, performing automatic feature selection. |
|
|
39
|
+
| **Elastic Net** | `ElasticNet` | Combines L1 and L2 penalties. Balances Lasso's feature selection with Ridge's stability for correlated features. |
|
|
40
|
+
| **WLS** | `WeightedRegression` | Weighted Least Squares. Assigns different importance to each observation. Useful when some data points are more reliable than others. |
|
|
41
|
+
| **Robust** | `RobustRegression` | Resistant to outliers. Uses Iteratively Reweighted Least Squares (IRLS) with Huber or Tukey bisquare M-estimators to downweight extreme values. |
|
|
42
|
+
|
|
43
|
+
### Classification
|
|
44
|
+
|
|
45
|
+
| Model | Class | What it does |
|
|
46
|
+
|-------|-------|--------------|
|
|
47
|
+
| **Logistic** | `LogisticRegression` | Binary classification (0/1). Models the probability of class membership using a sigmoid function, fitted via Newton-Raphson/IRLS. |
|
|
48
|
+
| **Multiclass Logistic** | `MulticlassLogisticRegression` | Extends logistic regression to K classes using softmax. Fitted via gradient descent on the cross-entropy loss. |
|
|
49
|
+
| **K-Nearest Neighbors** | `KNearestNeighbors` | Non-parametric method. Predicts by majority vote (classification) or mean (regression) of the k closest training points. Supports Euclidean and Manhattan distances. |
|
|
50
|
+
|
|
51
|
+
### Neural Network
|
|
52
|
+
|
|
53
|
+
| Model | Class | What it does |
|
|
54
|
+
|-------|-------|--------------|
|
|
55
|
+
| **Feedforward NN** | `NeuralNetwork` | Multi-layer perceptron with backpropagation. Configurable hidden layers, activations (relu, sigmoid, tanh, softmax), and learning rate. Supports both regression and classification tasks. |
|
|
56
|
+
|
|
57
|
+
### Usage
|
|
58
|
+
|
|
59
|
+
```typescript
|
|
60
|
+
import {
|
|
61
|
+
LinearRegression,
|
|
62
|
+
PolynomialRegression,
|
|
63
|
+
RidgeRegression,
|
|
64
|
+
LassoRegression,
|
|
65
|
+
ElasticNet,
|
|
66
|
+
WeightedRegression,
|
|
67
|
+
RobustRegression,
|
|
68
|
+
LogisticRegression,
|
|
69
|
+
MulticlassLogisticRegression,
|
|
70
|
+
KNearestNeighbors,
|
|
71
|
+
NeuralNetwork,
|
|
72
|
+
} from 'regressio';
|
|
73
|
+
|
|
74
|
+
// --- Regression ---
|
|
75
|
+
|
|
76
|
+
// OLS: multiple regression
|
|
77
|
+
const ols = new LinearRegression();
|
|
78
|
+
ols.fit([[1, 2], [3, 4], [5, 6]], [10, 22, 34]);
|
|
79
|
+
|
|
80
|
+
// Polynomial: fit a cubic curve
|
|
81
|
+
const poly = new PolynomialRegression({ degree: 3 });
|
|
82
|
+
poly.fit([1, 2, 3, 4, 5], [1, 8, 27, 64, 125]);
|
|
83
|
+
|
|
84
|
+
// Ridge: regularized regression for correlated features
|
|
85
|
+
const ridge = new RidgeRegression({ alpha: 0.5 });
|
|
86
|
+
ridge.fit(X, y);
|
|
87
|
+
|
|
88
|
+
// Lasso: automatic feature selection
|
|
89
|
+
const lasso = new LassoRegression({ alpha: 0.1 });
|
|
90
|
+
lasso.fit(X, y);
|
|
91
|
+
// Some coefficients will be exactly 0
|
|
92
|
+
|
|
93
|
+
// Elastic Net: mix of L1 and L2
|
|
94
|
+
const enet = new ElasticNet({ alpha: 0.1, l1Ratio: 0.5 });
|
|
95
|
+
enet.fit(X, y);
|
|
96
|
+
|
|
97
|
+
// Weighted Least Squares: different reliability per observation
|
|
98
|
+
const wls = new WeightedRegression();
|
|
99
|
+
wls.fit(X, y, weights);
|
|
100
|
+
|
|
101
|
+
// Robust: resistant to outliers
|
|
102
|
+
const robust = new RobustRegression({ method: 'huber' });
|
|
103
|
+
robust.fit(X, y);
|
|
104
|
+
|
|
105
|
+
// --- Classification ---
|
|
106
|
+
|
|
107
|
+
// Binary logistic regression
|
|
108
|
+
const logit = new LogisticRegression();
|
|
109
|
+
logit.fit(X, y); // y must be 0/1
|
|
110
|
+
logit.predictProbability(Xnew); // [0.12, 0.87, ...]
|
|
111
|
+
|
|
112
|
+
// Multiclass logistic regression (softmax)
|
|
113
|
+
const multi = new MulticlassLogisticRegression({ learningRate: 0.05 });
|
|
114
|
+
multi.fit(X, y); // y = 0, 1, 2, ...
|
|
115
|
+
multi.predictProbability(Xnew); // [[0.7, 0.2, 0.1], ...]
|
|
116
|
+
|
|
117
|
+
// K-Nearest Neighbors (classification or regression)
|
|
118
|
+
const knn = new KNearestNeighbors({ k: 5, mode: 'classification' });
|
|
119
|
+
knn.fit(X, y);
|
|
120
|
+
knn.predict(Xnew);
|
|
121
|
+
|
|
122
|
+
// --- Neural Network ---
|
|
123
|
+
|
|
124
|
+
// Regression with a neural network
|
|
125
|
+
const nn = new NeuralNetwork({
|
|
126
|
+
layers: [
|
|
127
|
+
{ units: 16, activation: 'relu' },
|
|
128
|
+
{ units: 8, activation: 'relu' },
|
|
129
|
+
],
|
|
130
|
+
learningRate: 0.01,
|
|
131
|
+
epochs: 200,
|
|
132
|
+
task: 'regression',
|
|
133
|
+
});
|
|
134
|
+
nn.fit(X, y);
|
|
135
|
+
nn.predict(Xnew);
|
|
136
|
+
|
|
137
|
+
// Classification with a neural network
|
|
138
|
+
const clf = new NeuralNetwork({
|
|
139
|
+
layers: [{ units: 10, activation: 'sigmoid' }],
|
|
140
|
+
learningRate: 0.1,
|
|
141
|
+
epochs: 100,
|
|
142
|
+
task: 'classification',
|
|
143
|
+
});
|
|
144
|
+
clf.fit(X, y); // y = 0, 1, 2, ...
|
|
145
|
+
clf.predict(Xnew);
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
## Statistical Outputs
|
|
149
|
+
|
|
150
|
+
Every linear model (OLS, Ridge, Lasso, Elastic Net, WLS, Robust, Polynomial) provides `statistics()` and `summary()`:
|
|
151
|
+
|
|
152
|
+
```typescript
|
|
153
|
+
const stats = model.statistics();
|
|
154
|
+
// {
|
|
155
|
+
// rSquared, -- proportion of variance explained (0 to 1)
|
|
156
|
+
// adjustedRSquared, -- R² penalized for number of predictors
|
|
157
|
+
// standardErrors, -- uncertainty of each coefficient estimate
|
|
158
|
+
// tStatistics, -- coefficient / standard error for each predictor
|
|
159
|
+
// pValues, -- probability of observing the t-stat under H0 (no effect)
|
|
160
|
+
// confidenceIntervals, -- 95% confidence range for each coefficient
|
|
161
|
+
// fStatistic, -- overall model significance test
|
|
162
|
+
// fPValue, -- p-value for the F-test
|
|
163
|
+
// residualStandardError, -- estimated standard deviation of residuals
|
|
164
|
+
// aic, -- Akaike Information Criterion (lower = better fit/complexity trade-off)
|
|
165
|
+
// bic, -- Bayesian Information Criterion (stronger complexity penalty than AIC)
|
|
166
|
+
// degreesOfFreedom, -- n - k (observations minus parameters)
|
|
167
|
+
// nObservations, -- number of data points
|
|
168
|
+
// }
|
|
169
|
+
|
|
170
|
+
console.log(model.summary());
|
|
171
|
+
// Coefficients:
|
|
172
|
+
// Estimate Std. Error t value Pr(>|t|)
|
|
173
|
+
// (Intercept) 0.0600 0.1200 0.50 0.6300
|
|
174
|
+
// x1 2.0200 0.0400 50.20 0.0000 ***
|
|
175
|
+
// ---
|
|
176
|
+
// Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
Binary logistic regression provides classification metrics:
|
|
180
|
+
|
|
181
|
+
```typescript
|
|
182
|
+
const stats = logit.statistics();
|
|
183
|
+
// { accuracy, precision, recall, f1Score, confusionMatrix,
|
|
184
|
+
// pseudoRSquared, logLikelihood, aic, bic }
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
Multiclass logistic regression provides per-class metrics:
|
|
188
|
+
|
|
189
|
+
```typescript
|
|
190
|
+
const stats = multi.statistics();
|
|
191
|
+
// { accuracy, precision (per class), recall (per class),
|
|
192
|
+
// nClasses, logLikelihood }
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
## Diagnostics
|
|
196
|
+
|
|
197
|
+
Functions to validate model assumptions and detect problems.
|
|
198
|
+
|
|
199
|
+
| Function | What it does |
|
|
200
|
+
|----------|--------------|
|
|
201
|
+
| `residualDiagnostics(X, y, yHat)` | Returns raw residuals, studentized residuals, Cook's distance, and leverage for each observation. |
|
|
202
|
+
| `studentizedResiduals(X, y, yHat)` | Residuals scaled by their estimated standard deviation. Values > 2-3 suggest outliers. |
|
|
203
|
+
| `cooksDistance(X, y, yHat)` | Measures how much each observation influences the fitted model. Values > 4/n flag influential points. |
|
|
204
|
+
| `leverage(X)` | Hat matrix diagonal. Measures how far each observation's features are from the center. High leverage = unusual feature values. |
|
|
205
|
+
| `durbinWatson(residuals)` | Tests for autocorrelation in residuals. Returns statistic in [0,4]: ~2 = no autocorrelation, <2 = positive, >2 = negative. Critical for time series. |
|
|
206
|
+
| `breuschPagan(X, residuals)` | Tests for heteroscedasticity (non-constant variance). Low p-value = variance depends on X, meaning standard errors are unreliable. |
|
|
207
|
+
| `shapiroWilk(data)` | Tests whether data follows a normal distribution. Low p-value = non-normal. Important because p-values and CIs assume normal residuals. |
|
|
208
|
+
| `vif(X)` | Variance Inflation Factor for each feature. VIF > 10 signals multicollinearity (features are too correlated). |
|
|
209
|
+
| `correlationMatrix(X)` | Pairwise Pearson correlation matrix. Pairs with |r| > 0.9 suggest redundant features. |
|
|
210
|
+
| `conditionNumber(X)` | Ratio of largest to smallest singular value of X. Values > 30 signal numerical instability from multicollinearity. |
|
|
211
|
+
|
|
212
|
+
```typescript
|
|
213
|
+
import {
|
|
214
|
+
residualDiagnostics, leverage, cooksDistance, studentizedResiduals,
|
|
215
|
+
durbinWatson, breuschPagan, shapiroWilk,
|
|
216
|
+
vif, correlationMatrix, conditionNumber,
|
|
217
|
+
} from 'regressio';
|
|
218
|
+
|
|
219
|
+
const diag = residualDiagnostics(X, y, yHat);
|
|
220
|
+
const dw = durbinWatson(model.residuals());
|
|
221
|
+
const bp = breuschPagan(X, model.residuals());
|
|
222
|
+
const sw = shapiroWilk(model.residuals());
|
|
223
|
+
const vifs = vif(X);
|
|
224
|
+
const corr = correlationMatrix(X);
|
|
225
|
+
const kappa = conditionNumber(X);
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
## Preprocessing
|
|
229
|
+
|
|
230
|
+
Functions to prepare data before fitting models.
|
|
231
|
+
|
|
232
|
+
| Function | What it does |
|
|
233
|
+
|----------|--------------|
|
|
234
|
+
| `standardize(X)` | Z-score normalization: transforms each feature to mean=0, std=1. Essential for Lasso/Ridge/Elastic Net and neural networks. |
|
|
235
|
+
| `unstandardize(X, params)` | Reverses standardization back to the original scale. |
|
|
236
|
+
| `normalize(X)` | Min-max scaling: transforms each feature to [0, 1] range. |
|
|
237
|
+
| `unnormalize(X, params)` | Reverses normalization back to the original scale. |
|
|
238
|
+
| `oneHotEncode(column, categories?, dropFirst?)` | Converts categorical values to binary columns. Use `dropFirst=true` to avoid the multicollinearity trap. |
|
|
239
|
+
| `polynomialFeatures(X, degree)` | Generates polynomial terms (x, x², x³, ...) for each feature. Use with `LinearRegression` for polynomial fitting with multiple features. |
|
|
240
|
+
| `interactionFeatures(X, pairs?)` | Generates interaction terms (xi * xj) for all or specified feature pairs. |
|
|
241
|
+
| `dropMissing(X, y?)` | Removes rows containing NaN or null values. |
|
|
242
|
+
| `imputeMean(X)` | Replaces NaN values with the column mean. |
|
|
243
|
+
| `imputeMedian(X)` | Replaces NaN values with the column median. More robust to outliers than mean imputation. |
|
|
244
|
+
|
|
245
|
+
```typescript
|
|
246
|
+
import {
|
|
247
|
+
standardize, unstandardize, normalize, unnormalize,
|
|
248
|
+
oneHotEncode, polynomialFeatures, interactionFeatures,
|
|
249
|
+
dropMissing, imputeMean, imputeMedian,
|
|
250
|
+
} from 'regressio';
|
|
251
|
+
|
|
252
|
+
const { transformed, means, stds } = standardize(X);
|
|
253
|
+
const original = unstandardize(transformed, { means, stds });
|
|
254
|
+
const { transformed: normed, mins, maxs } = normalize(X);
|
|
255
|
+
const dummies = oneHotEncode(['cat', 'dog', 'cat'], undefined, true);
|
|
256
|
+
const polyX = polynomialFeatures(X, 3);
|
|
257
|
+
const interX = interactionFeatures(X);
|
|
258
|
+
const clean = dropMissing(X, y);
|
|
259
|
+
const imputed = imputeMean(X);
|
|
260
|
+
```
|
|
261
|
+
|
|
262
|
+
## Prediction Intervals
|
|
263
|
+
|
|
264
|
+
Functions to quantify prediction uncertainty.
|
|
265
|
+
|
|
266
|
+
| Function | What it does |
|
|
267
|
+
|----------|--------------|
|
|
268
|
+
| `confidenceInterval(X, y, yHat, newX, newYHat)` | Confidence interval on the **mean** prediction. Answers: "where is the true regression line?" Narrower near the center of the training data. |
|
|
269
|
+
| `predictionInterval(X, y, yHat, newX, newYHat)` | Prediction interval for a **new individual** observation. Always wider than the confidence interval because it includes observation noise. |
|
|
270
|
+
| `bootstrapCoefficients(X, y, nBootstrap?)` | Non-parametric bootstrap: resamples data with replacement, refits the model many times, and returns empirical confidence intervals on coefficients. No distributional assumptions. |
|
|
271
|
+
|
|
272
|
+
```typescript
|
|
273
|
+
import { confidenceInterval, predictionInterval, bootstrapCoefficients } from 'regressio';
|
|
274
|
+
|
|
275
|
+
const ci = confidenceInterval(X, y, yHat, newX, newYHat);
|
|
276
|
+
// [{ predicted, lower, upper }, ...]
|
|
277
|
+
|
|
278
|
+
const pi = predictionInterval(X, y, yHat, newX, newYHat);
|
|
279
|
+
// Always wider than ci
|
|
280
|
+
|
|
281
|
+
const boot = bootstrapCoefficients(X, y, 1000);
|
|
282
|
+
// { coefficients, confidenceIntervals, standardErrors }
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
## Advanced: Matrix Class
|
|
286
|
+
|
|
287
|
+
Low-level matrix operations for advanced users. Backed by `Float64Array` in row-major order.
|
|
288
|
+
|
|
289
|
+
```typescript
|
|
290
|
+
import { Matrix } from 'regressio';
|
|
291
|
+
|
|
292
|
+
const A = Matrix.fromArray([[1, 2], [3, 4]]);
|
|
293
|
+
const B = Matrix.identity(2);
|
|
294
|
+
const C = A.multiply(B);
|
|
295
|
+
console.log(C.determinant()); // -2
|
|
296
|
+
console.log(C.trace()); // 5
|
|
297
|
+
console.log(C.transpose().toArray());
|
|
298
|
+
```
|
|
299
|
+
|
|
300
|
+
## WASM Engine (Optional)
|
|
301
|
+
|
|
302
|
+
For faster matrix operations on large datasets, build and load the Rust/WASM engine. When active, `Matrix.multiply()`, QR decomposition, Cholesky decomposition, and back-substitution are dispatched to compiled Rust code.
|
|
303
|
+
|
|
304
|
+
```bash
|
|
305
|
+
cd rust && wasm-pack build --target bundler --out-dir ../pkg
|
|
306
|
+
```
|
|
307
|
+
|
|
308
|
+
```typescript
|
|
309
|
+
import { useWasmEngine, useTypescriptEngine, isWasmActive, getEngine } from 'regressio';
|
|
310
|
+
|
|
311
|
+
// Load WASM engine (async, loads the .wasm file)
|
|
312
|
+
await useWasmEngine();
|
|
313
|
+
console.log(isWasmActive()); // true
|
|
314
|
+
|
|
315
|
+
// All subsequent matrix operations use WASM
|
|
316
|
+
const model = new LinearRegression();
|
|
317
|
+
model.fit(X, y); // QR decomposition runs in Rust
|
|
318
|
+
|
|
319
|
+
// Switch back to pure TypeScript
|
|
320
|
+
useTypescriptEngine();
|
|
321
|
+
```
|
|
322
|
+
|
|
323
|
+
## License
|
|
324
|
+
|
|
325
|
+
MIT
|