Score an answer against the truth

Score an answer against the truth

Scale AI LLM Interview Question

Scale AI grades a question-answering model by comparing each answer with the correct one. Marking an answer right or wrong is too blunt, since an answer of "Paris, France" when the truth is "Paris" deserves more credit than a wrong city does. The token-level F1 gives that partial credit, and it works on the words of each answer rather than on the whole string.

Write a function f1(prediction, truth) that lower-cases both, splits them on whitespace, and returns their F1 as defined below. A word that appears twice on both sides is shared twice. Return 0.0 when they share nothing.

Note

Precision=shared wordswords in the prediction\text{Precision} = \frac{\text{shared words}}{\text{words in the prediction}}
Recall=shared wordswords in the truth\text{Recall} = \frac{\text{shared words}}{\text{words in the truth}}
F1=2×Precision×RecallPrecision+Recall\text{F1} = 2 \times \frac{\text{Precision} \times \text{Recall}}{\text{Precision} + \text{Recall}}

Asked of

  • AI Engineer
  • ML Engineer
  • Data Scientist

Example 1

Input

prediction = "Paris , France", truth = "Paris"

Output

0.5

Example 2

Input

prediction = "the cat", truth = "the cat"

Output

1

Example 3

Input

prediction = "dogs", truth = "cats"

Output

0

Explanation

In the first example the prediction has 3 words and the truth has 1, and they share "paris". Precision is 1/3 and recall is 1/1, which gives an F1 of 0.5.

Submit also runs 3 hidden test cases that check edge cases.

Similar questions