Menu
CoddyTech

Conditional Probability

Part of the Statistics for ML section of Coddy's Machine Learning journey. Lesson 17 of 64.

Half of these 10 emails are spam. But once you know an email has a link, only the linked ones matter:

10 emails as cells in two groups. A frame marks the 4 emails with a link, 3 of them spam; the 6 without a link hold 2 spam

The share inside that group is the conditional probability of spam given a link, P(spam | link). Count both, then divide by the condition:

emails = pd.DataFrame({
    "link": ["yes", "no", "yes", "no", "no", "no", "yes", "no", "no", "yes"],
    "spam": ["yes", "no", "yes", "no", "no", "yes", "no", "no", "yes", "yes"],
})
spam = emails["spam"] == "yes"
link = emails["link"] == "yes"
print(spam.mean())
print((spam & link).sum() / link.sum())

This prints:

0.5
0.75

The condition you already know goes below the line: you divide by it. A spam filter works this way: the chance of spam given an email's words.

challenge icon

Challenge

Medium

A market logged 50 days in mornings.csv: the morning sky (clear, cloudy or foggy) and rain, yes if it rained later. Which sky warns best?

  1. For each sky in skies, print the chance of rain given that sky.
  2. Print the chance of rain on any day.
  3. Print the best clue: the sky with the top chance.

For a shorter log, to 2 decimals:

Rain after a clear morning: 0.25
Rain after a cloudy morning: 0.33
Rain after a foggy morning: 0.75
Rain on any day: 0.45
Best clue for rain: foggy

Try it yourself

import pandas as pd

days = pd.read_csv("mornings.csv")
skies = ["clear", "cloudy", "foggy"]

# Write your code below
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Statistics for ML

Practice on your own: Online Python compiler