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"
Learned word weights"love"3"great"2"okay"0.2"broken"2.5"awful"3
Logistic regression learns a weight for each word: green pushes towards positive, red towards negative.

Step 1: count each word in positive and negative reviews

WordPositive countNegative count
love20
great10
phone10
camera10
it11
the11
bad01
battery01
hate02
price01

Step 2: turn the new review into three numbers

BiasAlways 1
Positive totallove 2 + the 1 + phone 1 = 4
Negative totallove 0 + the 1 + phone 0 = 1

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.

  1. Clean the text (tokenise, lowercase, remove stop words and punctuation, stem).
  2. Build word frequencies for the positive and negative classes.
  3. Convert every review into [bias, positive total, negative total].
  4. Train logistic regression, adjusting the weights with gradient descent until predictions match the labels.
  5. Test on reviews it hasn't seen and measure accuracy.

Try it yourself

About 15 min

Score reviews with word weights

  1. Give positive words +1 (great, love) and negative words -1 (bad, broken).
  2. Score 5 product reviews by adding up the words.
  3. 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.

Build it for real · guided projectBuild a sentiment analyser for product reviewsAbout 60 min · Copy-paste code · step by step
Test what you learned

Take a quick quiz, or look up any word in the glossary.