SYDE 572 · Introduction to Pattern Recognition
Text classification with Naive Bayes
The data is all_sentiment_shuffled.txt from the assignment zip: 11,914 customer reviews from six topics (the Blitzer et al. dataset). There is one review per line. Each line has the topic label, the sentiment label (pos or neg), a document id, and then the words of the review, already lowercased and split into tokens. The file is valid UTF-8. The sentiment label is what the classifier predicts. The topic label is not used on this page.
| Sentiment | Reviews |
|---|---|
| pos | 6000 |
| neg | 5914 |
| Topic | Reviews |
|---|---|
| books | 2000 |
| camera | 1999 |
| dvd | 2000 |
| health | 2000 |
| music | 2000 |
| software | 1915 |
Train and evaluation split. I used the split from the assignment: the first 80% of the file for training (9531 reviews) and the last 20% for evaluation (2383 reviews). The file is already shuffled, so this split involves no random choice.
Choices the assignment leaves open.
Naive Bayes code. The functions are in nb.py and use only collections.Counter and numpy, with no machine learning toolkit. The labels are not hard-coded: train_nb takes the classes from the training labels.
Random seed. The only random choice on this page is the shuffle of the training reviews for the learning curve in Part 5. It uses seed 572, the same seed as in Assignment 3, which I picked before running anything. Part 5 also checks 9 other seeds.
Software. Python 3.14.3, numpy 2.5.3 and matplotlib 3.11.2.
train_nb(documents, labels) in nb.py takes the training reviews and their labels and returns a dictionary with the classes, the vocabulary (every word seen in training) and two tables of log probabilities: one for the prior of each class and one for each word given each class. The classes are taken from the labels, so nothing is hard-coded to pos and neg.
Let \(N\) be the number of training reviews, \(N_c\) the number with label \(c\), \(n_{c,w}\) how many times word \(w\) appears in the reviews with label \(c\), and \(V\) the number of different words in the training reviews. The estimates are
\[ P(c) = \frac{N_c}{N}, \qquad P(w \mid c) = \frac{n_{c,w} + \alpha}{\sum_{w'} n_{c,w'} + \alpha V} \]with \(\alpha = 1\) (add-one smoothing), so a word that never appeared with a label still gets a small probability for that label. train_nb stores the natural log of both.
On the 9531 training reviews, the vocabulary has \(V =\) 52,392 words and the priors are:
| Label | P(label) |
|---|---|
| neg | 0.4914 |
| pos | 0.5086 |
score_doc_label(document, label, model) returns
where the sum runs over the words of the review. Adding logs is the same as multiplying the probabilities, but it avoids the numbers underflowing to zero. classify_nb(document, model) computes this score for each class and returns the label with the highest one. classify_documents does it for a list of reviews.
| Word | Label | Log probability | Probability |
|---|---|---|---|
| great | neg | -7.546 | 0.00053 |
| great | pos | -6.629 | 0.00132 |
| bad | neg | -7.696 | 0.00045 |
| bad | pos | -8.666 | 0.00017 |
Both words came out the way the assignment says they should. "great" is more likely under pos (0.00132) than under neg (0.00053), and the pos value is inside the 0.001 to 0.002 range it mentions. "bad" goes the other way, with 0.00045 for neg against 0.00017 for pos.
The review ['a', 'top-quality', 'performance'] runs without crashing. "top-quality" is not in the training vocabulary, so it gets skipped and the score comes from "a" and "performance" only, which gives -13.487 for neg and -12.808 for pos.
| Review | Guessed label |
|---|---|
| great | pos |
| bad | neg |
| great product | pos |
| waste of money | neg |
| i love it | pos |
| not good | neg |
All six came out the way I would expect, but they are just six examples I picked myself, so they don't tell me how accurate the classifier is overall. That comes in Part 3. The code is part2_sanity.py.
classify_documents(docs, model) returns the predicted label for every review in a list, and accuracy(true_labels, guessed_labels) is the number of correct guesses divided by the number of reviews. I trained on the 9531 training reviews (alpha = 1) and classified the 2383 evaluation reviews.
Accuracy on the evaluation set: 1943 of 2383 correct, which is 0.8154 (about 81.5%).
The evaluation set is close to half pos and half neg, and always guessing pos (the most common training label) would only get 0.4838, so the classifier is clearly learning something. It made 440 mistakes in total: 194 neg reviews were guessed as pos and 246 pos reviews were guessed as neg.
| True label | Guessed neg | Guessed pos |
|---|---|---|
| neg | 1036 | 194 |
| pos | 246 | 907 |
The code is part3_evaluation.py.
I used alpha = 1 without trying other values on the evaluation set. To see how much the choice matters, part3_alpha_check.py trains on the first 80% of the training reviews (7624) and measures accuracy on the last 20% of the training reviews (1907). The evaluation set is not used in this check.
| alpha | Validation accuracy |
|---|---|
| 0.01 | 0.7567 |
| 0.1 | 0.7740 |
| 0.5 | 0.7850 |
| 1 | 0.7866 |
| 2 | 0.7913 |
| 5 | 0.7944 |
Very small alpha values are clearly worse (0.7567 at alpha = 0.01). From alpha = 1 to alpha = 5 the accuracy goes from 0.7866 to 0.7944, which is about 15 of the 1907 validation reviews, so the difference is small and comes from one split. This means alpha = 1 is probably not the best value, but I kept it for the result above because I chose it before looking at anything. I did not test values larger than 5. These accuracies are lower than 0.8154 because the model here is trained on fewer reviews, so they should not be compared with it.
The classifier got 440 of the 2383 evaluation reviews wrong. I didn't want to pick examples by hand, so I ranked the mistakes by how confident they were, using the log score of the guessed label minus the log score of the true label (I call this the margin). I then took the 5 largest margins among reviews with at most 30 words, plus the 3 largest overall, and I fixed that rule before reading any review. Reviews are numbered by their position in the evaluation set, starting at 0, and the code is part4_errors.py.
| Review | True | Guessed | Words | Margin | Text (long reviews cut after the first sentence) |
|---|---|---|---|---|---|
| 1507 | pos | neg | 15 | 3.72 | this was not a waste of brad 's time or mine . good job ! |
| 678 | pos | neg | 25 | 3.05 | i was a little diappointed when i found out that i would have to buy more versions to get continued training on this subject . |
| 1683 | neg | pos | 28 | 2.94 | was not impressed . narrow scoped , personal reflections , applications limited . i also read the male companion book wild at heart and was also not impressed |
| 1983 | neg | pos | 12 | 2.86 | this lifts your heart to god as you listen . beautifully done |
| 1791 | neg | pos | 18 | 2.56 | the mirror 's light is quite dim and the magnification ( 5x ) is inadequate for most purposes |
| 2226 | neg | pos | 2644 | 127.71 | we bought this camera thinking that it would be our do-all " eurocam " for an upcoming trip to europe . ... |
| 746 | neg | pos | 1210 | 91.44 | i grew up reading harold evan 's sunday times - in the late 1970s it provided a window on the world that few other papers could . ... |
| 1287 | pos | neg | 491 | 67.92 | i 've been using norton antivirus 2002 with annual updates of patches forever with norton internet security 2003. ... |
For each review the code also lists the words that pushed hardest towards the wrong label (the difference in log probability times how often the word appears in the review). The numbers below come from that list.
Review 1507 is labelled pos ("this was not a waste of brad's time or mine. good job!") but the classifier called it neg: "waste" pushes towards neg by 2.35, while "not" only adds 0.45. Review 1683 shows the same thing from the other side. It is labelled neg and says "not impressed" twice, but "impressed" adds 2.1 towards pos in total, so the guess was pos. Every word is scored on its own, so the classifier can't tell that "not" flips the meaning of the word after it. That is what the numbers show in these two reviews, but I didn't count how many of the 440 mistakes involve negation, so I can't say how common it is.
Review 678 is labelled pos, but it says "i was a little diappointed when i found out that i would have to buy more versions", which reads like a mild complaint to me. The neg guess is easy to follow, since the misspelling "diappointed" is in the training vocabulary and adds 0.7 towards neg, and I think the label is debatable. Review 1983 is a different kind of case: it is labelled neg, but "this lifts your heart to god as you listen. beautifully done" reads positive to me, and I can't explain the label from the text.
Review 1791 (neg, guessed pos) is "the mirror's light is quite dim and the magnification (5x) is inadequate for most purposes". The words pushing towards pos are ordinary words like "purposes", "light" and "mirror", each adding less than 1.
The three most confident mistakes overall are all long reviews (2644, 1210 and 491 words), with margins of 127.71, 91.44 and 67.92 compared with 2.56 to 3.72 for the short ones. That makes sense given how the score is built: the log scores are added up over every word, so a long review can get a much larger margin than a short one. Single words also carry a lot in these reviews. "norton" alone adds 22.21 towards neg in review 1287, and in review 746 the names "evan" (9.65) and "murdoch" (8.91) are the biggest pushes towards pos. I haven't looked into why these words lean the way they do in the training data.
I did the learning curve as the one optional task. I trained on 10%, 20%, and so on up to 100% of the 9531 training reviews (953 to 9531 reviews) and tested every model on the same 2383 evaluation reviews as in Part 3, with alpha = 1 each time. The training reviews are shuffled once with seed 572, and each bigger training set contains the smaller ones, so the points can be compared directly. I did not choose anything based on this curve. The code is part5_learning_curve.py.
The accuracy goes from 0.757 with 953 reviews to 0.8154 with all 9531, and most of that gain comes early. Going from 953 to 3812 reviews adds about 4 points (0.757 to 0.799), while going from 3812 to 9531 only adds about 1.6 points (0.799 to 0.8154). The last point uses all the training reviews, so it gives the same 0.8154 as Part 3.
The curve is not perfectly smooth: at 4766 reviews the accuracy (0.7927) is lower than at 3812 (0.799). I wanted to know whether a wiggle like that means anything, so part5_seed_check.py repeats the whole curve with 10 different shuffles (seed 572 and seeds 1 to 9, a list I fixed before running it). The table shows the lowest and highest accuracy over those 10 shuffles at each size.
| Training size | Training reviews | Accuracy (seed 572) | Lowest of 10 shuffles | Highest of 10 shuffles |
|---|---|---|---|---|
| 10% | 953 | 0.7570 | 0.7381 | 0.7600 |
| 20% | 1906 | 0.7747 | 0.7696 | 0.7768 |
| 30% | 2859 | 0.7872 | 0.7789 | 0.7923 |
| 40% | 3812 | 0.7990 | 0.7797 | 0.7990 |
| 50% | 4766 | 0.7927 | 0.7898 | 0.7994 |
| 60% | 5719 | 0.8057 | 0.7931 | 0.8057 |
| 70% | 6672 | 0.8149 | 0.7923 | 0.8149 |
| 80% | 7625 | 0.8128 | 0.8019 | 0.8154 |
| 90% | 8578 | 0.8128 | 0.8078 | 0.8158 |
| 100% | 9531 | 0.8154 | 0.8154 | 0.8154 |
At every size below 100%, the lowest and highest shuffle are between about 0.7 and 2.3 points apart, which is more than the dip at 4766 reviews (about 0.6 points), so I would not read anything into that dip. At 100% all shuffles use the same reviews, so there is no spread. I also noticed that at 40% and 70% the accuracy for seed 572 (0.799 and 0.8149) is the highest of the ten, so the curve in Fig 1 sits at the top of the range at those two sizes. Overall the shape is clear, since more data helps and the gains get smaller, but individual points can move by a point or two depending on the shuffle.
All the scripts are in this folder and only need numpy and matplotlib. Each one is run with python3 from this folder, with all_sentiment_shuffled.txt next to them, and the plot is saved in media/.
| File | What it does |
|---|---|
| common.py | reads the review file and makes the 80/20 split (the code given in the assignment) |
| nb.py | the Naive Bayes functions: train_nb, score_doc_label, classify_nb, classify_documents and accuracy |
| part2_sanity.py | Parts 1 and 2: vocabulary size, priors, the two sanity checks and the short reviews |
| part3_evaluation.py | Part 3: accuracy, the always-guess-pos comparison, the mistake counts and the share of unseen words |
| part3_alpha_check.py | Part 3: accuracy for different alpha values on a validation part of the training set |
| part4_errors.py | Part 4: the misclassified reviews with the largest margins and the words that pushed towards the wrong label |
| part5_learning_curve.py | Part 5: the learning curve and Fig 1 |
| part5_seed_check.py | Part 5: the learning curve repeated for 10 shuffles (it trains the model 100 times, so it is the slowest script) |
| all_sentiment_shuffled.txt | the review data from the assignment zip |
Larissa Rudenko - Fall 2026