Skip to content

Instantly share code, notes, and snippets.

View richwandell's full-sized avatar
:shipit:
Coding

Rich Wandell richwandell

:shipit:
Coding
View GitHub Profile
@richwandell
richwandell / kalman.js
Created August 22, 2016 00:37
Simple 1d kalman filter
var cest, pest = 0, mea, kg, eest = 1, emea = 1;
function kalman(m){
mea = m;
kg = eest / (eest + emea);
cest = pest + kg * (mea - pest);
pest = cest;
eest = (emea * eest) / (emea + eest);
return cest;
}
var linreg = (function(numbers){
var xsum = 0, ysum = 0, xysum = 0, x2sum = 0, m, b;
for(var i = 0; i < numbers.length; i++){
xsum += i;
ysum += numbers[i];
xysum += i * numbers[i];
x2sum += Math.pow(i, 2);
}
m = (numbers.length * xysum - xsum * ysum) / (numbers.length * x2sum - Math.pow(xsum, 2));
b = (ysum - m * xsum) / numbers.length;
@richwandell
richwandell / knn.js
Last active May 6, 2017 17:15
k nearest neighbor
function knn(s){
//Normalize sample
var s0 = (s[0] - min_X) / (max_X - min_X);
var s1 = (s[1] - min_X) / (max_X - min_X);
//Find nearest neighbors
var c1 = false;
var c2 = false;
var distance;
function kMeans(c){
var center, i, j, new_clusters = [], new_error = centroids.map(function(){return 0;}),
x, y, clu, dp, closest, closest_distance, distance, same;
centroids = [];
//Determine the center point of each cluster
for(i = 0; i < c.length; i++){
clu = c[i];
x = 0;
y = 0;
for(j = 0; j < clu.length; j++){
@richwandell
richwandell / neuralnetwork.js
Created March 5, 2017 05:30
Neural Network using math.js
function NeuralNetwork(){
this.inputLayerSize = 2;
this.outputLayerSize = 1;
this.hiddenLayerSize = 3;
this.W1 = math.randomInt([this.inputLayerSize, this.hiddenLayerSize])
.map(function(row){
return row.map(function(el){ return Math.random(); });
});
this.W2 = math.randomInt([this.hiddenLayerSize, this.outputLayerSize])
.map(function(row){
epoch(data){
//keep track of how many times we go through the dataset
this.ni++;
const N = data.length;
let bGrad = 0;
let mGrad = 0;
for(let i = 0; i < N; i ++){
const x = data[i][0];
const y = data[i][1];
const diff = (y - this.line(x));
epoch(d){
//keep track of how many times we go through the dataset
this.ni++;
//Shuffle our data first
let data = this.shuffle(d);
const N = data.length;
for(let i = 0; i < N; i ++){
const x = data[i][0];
const y = data[i][1];
sigmoid(x, c1 = 1, c2 = 0) {
return 1 / (1 + Math.pow(Math.E, -((c1 * x) - c2)));
}
derivative(x) {
let sig = this.sigmoid(x);
return sig * (1 - sig);
}
cost(X, y) {
@richwandell
richwandell / kalman.js
Created February 5, 2018 00:58
nd kalman filter
var cest,
pest = math.ones(2),
mea,
kg,
eest = math.ones(2),
emea = math.ones(2);
function kalman(m){
mea = m;
@richwandell
richwandell / huffman.js
Created October 8, 2018 14:55
Huffman Coding
buildHuffmanTree(charData) {
//Sort by lowest frequency
let cmp = (a, b) => {
if(a.fre < b.fre) {
return -1;
}
return 1;
};
//initially sorted list of nodes
let data = charData