Session 10 workshop: good news, bad news, or neither?: solutions

The solved steps. Each highlighted piece is what went in a ___ blank. Run the file with these answers and every step prints ✓ with what the result means.

# ── Step 1: load the sentences and take a first look ──────────────────
# Open step-1.png: how many sentences of each label?
try:
    news = pd.read_csv(HERE / "phrasebank.csv")
    print(news.sample(5, random_state=1).to_string())
    counts = news["label"].value_counts()
    print(counts)
    share_neutral = counts["neutral"] / len(news)
    counts.plot.bar(figsize=(5, 3.5), title="How many sentences of each kind?", rot=0)
    plt.tight_layout(); plt.savefig(HERE / "step-1.png"); plt.close()
    check(1, round(share_neutral, 3), 0.614, "Which pandas method counts how often each value appears?",
          "61 % of the sentences are neutral. A 'model' that always says neutral is right 61 % of the time: "
          "every model today must beat that.")
except Exception as e:
    stuck(1, e)


# ── Step 2: text → numbers, way 1: the bag of words ───────────────────
# CountVectorizer makes one column per word of the vocabulary; each cell
# counts how often that word appears in that sentence. Open step-2.png.
try:
    bag = CountVectorizer()
    X_bag = bag.fit_transform(news["sentence"])
    rows, cols = X_bag.shape
    zeros = 1 - X_bag.nnz / (rows * cols)
    print("bag of words:", rows, "rows ×", cols, "columns;", round(100 * zeros, 2), "% of the cells are 0")
    words_used = (X_bag > 0).sum(axis=1).A1          # how many different words each sentence uses
    plt.figure(figsize=(6, 3.5)); plt.hist(words_used, bins=40)
    plt.title(f"Words used per sentence, out of {cols} columns"); plt.xlabel("different words in the sentence")
    plt.tight_layout(); plt.savefig(HERE / "step-2.png"); plt.close()
    check(2, cols, 6057, "The verb for models, plus _transform: it learns the words AND makes the table.",
          "More columns than rows, and almost every cell is 0: each sentence uses only a handful of the words.")
except Exception as e:
    stuck(2, e)


# ── Step 3: cosine similarity by hand ─────────────────────────────────
# cos = (a · b) / (length of a × length of b). 1 = same direction, 0 = nothing in common.
try:
    i, j = 172, 404
    a = X_bag[i].toarray()[0]
    b = X_bag[j].toarray()[0]
    cos = (a * b).sum() / (np.sqrt((a * a).sum()) * np.sqrt((b * b).sum()))
    print("A:", news["sentence"][i]); print("B:", news["sentence"][j])
    sk = cosine_similarity(X_bag[i], X_bag[j])[0, 0]
    print("by hand:", round(cos, 3), "  scikit-learn:", round(sk, 3))
    check(3, round(cos, 3), round(sk, 3), "The length of b, like the length of a: square root of the sum of b times b.",
          "Same number as scikit-learn. A and B share words (operating, profit, EUR, from), so the bag of words finds them close.")
except Exception as e:
    stuck(3, e)


# ── Step 4: text → numbers, way 2: embeddings ─────────────────────────
# A sentence model (EmbeddingGemma, by Google) turned each sentence into 768
# numbers, so that sentences with a SIMILAR MEANING get similar numbers.
# It was run once for you: embeddings.npy.
try:
    E = np.load(HERE / "embeddings.npy")
    print("embeddings:", E.shape[0], "rows ×", E.shape[1], "columns")
    i, j = 361, 2171
    bag_cos = cosine_similarity(X_bag[i], X_bag[j])[0, 0]
    emb_cos = cosine_similarity(E[[i]], E[[j]])[0, 0]
    print("A:", news["sentence"][i]); print("B:", news["sentence"][j])
    print("bag of words:", round(bag_cos, 2), "  embeddings:", round(emb_cos, 2))
    check(4, bool(emb_cos > 0.5 and bag_cos < 0.1), True, "Same shape as E[[i]], for sentence j.",
          "A and B share NO word, so the bag of words sees nothing in common. Both say 'the numbers went down': "
          "the embedding sees it.")
except Exception as e:
    stuck(4, e)


# ── Step 5: the closest sentences, two ways ───────────────────────────
# For one sentence, find the 3 most similar others, with words and with meaning.
# Then open step-5.png: similarity of six sentences, bright = similar.
try:
    q = 2050
    print("Sentence:", news["sentence"][q])
    for name, S in [("bag of words", cosine_similarity(X_bag[q], X_bag)[0]),
                    ("embeddings", cosine_similarity(E[[q]], E)[0])]:
        S[q] = -1                                  # not itself
        top3 = np.argsort(S)[-3:]
        print(" ", name)
        for k in top3[::-1]:
            print(f"    {S[k]:.2f}  {news['label'][k]:8}  {news['sentence'][k]}")
    six = [2050, 2021, 2093, 361, 172, 404]       # 3 'went down', 3 'went up'
    fig, ax = plt.subplots(1, 2, figsize=(10, 4.2))
    for k, (name, M) in enumerate([("bag of words", cosine_similarity(X_bag[six])), ("embeddings", cosine_similarity(E[six]))]):
        ax[k].imshow(M, vmin=0, vmax=1, cmap="viridis"); ax[k].set_title(name)
        ax[k].set_xticks(range(6)); ax[k].set_yticks(range(6))
    plt.tight_layout(); plt.savefig(HERE / "step-5.png"); plt.close()
    for k, p in enumerate(six):
        print(f"  {k}  {news['label'][p]:8}  {news['sentence'][p]}")
    check(5, int(top3[-1]), 2021, "The 3 LARGEST similarities are at the end of argsort: [-3:]",
          "The bag of words finds the same WORDS, and its closest sentence says the opposite (EPS improved). "
          "The embeddings put the sentence with the same meaning first; one positive is still close: "
          "same topic is not yet the same sentiment.")
except Exception as e:
    stuck(5, e)


# ── Step 6: a classifier on the bag of words ──────────────────────────
# Keep 30 % of the sentences for the test. stratify keeps the same share of each label in both parts.
try:
    y = news["label"]
    tr, te = train_test_split(news.index, test_size=0.3, random_state=0, stratify=y)
    vec = CountVectorizer().fit(news["sentence"][tr])         # the vocabulary comes from training only
    model_bag = LogisticRegression(max_iter=3000)
    # your line: fit model_bag on vec.transform(news["sentence"][tr]) and y[tr]
    model_bag.fit(vec.transform(news["sentence"][tr]), y[tr])
    acc_bag = model_bag.score(vec.transform(news["sentence"][te]), y[te])
    print("always 'neutral':", round((y[te] == "neutral").mean(), 3), "  bag of words:", round(acc_bag, 3))
    check(6, round(acc_bag, 3), 0.882, "One line: model_bag.fit(X, y) with the training rows.",
          "Much better than always saying neutral. Each word gets a weight for each label.")
except Exception as e:
    stuck(6, e)


# ── Step 7: the same classifier on the embeddings ─────────────────────
try:
    model_emb = LogisticRegression(max_iter=3000).fit(E[tr], y[tr])
    acc_emb = model_emb.score(E[te], y[te])
    print("bag of words:", round(acc_bag, 3), "  embeddings:", round(acc_emb, 3))
    check(7, round(acc_emb, 3), 0.935, "Score on the TEST rows: E[te], y[te]",
          "Same model, better numbers in: the embedding already 'knows' that fell, dropped and declined mean the same.")
except Exception as e:
    stuck(7, e)


# ── Step 8: PICTURE — how many labelled sentences do you need? ────────
# Train on only 50, 100, 200, 500 sentences, then on all, and test each time.
# Open step-8.png.
try:
    sizes = [50, 100, 200, 500, len(tr)]
    rng = np.random.default_rng(0)
    curve = {"bag of words": [], "embeddings": []}
    for n in sizes:
        small = rng.choice(tr, size=n, replace=False)
        v = CountVectorizer().fit(news["sentence"][small])
        curve["bag of words"].append(LogisticRegression(max_iter=3000)
                                     .fit(v.transform(news["sentence"][small]), y[small])
                                     .score(v.transform(news["sentence"][te]), y[te]))
        curve["embeddings"].append(LogisticRegression(max_iter=3000).fit(E[small], y[small]).score(E[te], y[te]))
    plt.figure(figsize=(6, 4))
    for name, accs in curve.items():
        plt.plot(sizes, accs, marker="o", label=name)
    plt.axhline((y[te] == "neutral").mean(), color="grey", linestyle="--", label="always neutral")
    plt.xscale("log"); plt.xlabel("labelled sentences used for training"); plt.ylabel("test accuracy")
    plt.legend(); plt.tight_layout(); plt.savefig(HERE / "step-8.png"); plt.close()
    print(pd.DataFrame(curve, index=sizes).round(3))
    check(8, round(curve["embeddings"][3], 3), 0.913, "Each time, draw n training sentences: size=n",
          "With only 200 labelled sentences, the embeddings already beat the bag of words trained on all 1,584. "
          "That is the magic: the model learned language from millions of sentences before it saw ours.")
except Exception as e:
    stuck(8, e)


# ── Step 9: the four models from the lecture, on words and on meaning ─
# Open step-9.png (the grey line: always say 'neutral').
try:
    from sklearn.neighbors import KNeighborsClassifier
    from sklearn.tree import DecisionTreeClassifier
    from sklearn.ensemble import RandomForestClassifier
    models = {"kNN (5 neighbours)": KNeighborsClassifier(5),
              "logistic regression": LogisticRegression(max_iter=3000),
              "decision tree": DecisionTreeClassifier(random_state=0),
              "random forest": RandomForestClassifier(300, random_state=0)}
    inputs = {"bag of words": (vec.transform(news["sentence"][tr]), vec.transform(news["sentence"][te])),
              "embeddings": (E[tr], E[te])}
    results = {}
    for rep, (A, B) in inputs.items():
        for name, model in models.items():
            results[(name, rep)] = model.fit(A, y[tr]).score(B, y[te])
    table = pd.Series(results).unstack().round(3)
    print(table)
    table.plot.barh(figsize=(7, 4), xlim=(0.5, 1), title="Test accuracy, four models × two ways")
    plt.axvline((y[te] == "neutral").mean(), color="grey", linestyle="--")
    plt.tight_layout(); plt.savefig(HERE / "step-9.png"); plt.close()
    check(9, round(table.loc["logistic regression", "embeddings"], 3), 0.935,
          "Fit on the training rows, then score: model.fit(A, y[tr])",
          "Logistic regression is best on both. kNN works on embeddings but not on word counts: distances "
          "between word counts mean little. One tree does better on words (one word like 'decreased' can decide) "
          "than on embeddings, where one of 768 numbers means nothing alone.")
except Exception as e:
    stuck(9, e)


# ═══ ★ Faster? Three more steps ═══════════════════════════════════

# ── ★ Step 10: which words push a sentence to 'negative'? ─────────────
# The bag-of-words model has one row of weights per label. Sort the 'negative' row.
try:
    labels = list(model_bag.classes_)
    w = pd.Series(model_bag.coef_[labels.index("negative")], index=vec.get_feature_names_out()).sort_values()
    top5 = list(w.index[-5:])
    print("most 'negative' words:", top5[::-1])
    check(10, top5[-1], "decreased", "The last five of a sorted Series: [-5:]",
          "The model found real finance vocabulary on its own, from the labels only.")
except Exception as e:
    stuck(10, e)


# ── ★ Step 11: which mistakes? The confusion matrix (session 10) ──────
try:
    from sklearn.metrics import confusion_matrix
    order = ["negative", "neutral", "positive"]
    pred = model_emb.predict(E[te])
    cm = pd.DataFrame(confusion_matrix(y[te], pred, labels=order), index=order, columns=order)
    print("rows = truth, columns = prediction"); print(cm)
    plt.figure(figsize=(4.5, 4)); plt.imshow(cm, cmap="Blues")
    for r in range(3):
        for c in range(3):
            plt.text(c, r, cm.iloc[r, c], ha="center", va="center",
                     color="white" if cm.iloc[r, c] > cm.values.max() / 2 else "black")
    plt.xticks(range(3), order); plt.yticks(range(3), order); plt.xlabel("prediction"); plt.ylabel("truth")
    plt.tight_layout(); plt.savefig(HERE / "step-11.png"); plt.close()
    recall_neg = cm.loc["negative", "negative"] / cm.loc["negative"].sum()
    check(11, round(recall_neg, 3), 0.912, "Recall: of all the truly negative sentences, which share did we find? Divide by the row total.",
          "Most mistakes are between neutral and the other two; positive and negative are rarely confused.")
except Exception as e:
    stuck(11, e)


# ── ★ Step 12: kNN with cosine on the embeddings, by hand ─────────────
# For one test sentence: the 5 most similar training sentences vote.
try:
    q = te[0]
    sims = cosine_similarity(E[[q]], E[tr])[0]
    nearest = tr[np.argsort(sims)[-5:]]
    vote = y[nearest].value_counts().idxmax()
    print("sentence:", news["sentence"][q]); print("vote:", vote, "  truth:", y[q])
    for k in nearest[::-1]:
        print(f"    {news['label'][k]:8} {news['sentence'][k]}")
    best = float(round(cosine_similarity(E[[q]], E[[nearest[-1]]])[0, 0], 3))
    check(12, best, float(round(sims.max(), 3)), "The 5 LARGEST similarities are at the end of argsort: [-5:]",
          "kNN with embeddings: find the sentences that mean the same, and copy their label.")
except Exception as e:
    stuck(12, e)