LECTURE 8

What is machine learning?

Learning from examples: the ideas behind every model

Today's key line of code
model.fit(X_train, y_train)
model.predict(X_test)

The road ahead: machine learning

L7Charts and stats
TodayL8What is ML?
L9Regression
L10Classification
L11Evaluation
L12Features
L13Clustering
L14Responsible ML

Today you will

  1. 1Explain machine learning as learning a function from examples
  2. 2Tell supervised from unsupervised learning
  3. 3Tell classification from regression
  4. 4Use the fit / predict pattern with any scikit-learn model
  5. 5Explain why we judge a model on data it has never seen
Md Mahbub E NoorLecture 8: What is machine learning?University of Barishal2 / 19

Machine learning in one sentence

1

Examples in

We give the computer many examples: inputs (features) and, often, the right answers (labels).

2

Pattern learned

An algorithm finds a rule, called a model, that maps inputs to answers.

3

New answers out

The model predicts answers for inputs it has never seen. That is the whole point.

Md Mahbub E NoorLecture 8: What is machine learning?University of Barishal3 / 19

Supervised or unsupervised?

Supervised (labels given)

  • Every example has the right answer
  • Goal: predict the answer for new inputs
  • Spam filter, price prediction, diagnosis
  • Lectures 9 to 12

Unsupervised (no labels)

  • Only inputs, no answers
  • Goal: find structure, such as groups
  • Customer segments, topic grouping
  • Lecture 13
Md Mahbub E NoorLecture 8: What is machine learning?University of Barishal4 / 19

Classification or regression?

Ask: is the answer a category or a number?

QuestionAnswer looks likeType
Is this message spam?spam / hamClassification
What mark will this student get?a number, e.g. 78.5Regression
Which flower species is this?one of 3 namesClassification
How many units will sell next week?a numberRegression
Will this loan be repaid?yes / noClassification
Md Mahbub E NoorLecture 8: What is machine learning?University of Barishal5 / 19

The machine learning workflow

1Question
What will we predict?
➜
2Data
Collect and clean
➜
3Features
Choose and prepare inputs
➜
4Split
Hide a test set
➜
5Train
fit()
➜
6Evaluate
Honest test score
➜
7Use
predict() on new data

The same workflow as Lecture 6, for any dataset. Most of the work is before training.

Md Mahbub E NoorLecture 8: What is machine learning?University of Barishal6 / 19

Meet a classic dataset: iris flowers

150 flowers, 4 measurements each (in cm), 3 species. It ships with scikit-learn, so it works offline.

sepal lengthsepal widthpetal lengthpetal widthspecies (label)
5.13.51.40.2setosa
7.03.24.71.4versicolor
6.33.36.02.5virginica
4.93.01.40.2setosa
6.43.24.51.5versicolor
Md Mahbub E NoorLecture 8: What is machine learning?University of Barishal7 / 19

Look first: can the classes be told apart?

Two petal measurements already separate the species well. Machine learning finds such patterns automatically, in many dimensions.

Code
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
iris = load_iris(as_frame=True)
X = iris.data
y = iris.target
for k, name in enumerate(iris.target_names):
    part = X[y == k]
    plt.scatter(part["petal length (cm)"],
                part["petal width (cm)"], label=name)
plt.xlabel("petal length (cm)")
plt.ylabel("petal width (cm)")
plt.legend()
plt.show()
Look first: can the classes be told apart?
Md Mahbub E NoorLecture 8: What is machine learning?University of Barishal8 / 19

The same pattern for every model

  • Split first, with the same function as Lecture 6
  • fit learns from training data
  • score reports accuracy on test data
  • Swap the model; the code stays the same
Code
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.naive_bayes import GaussianNB
X_tr, X_te, y_tr, y_te = train_test_split(
    X, y, test_size=0.3, random_state=42, stratify=y)
for model in [KNeighborsClassifier(),
              DecisionTreeClassifier(random_state=0),
              GaussianNB()]:
    model.fit(X_tr, y_tr)
    acc = model.score(X_te, y_te)
    print(type(model).__name__, round(acc, 3))
Output
KNeighborsClassifier 0.978
DecisionTreeClassifier 0.978
GaussianNB 0.911
Md Mahbub E NoorLecture 8: What is machine learning?University of Barishal9 / 19

100% on training data: a perfect model?

Predict first
Code
one_nn = KNeighborsClassifier(n_neighbors=1)
one_nn.fit(X_tr, y_tr)
print(one_nn.score(X_tr, y_tr))
print(round(one_nn.score(X_te, y_te), 3))
?

A 1-nearest-neighbour model scores 100% on its training data. What will it score on the test data?

Md Mahbub E NoorLecture 8: What is machine learning?University of Barishal10 / 19

Answer: 100% on training data: a perfect model?

Code
one_nn = KNeighborsClassifier(n_neighbors=1)
one_nn.fit(X_tr, y_tr)
print(one_nn.score(X_tr, y_tr))
print(round(one_nn.score(X_te, y_te), 3))
Output
1.0
0.933
  • On training data it just finds each flower itself
  • That is memorising, not learning
  • Only the test score shows real skill
  • Never report training accuracy as your result
Md Mahbub E NoorLecture 8: What is machine learning?University of Barishal11 / 19

Generalisation: the real goal

1

Memorising

Learning the exact exam questions. Perfect on those, lost on new ones.

2

Generalising

Understanding the patterns, so new questions can be answered too.

3

How we check

Keep a test set the model never sees, and judge it only there.

Md Mahbub E NoorLecture 8: What is machine learning?University of Barishal12 / 19

Watch it: memorising vs generalising

WATCH FOR

  • k = 1 wraps a border around every training point
  • 100% on training data, 74% on new points
  • k = 15 is smoother: 87% on training data
  • But 88% on new points: it generalises better

Silent video: press play, pause any time.

Md Mahbub E NoorLecture 8: What is machine learning?University of Barishal13 / 19

Vocabulary for the rest of the course

WordMeaning
Feature (X)An input column the model uses
Label / target (y)The answer we want to predict
ModelThe learned rule that maps features to a label
Training (fit)Learning the rule from examples
PredictionThe model's answer for a new example
HyperparameterA setting we choose, e.g. k in k-nearest neighbours
GeneralisationDoing well on data the model has never seen
Md Mahbub E NoorLecture 8: What is machine learning?University of Barishal14 / 19

Your turn 8 minutes

  1. 1Load the wine dataset: from sklearn.datasets import load_wine
  2. 2Split it 70/30 with stratify
  3. 3Score the same three models
  4. 4Which model wins? Is it the same as for iris?
Code
from sklearn.datasets import load_wine
wine = load_wine(as_frame=True)
X, y = wine.data, wine.target
...

Starter code: replace the ... with your own code

Md Mahbub E NoorLecture 8: What is machine learning?University of Barishal15 / 19

Interactive lab: What is ML? Lab

In the lab you can

  1. Sort the tasks12 questions: supervised or not, category or number.
  2. Be the modelWrite a two-question rule for iris, then meet the tree's.
  3. Same pattern, any modelfit / score on iris, wine, breast cancer; guess the winner.
  4. Memorise or generalisek-NN from k = 1 to 101: training vs new points.
Open the lab ►︎

Opens in a new tab and works offline. All labs: labs/START_HERE.html

Screenshot of the What is ML? Lab
Md Mahbub E NoorLecture 8: What is machine learning?University of Barishal16 / 19

Today's toolkit

supervisedLearn from labelled examples
unsupervisedFind structure without labels
classificationPredict a category
regressionPredict a number
model.fit(X, y)Train
model.predict(X)Answer for new rows
model.score(X, y)Accuracy (classifiers)
test setData the model never sees in training
Md Mahbub E NoorLecture 8: What is machine learning?University of Barishal17 / 19

Homework 8

Due before Lecture 9 · [date]

1

Classify the task

Write 6 prediction questions from daily life. Label each: classification or regression, supervised or unsupervised.

2

Features and label

For two of your questions, list 3 useful features and the label.

3

Three models

Repeat the 'same pattern' slide on load_breast_cancer. Report the three test accuracies.

4

Train vs test

For KNeighborsClassifier(n_neighbors=1) on breast cancer, print training and test accuracy. Explain the gap.

5

Explain

In 3 sentences: why do we judge a model only on data it has not seen?

Submit on [LMS / Google Classroom]: your notebook file HW8_<your ID>.ipynb, or a Colab link set to “Anyone with the link can view”.
Md Mahbub E NoorLecture 8: What is machine learning?University of Barishal18 / 19