Sentiment analysis with logistic regression
A classic first NLP project: decide whether a review or tweet is positive or negative using logistic regression. First build a vocabulary and count how often each word appears in positive and in negative examples. Then describe any new text with just three numbers, and let logistic regression turn them into a probability.
Everyday analogy
A teacher who has read thousands of feedback forms knows that "love" and "great" usually mean a happy student, and "boring" and "hate" an unhappy one. Count the happy words and the unhappy words, weigh them, and you can guess the mood.
Example
- Training reviews (positive): "great phone, love it", "love the camera"
- Training reviews (negative): "bad battery, hate it", "hate the price"
- New review to classify: "love the phone"
Step 1: count each word in positive and negative reviews
| Word | Positive count | Negative count |
|---|---|---|
| love | 2 | 0 |
| great | 1 | 0 |
| phone | 1 | 0 |
| camera | 1 | 0 |
| it | 1 | 1 |
| the | 1 | 1 |
| bad | 0 | 1 |
| battery | 0 | 1 |
| hate | 0 | 2 |
| price | 0 | 1 |
Step 2: turn the new review into three numbers
So "love the phone" becomes the feature list [1, 4, 1].
Step 3: weigh the features and apply the S-curve
Training has learned weights, say: bias 0, positive total +0.8, negative total −0.9.
Score = 0 × 1 + 0.8 × 4 − 0.9 × 1 = 2.3
Sigmoid(2.3) ≈ 0.91 → 91% positive. Above the 50% threshold, so the review is labelled positive.
- Clean the text (tokenise, lowercase, remove stop words and punctuation, stem).
- Build word frequencies for the positive and negative classes.
- Convert every review into [bias, positive total, negative total].
- Train logistic regression, adjusting the weights with gradient descent until predictions match the labels.
- Test on reviews it hasn't seen and measure accuracy.
Try it yourself
About 15 minScore reviews with word weights
- Give positive words +1 (great, love) and negative words -1 (bad, broken).
- Score 5 product reviews by adding up the words.
- Compare with your own judgement, especially on not bad.
What you should see: Simple word scores work surprisingly well, but miss tricks like negation.
Use any free AI chatbot (ChatGPT, Claude, Gemini or Copilot). Never paste private or confidential information.