(sentences, V, start_idx, end_idx, smoothing=1)
| 17 | |
| 18 | |
| 19 | def get_bigram_probs(sentences, V, start_idx, end_idx, smoothing=1): |
| 20 | # structure of bigram probability matrix will be: |
| 21 | # (last word, current word) --> probability |
| 22 | # we will use add-1 smoothing |
| 23 | # note: we'll always ignore this from the END token |
| 24 | bigram_probs = np.ones((V, V)) * smoothing |
| 25 | for sentence in sentences: |
| 26 | for i in range(len(sentence)): |
| 27 | |
| 28 | if i == 0: |
| 29 | # beginning word |
| 30 | bigram_probs[start_idx, sentence[i]] += 1 |
| 31 | else: |
| 32 | # middle word |
| 33 | bigram_probs[sentence[i-1], sentence[i]] += 1 |
| 34 | |
| 35 | # if we're at the final word |
| 36 | # we update the bigram for last -> current |
| 37 | # AND current -> END token |
| 38 | if i == len(sentence) - 1: |
| 39 | # final word |
| 40 | bigram_probs[sentence[i], end_idx] += 1 |
| 41 | |
| 42 | # normalize the counts along the rows to get probabilities |
| 43 | bigram_probs /= bigram_probs.sum(axis=1, keepdims=True) |
| 44 | return bigram_probs |
| 45 | |
| 46 | |
| 47 |
no outgoing calls
no test coverage detected