Skip to content

Instantly share code, notes, and snippets.

@itrav
Created April 24, 2018 10:18
Show Gist options
  • Save itrav/0da0102480006354211b9135229a17b5 to your computer and use it in GitHub Desktop.
Save itrav/0da0102480006354211b9135229a17b5 to your computer and use it in GitHub Desktop.
// Console API
const print = o => console.log(JSON.stringify(o));
const printm = A => console.log(A.map(row => row.join("\t")).join("\n"));
// Matrix API
//1
const trans = A => A[0].map((_, j) => A.map(row => row[j]));
//2
const sum = (A, B) => A.map((row, i) => row.map((_, j) => A[i][j] + B[i][j]));
//3
const mult = (k, A) => A.map(row => row.map(a => k * a));
//4
const dotprod = (a, b) => a.reduce((p, _, j) => p + a[j] * b[j], 0);
//5
const prod = (A, B) => ((B_ = trans(B)) => A.map(row => B_.map(col => dotprod(row, col))))();
//6
const minor = (A, r, c) => A.filter((_, i) => i != r).map(row => row.filter((_, j) => j != c));
//7
const det = A => A[0].length == 1 ? A[0][0] : A[0].reduce((d, a, j) => d + Math.pow(-1, j) * a * det(minor(A, 0, j)), 0);
//8
const inv = A => mult(1 / det(A), trans(A.map((row, i) => row.map((_, j) => Math.pow(-1, i + j) * det(minor(A, i, j))))));
// Stat API
//9
const mean = xs => ((n = xs.length) => xs.reduce((m, x) => m + x / n, 0))();
//10
const sd = xs => ((n = xs.length, m = mean(xs)) => Math.sqrt(mean(xs.map(x => Math.pow(x - m, 2))) * n / (n - 1)))();
//11
const norm = xs => ((m = mean(xs), s = sd(xs)) => xs.map(x => (x - m) / s))();
// Regression API
//12
const regcoeff = (xs, ys) => ((X = xs.map(x => [1, x]), X_ = trans(X), XX = prod(X_, X), Y = [ys]) => prod(prod(Y, X), inv(XX))[0])();
// Examples
print(regcoeff([1,2,3,4],[3,5,7,10]));
// => [0.5, 2.3]
// see: http://m.wolframalpha.com/input/?i=linear+regression+%5B%5B1%2C3%5D%2C+%5B2%2C5%5D%2C+%5B3%2C+7%5D%2C+%5B4%2C+10%5D%5D
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment