Skip to content

Commit 4af0222

Browse files
committed
best path: performance improvement by only computing argmax once on matrix
1 parent 106ea6a commit 4af0222

File tree

1 file changed

+22
-24
lines changed

1 file changed

+22
-24
lines changed

src/BestPath.py

Lines changed: 22 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -4,36 +4,34 @@
44

55

66
def ctcBestPath(mat, classes):
7-
"implements best path decoding as shown by Graves (Dissertation, p63)"
7+
"implements best path decoding as shown by Graves (Dissertation, p63)"
88

9-
# dim0=t, dim1=c
10-
maxT, maxC = mat.shape
11-
label = ''
12-
blankIdx = len(classes)
13-
lastMaxIdx = maxC # init with invalid label
9+
# get list of char indices along best path
10+
best_path = np.argmax(mat, axis=1)
1411

15-
for t in range(maxT):
16-
maxIdx = np.argmax(mat[t, :])
12+
# collapse best path and map char indices to string
13+
blank_idx = len(classes)
14+
last_char_idx = blank_idx
15+
res = ''
16+
for char_idx in best_path:
17+
if char_idx != last_char_idx and char_idx != blank_idx:
18+
res += classes[char_idx]
19+
last_char_idx = char_idx
1720

18-
if maxIdx != lastMaxIdx and maxIdx != blankIdx:
19-
label += classes[maxIdx]
20-
21-
lastMaxIdx = maxIdx
22-
23-
return label
21+
return res
2422

2523

2624
def testBestPath():
27-
"test decoder"
28-
classes = 'ab'
29-
mat = np.array([[0.4, 0, 0.6], [0.4, 0, 0.6]])
30-
print('Test best path decoding')
31-
expected = ''
32-
actual = ctcBestPath(mat, classes)
33-
print('Expected: "' + expected + '"')
34-
print('Actual: "' + actual + '"')
35-
print('OK' if expected == actual else 'ERROR')
25+
"test decoder"
26+
classes = 'ab'
27+
mat = np.array([[0.4, 0, 0.6], [0.4, 0, 0.6]])
28+
print('Test best path decoding')
29+
expected = ''
30+
actual = ctcBestPath(mat, classes)
31+
print('Expected: "' + expected + '"')
32+
print('Actual: "' + actual + '"')
33+
print('OK' if expected == actual else 'ERROR')
3634

3735

3836
if __name__ == '__main__':
39-
testBestPath()
37+
testBestPath()

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy