Skip to content

Commit

Permalink
ENH vectorized Viterbi decoding
Browse files Browse the repository at this point in the history
For (20 states, 30k samples) data it makes StructuredPerceptron.fit 4x faster
  • Loading branch information
kmike authored and larsmans committed Aug 3, 2013
1 parent 1e4134d commit aa27b20
Showing 1 changed file with 5 additions and 7 deletions.
12 changes: 5 additions & 7 deletions seqlearn/_decode.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,15 +48,13 @@ def viterbi(Phi, trans, init, final):
dp[0, :] = init + Phi[0, :]

backp = np.empty((n_samples, n_states), dtype=np.int32)
idx = np.arange(n_states)

for i in xrange(1, n_samples):
for k in xrange(n_states):
# XXX there's probably a vectorized way to do this
# (with outer products?)
cand = dp[i - 1] + trans[:, k] + Phi[i, k]
best = cand.argmax()
backp[i, k] = best
dp[i, k] = cand[best]
candidates = trans.T + Phi[i, :].reshape((n_states, 1)) + dp[i - 1, :]
backp_i = np.argmax(candidates, axis=1)
backp[i, :] = backp_i
dp[i, :] = candidates[idx, backp_i]

dp[-1, :] += final

Expand Down

0 comments on commit aa27b20

Please sign in to comment.