cat /en/the-bag-and-the-network/
MDN-121:39
SERIES Inside the Puppet · Workshop B

The bag and the network

· Artificial Intelligence · 6 min read

Is a review positive or negative? The simplest way to decide is the bag of words: you count the words in the sentence, each one has a learned weight, and you add them up. “great” pushes towards positive, “awful” towards negative. Order does not matter: for the bag, “the food was not good” and “not the food, good was” are the same sentence.

The book’s Workshop B puts the recurrent networks of chapter 9 to the test on two real problems, the daily sales of a shop and the sentiment of 3,000 English reviews from Amazon, IMDb and Yelp. In both the lesson is the same: before celebrating a network, you compare it with a simple model. On the reviews the opponent is the bag of words, and the network is an LSTM that reads the sentence word after word and decides at the end.

DEMO The bag and the network · about this demo · full screen ↗

Both of the Workshop’s models, trained with seed 2026, run in the page. Type a sentence: on the left you see the two probabilities and the weight the bag gives to each word, on the right the LSTM as it reads, with what it would say if the sentence ended after each word. At the bottom, the match on the 300 test sentences and the bag’s heaviest words.

Three experiments

1. good and not good. Press “1” twice. For the bag, “the food was good” is 56% positive and “the food was not good” 43%: “not” weighs −0.56 and almost cancels the +0.46 of “good”, but the sentence stays on the fence. The LSTM, instead, says 100% and 0%. Look at its curve: after “not” it collapses to zero and “good” does not bring it back up. It has learned that “not” changes the meaning of what follows, something the bag cannot represent.

2. not bad. Press “2”. “not bad”, in English, is a compliment. The bag gives it 23% positive, the LSTM zero: both get it wrong, and the LSTM with more confidence. Of the 235 training sentences that contain “not”, 82% are negative, and “not bad” appears only once: the network has learned a simpler rule than the real one, “not” means negative. A network learns what the data show it, not what we know.

3. Who wins the match. Press “3”. On the 300 test sentences the bag, with 1,927 parameters, gets 82.7% of them right; the LSTM, with 156,609, 81.0%; the bidirectional LSTM 79.7%. The simple model wins. Review sentences are short and almost always direct, and cases like “not good”, where order matters, are too few to make a difference. This is exactly why the simple opponent must always be put on the field.

The same experiment in Python

The code downloads the 3,000 sentences from the book’s repository, builds the vocabulary and trains the Workshop’s three models with early stopping on the validation set. It takes a couple of minutes on a laptop.

import os
os.makedirs("recensioni", exist_ok=True)                 # the 3,000 sentences, from the book's repository
for nome in ["amazon_cells", "imdb", "yelp"]:
    os.system(f"wget -q -P recensioni https://raw.githubusercontent.com/mid079/"
              f"deep-learning-teoria-pratica/main/dati/recensioni/{nome}_labelled.txt")

import re
import random
import torch
import torch.nn as nn
import torch.nn.functional as F

frasi = []                                             # (sentence, 1 if positive)
for nome in ["amazon_cells", "imdb", "yelp"]:
    for riga in open(f"recensioni/{nome}_labelled.txt", encoding="utf-8"):
        riga = riga.strip()
        if riga:                                       # skip empty lines
            testo, etichetta = riga.rsplit("\t", 1)    # the sentence, then the tab, then 0 or 1
            frasi.append((testo, int(etichetta)))
print(len(frasi), sum(e for _, e in frasi))
# 3000 1500
random.Random(2026).shuffle(frasi)                     # shuffle, with our seed
add, ver, test = frasi[:2400], frasi[2400:2700], frasi[2700:]

def parole(t):
    return re.findall(r"[a-z']+", t.lower())           # lower case, only letters and apostrophes

from collections import Counter

conta = Counter(p for t, _ in add for p in parole(t))  # how many times each word appears
voc = ["<pad>", "<ign>"] + [p for p, n in conta.items() if n >= 2]
stoi = {p: i for i, p in enumerate(voc)}
V = len(voc)
print(len(conta), V)
# 4564 1926
def tensori(dati):
    seq = [torch.tensor([stoi.get(p, 1) for p in parole(t)] or [1]) for t, _ in dati]
    lunghezze = torch.tensor([len(x) for x in seq])
    X = nn.utils.rnn.pad_sequence(seq, batch_first=True)   # pads them all with the 0 of <pad>
    Y = torch.tensor([e for _, e in dati])
    return X, lunghezze, Y

Xa, La, Ya = tensori(add)
Xv, Lv, Yv = tensori(ver)
Xt, Lt, Yt = tensori(test)
class Sacco(nn.Module):
    def __init__(self):
        super().__init__()
        self.uscita = nn.Linear(V, 1)                  # one weight for each word

    def forward(self, X, lunghezze):
        conti = torch.zeros(len(X), V).scatter_add_(1, X, torch.ones(X.shape))
        conti[:, 0] = 0                                # the padding does not count
        return self.uscita(conti).squeeze(-1)          # one logit: positive or negative?
class Sentimento(nn.Module):
    def __init__(self, tipo="lstm", bi=False, D=64, H=64, dropout=0.3):
        super().__init__()
        tipi = {"lstm": nn.LSTM, "gru": nn.GRU}
        self.embedding = nn.Embedding(V, D, padding_idx=0)
        self.rete = tipi[tipo](D, H, batch_first=True, bidirectional=bi)
        self.drop = nn.Dropout(dropout)
        self.uscita = nn.Linear(2 * H if bi else H, 1)

    def forward(self, X, lunghezze):
        e = self.drop(self.embedding(X))
        pacco = nn.utils.rnn.pack_padded_sequence(e, lunghezze, batch_first=True,
                                                  enforce_sorted=False)   # skips the padding
        _, h = self.rete(pacco)
        if isinstance(h, tuple):                       # the LSTM returns (h, c)
            h = h[0]
        h = torch.cat(list(h), dim=1)                  # the last state of each direction
        return self.uscita(self.drop(h)).squeeze(-1)
import copy

def accuratezza(m, X, L, Y):
    m.eval()
    with torch.no_grad():
        giuste = ((m(X, L) > 0).long() == Y).float().mean()   # logit > 0: positive
    m.train()
    return round(giuste.item(), 3)

def addestra(m, passi=1500):
    ott = torch.optim.AdamW(m.parameters(), lr=2e-3, weight_decay=0.01)
    migliore = -1
    for passo in range(passi + 1):
        ix = torch.randint(0, len(Xa), (32,))
        Lb = La[ix]
        Xb = Xa[ix][:, :Lb.max()]                      # trim the extra padding
        L = F.binary_cross_entropy_with_logits(m(Xb, Lb), Ya[ix].float())
        ott.zero_grad(); L.backward(); ott.step()
        if passo % 100 == 0:
            a = accuratezza(m, Xv, Lv, Yv)
            if a > migliore:                           # early stopping
                migliore, pesi, quando = a, copy.deepcopy(m.state_dict()), passo
    m.load_state_dict(pesi)
    return quando, migliore

modelli = {}
for nome, crea in [("bag of words", Sacco),
                   ("LSTM", lambda: Sentimento("lstm")),
                   ("bidirectional LSTM", lambda: Sentimento("lstm", bi=True))]:
    torch.manual_seed(2026)
    m = crea()
    print(nome, addestra(m), accuratezza(m, Xt, Lt, Yt))
    modelli[nome] = m
# bag of words (500, 0.807) 0.827
# LSTM (1300, 0.813) 0.81
# bidirectional LSTM (1200, 0.8) 0.797
prove = ["the food was good", "the food was not good",
         "i loved it", "i did not love it",
         "bad", "not bad"]
X, L, _ = tensori([(t, 0) for t in prove])
for nome, m in modelli.items():
    m.eval()
    with torch.no_grad():
        p = torch.sigmoid(m(X, L))                     # the probability that it is positive
    print(nome, [round(x, 2) for x in p.tolist()])
# bag of words [0.56, 0.43, 0.55, 0.42, 0.34, 0.23]
# LSTM [1.0, 0.0, 1.0, 0.08, 0.0, 0.0]
# bidirectional LSTM [1.0, 0.0, 1.0, 0.04, 0.0, 0.0]

In the book

This lab accompanies Workshop B, “Series and sentiment”, between chapters 9 and 10. In the first part the Workshop forecasts the daily sales of a simulated shop with an LSTM, against naive forecasts and a linear model, and measures the limit that no model can beat. In the second it tackles the reviews: the vocabulary of words, sentences of different lengths, the bag of words, the LSTM and the bidirectional LSTM.

COVER COMING SOON
dltp · 2026

Deep Learning. Teoria, matematica e pratica delle reti neurali

Michele di Nuzzo · in Italian

Over the course of the book we build a small language model, a GPT, from scratch and grow it one piece at a time. At the start it is a model that counts which letter follows which. At the end it is a complete Transformer that writes dialogue, answers questions, reads images and draws the digits we ask for in words.

[the book’s page] [shop links coming soon]

The “Inside the Puppet” series