# Optional task: learning curve
# Training sizes are 10%, 20%, ..., 100% of the 9531 training reviews.
# The reviews are shuffled once with seed 572 (picked before looking at results)
# and each bigger training set contains the smaller ones.
# Evaluation: the same 2383 evaluation reviews as in Part 3. alpha = 1.
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from common import load_split
from nb import train_nb, classify_documents, accuracy

SEED = 572
train_docs, train_labels, eval_docs, eval_labels = load_split()
n = len(train_docs)

rng = np.random.default_rng(SEED)
order = rng.permutation(n)

sizes = []
accs = []
print('percent  training reviews  accuracy')
for pct in range(10, 101, 10):
    k = int(round(pct / 100 * n))
    idx = order[:k]
    docs = [train_docs[i] for i in idx]
    labs = [train_labels[i] for i in idx]
    model = train_nb(docs, labs)
    acc = accuracy(eval_labels, classify_documents(eval_docs, model))
    sizes.append(k)
    accs.append(acc)
    print(pct, ' ', k, ' ', round(acc, 4))

fig, ax = plt.subplots(figsize=(7, 4.5))
ax.plot(sizes, accs, marker='o', color='#2b5d5a')
ax.set_xlabel('Number of training reviews')
ax.set_ylabel('Accuracy on the evaluation set')
ax.set_title('Learning curve (seed 572)')
ax.set_xticks(sizes)
ax.set_xticklabels([str(s) for s in sizes], rotation=45, ha='right')
ax.grid(True, alpha=0.3)
fig.tight_layout()
fig.savefig('media/fig_learning_curve.png', dpi=150)
print('saved media/fig_learning_curve.png')
