Calculate the perplexity for the y_true and y_pred. Compute the Perplexity which useful in predicting language model accuracy in Natural Language Processing (NLP.) Perplexity is measure of how certain the model in its predictions. Perplexity Loss = exp(-1/N (Σ ln(p(x))) R
(
y_true: np.ndarray, y_pred: np.ndarray, epsilon: float = 1e-7
)
| 482 | |
| 483 | |
| 484 | def perplexity_loss( |
| 485 | y_true: np.ndarray, y_pred: np.ndarray, epsilon: float = 1e-7 |
| 486 | ) -> float: |
| 487 | """ |
| 488 | Calculate the perplexity for the y_true and y_pred. |
| 489 | |
| 490 | Compute the Perplexity which useful in predicting language model |
| 491 | accuracy in Natural Language Processing (NLP.) |
| 492 | Perplexity is measure of how certain the model in its predictions. |
| 493 | |
| 494 | Perplexity Loss = exp(-1/N (Σ ln(p(x))) |
| 495 | |
| 496 | Reference: |
| 497 | https://en.wikipedia.org/wiki/Perplexity |
| 498 | |
| 499 | Args: |
| 500 | y_true: Actual label encoded sentences of shape (batch_size, sentence_length) |
| 501 | y_pred: Predicted sentences of shape (batch_size, sentence_length, vocab_size) |
| 502 | epsilon: Small floating point number to avoid getting inf for log(0) |
| 503 | |
| 504 | Returns: |
| 505 | Perplexity loss between y_true and y_pred. |
| 506 | |
| 507 | >>> y_true = np.array([[1, 4], [2, 3]]) |
| 508 | >>> y_pred = np.array( |
| 509 | ... [[[0.28, 0.19, 0.21 , 0.15, 0.15], |
| 510 | ... [0.24, 0.19, 0.09, 0.18, 0.27]], |
| 511 | ... [[0.03, 0.26, 0.21, 0.18, 0.30], |
| 512 | ... [0.28, 0.10, 0.33, 0.15, 0.12]]] |
| 513 | ... ) |
| 514 | >>> float(perplexity_loss(y_true, y_pred)) |
| 515 | 5.0247347775367945 |
| 516 | >>> y_true = np.array([[1, 4], [2, 3]]) |
| 517 | >>> y_pred = np.array( |
| 518 | ... [[[0.28, 0.19, 0.21 , 0.15, 0.15], |
| 519 | ... [0.24, 0.19, 0.09, 0.18, 0.27], |
| 520 | ... [0.30, 0.10, 0.20, 0.15, 0.25]], |
| 521 | ... [[0.03, 0.26, 0.21, 0.18, 0.30], |
| 522 | ... [0.28, 0.10, 0.33, 0.15, 0.12], |
| 523 | ... [0.30, 0.10, 0.20, 0.15, 0.25]],] |
| 524 | ... ) |
| 525 | >>> perplexity_loss(y_true, y_pred) |
| 526 | Traceback (most recent call last): |
| 527 | ... |
| 528 | ValueError: Sentence length of y_true and y_pred must be equal. |
| 529 | >>> y_true = np.array([[1, 4], [2, 11]]) |
| 530 | >>> y_pred = np.array( |
| 531 | ... [[[0.28, 0.19, 0.21 , 0.15, 0.15], |
| 532 | ... [0.24, 0.19, 0.09, 0.18, 0.27]], |
| 533 | ... [[0.03, 0.26, 0.21, 0.18, 0.30], |
| 534 | ... [0.28, 0.10, 0.33, 0.15, 0.12]]] |
| 535 | ... ) |
| 536 | >>> perplexity_loss(y_true, y_pred) |
| 537 | Traceback (most recent call last): |
| 538 | ... |
| 539 | ValueError: Label value must not be greater than vocabulary size. |
| 540 | >>> y_true = np.array([[1, 4]]) |
| 541 | >>> y_pred = np.array( |
nothing calls this directly
no outgoing calls
no test coverage detected