πŸŽ“ A1Learner
πŸ”
0 of 50 lessons completed

Python ML What Is Machine Learning?

Machine learning is learning from examples instead of fixed rules. A program looks at many examples and finds the pattern in them.

A fixed rule flags one word

The rule flags every subject with the word free in it. Two subjects match the rule.

subjects = ["win free money", "meeting notes", "free prize now", "lunch plan"]
flagged = [s for s in subjects if "free" in s]
print(flagged)
print(len(flagged))

Labels tell the program the answers

Each example carries its label. Ham means a normal message. Two examples are spam and two are ham.

examples = [("win free money", "spam"), ("meeting at noon", "ham"), ("free prize now", "spam"), ("lunch plan", "ham")]
labels = [label for text, label in examples]
print(labels)
print(labels.count("spam"))
print(labels.count("ham"))

Three clues point at spam

The new message holds all three spam words. Three matches is a strong clue.

spam_words = ["free", "win", "prize"]
new = "win a free prize"
found = [w for w in spam_words if w in new]
print(found)
print(len(found))

Example

examples = [("win free money", "spam"), ("free prize for you", "spam"), ("meeting at noon", "ham"), ("free lunch today", "ham"), ("claim free cash", "spam")]
spam_free = sum(1 for text, label in examples if label == "spam" and "free" in text)
ham_free = sum(1 for text, label in examples if label == "ham" and "free" in text)
print("Spam examples with free:", spam_free)
print("Ham examples with free:", ham_free)
new = "free gift for you"
print("New message:", new)
if spam_free > ham_free:
    print("Guess: spam")
else:
    print("Guess: ham")

Key points

  • Machine learning: a program that finds patterns in examples, instead of following fixed rules
  • Use examples to teach a program. A photo with its name attached teaches the program what is in the photo.
  • Label: the right answer attached to one example
  • Feature: one measured detail of an example, like the number of letters in a word
  • Prediction: the program's guess for a new example
  • Fixed rules break when the pattern changes. New examples keep the program up to date.

In this example, the list holds five labelled messages. The program counts how many spam messages hold the word free. It counts how many normal messages hold the same word. Free shows up in three spam messages and in one normal message. The new message holds the word free, so the program guesses spam. The counts are the whole lesson. The guess comes from the examples, not from a rule.

Note

Machine learning still needs good examples. Wrong examples teach the wrong pattern.

Try it Yourself

Edit the code, then press Run.

Running is simulated Β· Python Playground

Exercise

What does machine learning learn from?