# Part 4: look at misclassified evaluation reviews
# Confidence = score of the guessed label minus score of the true label (log scale).
# Selection rule (fixed before looking): the 5 most confident mistakes among
# reviews with at most 30 words, and the 3 most confident mistakes overall.
from common import load_split
from nb import train_nb, score_doc_label, classify_nb

train_docs, train_labels, eval_docs, eval_labels = load_split()
model = train_nb(train_docs, train_labels)

wrong = []
for i, (doc, true) in enumerate(zip(eval_docs, eval_labels)):
    guess = classify_nb(doc, model)
    if guess != true:
        margin = score_doc_label(doc, guess, model) - score_doc_label(doc, true, model)
        wrong.append((margin, i, true, guess))
print('misclassified:', len(wrong))

def show(margin, i, true, guess):
    doc = eval_docs[i]
    print('--- evaluation review', i, '| true:', true, '| guessed:', guess,
          '| words:', len(doc), '| margin:', round(float(margin), 2))
    shown = doc if len(doc) <= 60 else doc[:60]
    print(' '.join(shown) + (' ...' if len(doc) > 60 else ''))
    # words that pushed hardest towards the wrong label
    pushes = []
    for w in set(doc):
        if w in model['vocab']:
            d = model['log_prob'][guess][w] - model['log_prob'][true][w]
            pushes.append((d * doc.count(w), w))
    pushes.sort(reverse=True)
    print('words pushing towards', guess + ':', [(w, round(float(d), 2)) for d, w in pushes[:5]])
    print()

by_margin = sorted(wrong, reverse=True)
short = [m for m in by_margin if len(eval_docs[m[1]]) <= 30]
print()
print('5 most confident mistakes among reviews with at most 30 words')
print()
for m in short[:5]:
    show(*m)
print('3 most confident mistakes overall')
print()
for m in by_margin[:3]:
    show(*m)
