Public
Edited
Jan 30, 2022
1 fork
2 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
//Credit to: https://gist.github.com/stephband/8237123

function Viterbi(data) {
var V = [{}]; //V acts as the "alpha"
var path = {};
// Initialize base cases (t == 0)
for(var i=0;i<data.states.length;i++) {
var state = data.states[i];
V[0][state] = data.start_probability[state] * data.emission_probability[state][data.observations[0]];
path[state] = [state]; //Backpointer
}

// Run Viterbi for t > 0
for(var t=1;t<data.observations.length;t++) {
V.push({}); //Push adds new item to array
var newpath = {};

//For each state
for(var i=0;i<data.states.length;i++) {
var state = data.states[i];
var max = [0,null];
for(var j=0;j<data.states.length;j++) {
var state0 = data.states[j];
// Calculate the probablity
var calc = V[t-1][state0]
* data.transition_probability[state0][state]
* data.emission_probability[state][data.observations[t]];
if(calc > max[0])
max = [calc,state0];
}
V[t][state] = max[0];
newpath[state] = path[max[1]].concat(state);
/*
Backpointer
max[1] = [state0]
concat combines two arrays together, yielding a new array with [state0,state]
Recall that we only need to know the store the maximum of the previous hidden state for each one of the
two current hidden states
*/
}
path = newpath;
}

var max = [0,null];
for(var i=0;i<data.states.length;i++) {
var state = data.states[i];
var calc = V[data.observations.length-1][state];
if(calc > max[0]) max = [calc,state];
}
return [max[0], path[max[1]]];
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
result = Viterbi({
states: [
'Low',
'High'
],
observations: [
'Rain',
'Dry'
],
start_probability: {
'Low': 0.4,
'High': 0.6
},
transition_probability: {
'Low' : {'Low': 0.3, 'High': 0.7},
'High' : {'High': 0.8, 'Low': 0.2}
},
emission_probability: {
'Low' : {'Rain': 0.6, 'Dry': 0.4},
'High' : {'Rain': 0.4, 'Dry': 0.6}
}
});
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more