Asiman Data School

Module 3, topic 21, week 11, Tuesday

Introduction to Machine Learning

What machine learning is and where it is used, the three types of learning, classification and regression, the map of the models of this module, the steps of a machine learning project, and a first look at scikit-learn. A lesson about ideas, with one short code example.

Introduction: the map of the module

The first lesson of Module 3. In Module 1 you learned to write Python and to work with tables of data. In Module 2 you learned the mathematics that describes data: vectors and matrices, probability, the mean and the standard deviation, tests, intervals and correlation. This module puts the two together. From now on the computer will not only describe the data: it will learn from it and make predictions about cases it has never seen.

This lesson is the map of the whole module. It explains what machine learning is and where it is used, the three types of learning (supervised, unsupervised and reinforcement learning), the kinds of tasks each type solves, the difference between classification and regression, the steps of a machine learning project from the first question to a working model, and the basics of scikit-learn, the Python library used in every lesson of this module.

You need nothing new for this lesson. It helps to remember pandas DataFrames (Topic 10), the mean and the standard deviation (Topic 18) and the regression line of the five students (Topic 20). There are no formulas to calculate here and almost no code: this lesson is about ideas and words. The lessons that follow will fill every box of the map with mathematics and code.

What you will learn

  1. 1.What machine learning is, and how it differs from ordinary programming
  2. 2.How artificial intelligence, machine learning and deep learning are related
  3. 3.Where machine learning is used in everyday life and in business
  4. 4.The basic words: dataset, sample, feature, target, label, model, training, prediction
  5. 5.Supervised learning, unsupervised learning and reinforcement learning, and how to tell them apart
  6. 6.Which models belong to which type, and in which lesson of this module each one is taught
  7. 7.The kinds of tasks every type of learning solves
  8. 8.The difference between classification and regression
  9. 9.The steps of a machine learning project, in the right order, and why the order matters
  10. 10.A first look at scikit-learn: what it is, X and y, and the pattern create, fit, predict that every model follows
The words of this lesson
WordMeaning
datasetthe table of data that the computer learns from
sample (also: example, observation, instance)one row of the table: one flat, one customer, one email
feature (also: input, variable, predictor)one column that describes the sample: the area of the flat, the age of the customer
target (also: output, response)the column we want to predict: the price of the flat
labelthe value of the target for one sample, especially when it is a category: "spam", "not spam"
modelthe result of learning: a rule, found from data, that turns features into a prediction
training (also: fitting, learning)the process of finding that rule from data
predictionthe answer of the model for a sample
X, ythe usual names in code for the table of features and the column of the target

1What is machine learning?

1.1Two ways to make a computer solve a task

Suppose you want a program that moves unwanted emails (spam) out of the inbox.

The first way: write the rules yourself. You read many spam emails and notice patterns. Then you program them:

Python
if "free money" in email or "you won" in email:
    folder = "spam"
else:
    folder = "inbox"

This is ordinary programming, the kind you learned in Module 1. A person thinks of the rules and the computer follows them. It works for a while. Then the senders of spam write "fr3e m0ney", and you add a rule. They change again, and you add another. After a year the program has thousands of rules, nobody understands it any more, and it still misses new tricks.

The second way: let the computer find the rules. Collect many emails that people have already marked as "spam" or "not spam". Give them to a learning algorithm. The algorithm compares the two groups and finds by itself which words, senders and patterns separate them. The result is a model: a rule that was not written by a person but found from examples. When the senders of spam change their tricks, you do not rewrite the program. You give it new examples and it learns again.

The second way is machine learning.

Normal programming

Rules

Written by a programmer: “if the subject says WIN, it is spam”

Data

A new email arrives

Answer

Spam or not spam

Machine Learning

Data

Thousands of emails

Answers

Each one marked “spam” or “not spam”

Rules

Found by the computer itself: a model

In ordinary programming a person gives the computer the rules and the data, and the computer gives the answers. In machine learning a person gives the computer the data and the answers of many known examples, and the computer gives back the rules. Those rules, the model, are then used to answer new cases.

1.2A definition

Two definitions are quoted in almost every textbook:

  • Arthur Samuel, a pioneer of the field, described machine learning in 1959 as the field of study that gives computers the ability to learn without being explicitly programmed.
  • Tom Mitchell gave a more exact one in 1997: a program learns from experience E with respect to a task T and a performance measure P, if its performance at T, measured by P, improves with experience E.

For the spam filter: the task T is to sort emails into spam and not spam, the experience E is the collection of emails that people have already marked, and the performance measure P is the share of emails that the filter sorts correctly. If that share grows as the filter sees more marked emails, the filter is learning.

In the words of this course:

1.3You have already done it once

In Topic 20 five students studied for 2, 4, 5, 6 and 8 hours and got the marks 50, 60, 65, 75 and 80. From these five pairs you calculated the regression line

y^=39.75+5.25 x\hat{y} = 39.75 + 5.25\,x

and used it to predict the mark of a student who studies 7 hours: 76.5. Nobody told you the rule "every hour gives 5.25 marks". It came out of the data. That is machine learning in its smallest form: data in, a rule out, and the rule is used for a new case. The line is the model, the numbers 39.75 and 5.25 are what the model learned, and finding them is called training. Everything in this module is a larger and more careful version of that idea.

1.4Artificial intelligence, machine learning, deep learning

The three terms are often mixed up. They fit inside one another:

Artificial intelligence

Any technique that makes a computer do tasks that normally need human intelligence.

Machine learning

The rules are learned from data, not written by hand (Module 3).

Deep learning

Machine learning with large neural networks: images, speech, text, large language models (Modules 4 and 5).

The three terms fit inside one another: deep learning is a part of machine learning, and machine learning is a part of artificial intelligence.
  • Artificial intelligence (AI) is the widest term: any technique that makes a computer do something that normally needs human intelligence. A chess program made only of hand-written rules is AI, but it is not machine learning.
  • Machine learning (ML) is the part of AI in which the rules are learned from data.
  • Deep learning is the part of machine learning that uses large neural networks. It is the technique behind image recognition, speech recognition and large language models. Modules 4 and 5 cover it.

1.5When machine learning fits, and when it does not

Machine learning is a good choice when:

  • the rules are too many or too complicated to write by hand (recognising a face, understanding a spoken sentence);
  • the rules keep changing (spam, fraud);
  • there is a lot of data in which people cannot see the pattern by eye (which of 200,000 customers will leave next month);
  • every user needs a different answer (recommendations).

It is a poor choice when:

  • a simple, exact rule exists. The price with 18 percent tax is price * 1.18. No learning is needed for that;
  • there is no data, or very little, or the data does not contain the answer;
  • every single decision must be explained and proven exactly, and a mistake is never acceptable. A model is almost never right in 100 percent of cases.

A model is not magic. It can only learn what is in its data. Poor data gives a poor model, whatever the algorithm. The short form of this rule is "garbage in, garbage out".

Try it yourself

For each task decide whether machine learning is a sensible choice. (a) Calculating the area of a circle from its radius. (b) Recognising whether a photograph shows a cat. (c) Adding 18 percent tax to a price. (d) Choosing the songs that a listener will probably like.

Show a hint
Is there a short, exact rule that a person can write down? Then no learning is needed.
Show the solution

Answer: (a) no; (b) yes; (c) no; (d) yes.

The area of a circle and a price with tax have exact formulas: a person writes the rule in one line, and it is always right. Nobody can write down the rules that separate a cat from every other thing in a photograph, and every listener needs a different answer. In these two cases the rules have to be found from examples.

2Where is machine learning used?

You use machine learning many times a day, usually without noticing it.

Where is machine learning used?
WhereWhat the model doesThe data it learns from
Emaildecides whether a message is spamemails that users marked as spam or not spam
Online shops, video and music servicesrecommends the next product, film or songwhat you and similar users bought, watched or listened to
Maps and taxi appspredicts the travel time and the price of a ridemillions of earlier trips, the time of day, the traffic
Banksdecides whether a card payment looks like fraud; estimates whether a loan will be repaidearlier payments and loans whose outcome is known
Phonesunlocks with your face, turns speech into text, corrects typingphotographs, recordings and texts
Medicinemarks suspicious areas in X-ray and MRI images for the doctorimages that doctors have already diagnosed
Translation and chat assistantstranslate a text, answer a question, write a summaryvery large collections of text
Shops and factoriespredict next month's sales; warn before a machine breakssales of earlier years; measurements of sensors
Mobile operators and subscriptionsfind the customers who are likely to leavethe behaviour of customers who left and who stayed
Agriculture and weatherpredict the harvest or tomorrow's temperaturemeasurements of earlier years
Carsrecognise lanes, signs and pedestriansrecorded video of roads

All of these have the same shape. There is a question about a new case (this email, this customer, this image). There is a collection of old cases. And the answer for the new case is found from the patterns in the old ones.

The same list also shows that different tasks need different kinds of answers. "Spam or not" is a choice between two categories. "The travel time" is a number. "Customers who are similar to one another" has no right answer in the data at all. These differences lead to the types of machine learning of the next parts.

Try it yourself

What kind of answer does the model give in each case: a number or a category? (a) A spam filter. (b) The travel time of a taxi ride. (c) Whether a loan will be repaid. (d) The sales of next month.

Show a hint
A category is one of a few fixed names. A number can be larger or smaller by any amount.
Show the solution

Answer: (a) a category; (b) a number; (c) a category; (d) a number.

"Spam or not spam" and "will repay or will not repay" are choices between two names. A travel time and a number of sales are quantities. Part 9 gives the two kinds of tasks their names: classification and regression.

3The words of machine learning

Before the types, the vocabulary. Here is a small dataset of six flats:

The words of machine learning
area (m²)roomsfloordistance to the centre (km)price (thousand)
flat 145136.081
flat 260274.5118
flat 375328.0126
flat 4903102.0205
flat 5110453.5232
flat 61304121.0310

(The numbers are invented for this example.)

  • The whole table is the dataset.
  • Every row is one sample: one flat. Other words for the same thing are example, observation and instance. This dataset has 6 samples.
  • The columns area, rooms, floor and distance describe the flat. They are the features. This dataset has 4 features.
  • The price is what we want to predict. It is the target.
  • In code, the table of features is called X (a capital letter, because it is a table, a matrix as in Topic 14) and the column of the target is called y (a small letter, because it is one column, a vector as in Topic 13). Here X has 6 rows and 4 columns, and y has 6 values.
  • The algorithm looks at X and y together and finds a rule that turns the four features into a price. This step is the training (or fitting), and the rule it produces is the model.
  • A new flat comes: 80 m², 3 rooms, floor 4, 5 km from the centre. Its price is not known. The model gives an estimate. That is a prediction.

Two more words that you will hear in every lesson:

  • Parameters are the numbers that the model learns from the data. In the line y^=39.75+5.25 x\hat{y} = 39.75 + 5.25\,x the parameters are 39.75 and 5.25.
  • Hyperparameters are the settings that you choose before the training, for example how many neighbours a model looks at, or how deep a decision tree may grow. The model does not learn them. You set them.

Try it yourself

A table has 200 rows, one for every customer of a company, and five columns: age, city, monthly spending, number of complaints and "left the company (yes/no)". The company wants to predict who will leave. (a) How many samples does the dataset have? (b) How many features? (c) Which column is the target? (d) A model looks at the 5 most similar customers. Is the number 5 a parameter or a hyperparameter?

Show a hint
A sample is a row. The target is the column that is predicted; the other columns are the features.
Show the solution

Answer: (a) 200; (b) 4; (c) left the company; (d) a hyperparameter.

Every customer is one row, so there are 200 samples. "Left the company" is what the company wants to predict: the target. The other four columns describe the customer: they are the features, and XX has 200 rows and 4 columns. The number 5 is chosen by the person before the training; the model does not learn it. That makes it a hyperparameter.

4The three types of machine learning

Machine learning is usually divided into three types. The difference between them is what kind of data the algorithm gets and what kind of feedback it receives.

Classification: spam or not spamSample emails placed by how many links they have and how many words like FREE or WIN they use. A dashed boundary separates spam from not spam.05100246810Links in the emailWords like FREE or WINNot spamSpam

Supervised learning

every example has a right answer

Unsupervised learning: finding groups of similar customersThe k-means algorithm found three groups of customers without being told what the groups are.0255075100036912Visits per monthAverage spendGroup 1Group 2Group 3

Unsupervised learning

no answers, only the data

Reinforcement learning

learning by trial and reward

Supervised learning: every example has a right answer (here: spam or not spam), and the task is to find the answer for a new example. Unsupervised learning: no answers, only the data, and the task is to find which points belong together. Reinforcement learning: an agent tries actions, receives rewards, and looks for the actions that bring the most reward.
The three types of machine learning
Supervised learningUnsupervised learningReinforcement learning
The datafeatures and the right answer for every samplefeatures only, no answersno fixed table: the learner collects its own experience
The feedback"your prediction was right / wrong by this much"nonea reward or a penalty after actions
The goalpredict the answer for new samplesfind structure: groups, patterns, a simpler descriptionfind the behaviour that collects the most reward over time
A picture of ita student who learns with a teacher and an answer keya person who sorts a box of mixed buttons without being told howa child who learns to ride a bicycle by trying
In this courseTopics 22 to 42Topics 43 and 44not covered (only this lesson)

The next three parts take them one at a time.

Try it yourself

Which type of learning is described? (a) The data has the selling price of every flat. (b) A program receives one point for every game it wins. (c) There are only measurements, and nobody knows the groups.

Show a hint
Look at the feedback: a right answer for every sample, a reward after actions, or nothing.
Show the solution

Answer: (a) supervised; (b) reinforcement; (c) unsupervised.

A known price for every flat is a right answer for every sample: supervised. A point for a won game is a reward after a series of actions: reinforcement. Measurements without any answer leave only one thing to do, looking for structure: unsupervised.

5Supervised learning

5.1Learning with an answer key

In supervised learning every sample of the dataset comes with the right answer. The table of flats in Part 3 is such a dataset: for every flat the price is known. The emails that people marked as spam or not spam are another one.

The algorithm sees the features and the answer together, many times, and looks for the rule that connects them. The name comes from the picture of a teacher who supervises: for every exercise the teacher knows the right answer and tells the student how far off the attempt was.

After the training, the model is given new samples without the answer, and it predicts the answer. That is the whole purpose: a model is not useful because it knows the prices of the flats it has already seen. It is useful because it can estimate the price of a flat it has never seen. The ability to work well on new data is called generalisation, and measuring it honestly is one of the main subjects of this module (Topics 23 and 28).

Where do the answers come from? Sometimes they are recorded automatically (the price at which a flat was sold, whether a loan was repaid). Sometimes people must write them by hand, one by one (a doctor marks 10,000 images as "healthy" or "not healthy"). This work is called labelling, and it is often the most expensive part of a supervised project.

5.2The two kinds of supervised tasks

Supervised tasks are divided by the kind of answer:

  • If the answer is a number, the task is regression. The price of a flat, the travel time, tomorrow's temperature.
  • If the answer is a category, the task is classification. Spam or not spam, the species of a flower, the digit in an image.

Part 9 looks at this difference closely, because choosing between the two is the first decision in every supervised project.

5.3Tasks solved with supervised learning

Tasks solved with supervised learning
TaskFeatures (the input)Target (the answer)Kind
Price of a flatarea, rooms, floor, districtthe priceregression
Sales forecastmonth, price, advertising, holidaysthe units soldregression
Delivery timedistance, time of day, weatherthe minutesregression
Salary estimateyears of experience, education, positionthe salaryregression
Spam filterthe words of the email, the senderspam / not spamclassification
Loan decisionincome, age, earlier loanswill repay / will not repayclassification
Medical testmeasurements of a blood sampleill / healthyclassification
Customers who leavemonths as a customer, complaints, usagewill leave / will stayclassification
Handwritten digitsthe pixels of the imagethe digit 0 to 9classification
Species of a flowerthe length and width of the petalsone of three speciesclassification

Try it yourself

A hospital has 8,000 records of patients. Every record has the measurements of a blood sample and the diagnosis of a doctor: ill or healthy. A model should give the diagnosis for new patients. (a) Is this a supervised task? (b) What is the target? (c) Is it regression or classification?

Show a hint
Is the right answer known for the old records? Is that answer a number or a category?
Show the solution

Answer: (a) yes; (b) the diagnosis; (c) classification.

Every record comes with its right answer, the diagnosis, so the task is supervised and the diagnosis is the target. The blood measurements are the features. The answer is one of two categories, ill or healthy: classification. The diagnoses were written by doctors, one by one: this is the labelling work that makes supervised projects expensive.

6Unsupervised learning

6.1Learning without an answer key

In unsupervised learning the dataset has features only. There is no target column and no right answer. Nobody tells the algorithm what to look for. Its task is to find structure in the data by itself.

Imagine a box with 500 mixed buttons. Nobody gives you names for them. Still, you can sort them: by colour, by size, by the number of holes. You discover groups that are in the data, without a teacher. That is what an unsupervised algorithm does with the rows of a table.

Unsupervised learning: finding groups of similar customersTwenty-four sample customers placed by visits per month and average spend, with no labels.0255075100036912Visits per monthAverage spend

The data: no answers

Unsupervised learning: finding groups of similar customersThe k-means algorithm found three groups of customers without being told what the groups are.0255075100036912Visits per monthAverage spendGroup 1Group 2Group 3

The groups the algorithm found

Twenty-four customers of a shop, placed by their visits per month and their average spend. On the left the data as the algorithm receives it: no labels. On the right the three groups that the k-means algorithm (Topic 43) found by itself. Nobody told it what the groups are; a person still has to look at them and give them a meaning.

Because there are no right answers, there is also no simple mark for the result. Whether a grouping is good depends on whether it is useful: do the groups of customers that the algorithm found help the company to speak to each group in a better way? A person has to look at the result and interpret it.

6.2The main kinds of unsupervised tasks

  • Clustering: divide the samples into groups (clusters), so that the samples inside a group are similar to one another and different from the samples of other groups. A shop divides its customers into groups by what and how often they buy. Nobody defined the groups beforehand: the algorithm proposes them.
  • Dimensionality reduction: describe every sample with fewer numbers, and lose as little information as possible. A table with 100 columns is replaced by a table with 2 or 3 new columns that keep most of the variation. This makes it possible to draw the data, and it makes other models faster. The eigenvectors of Topic 15 are the mathematics behind the most important method, principal component analysis (PCA).
  • Anomaly detection: find the few samples that do not look like the rest. A card payment that is unlike all the earlier payments of the customer, or a machine whose sensors suddenly behave differently.
  • Association rules: find things that often occur together. "Customers who buy bread and butter often buy jam." (This kind is mentioned for completeness; it is not part of this course.)

6.3Tasks solved with unsupervised learning

Tasks solved with unsupervised learning
TaskThe dataWhat the algorithm findsKind
Customer groups for marketingpurchases, visits, spendinggroups of similar customersclustering
Sorting news articles by subjectthe words of the articlesgroups of articles about the same subjectclustering
Grouping similar photographsthe pixelsgroups of photographs that look alikeclustering
Drawing a table with 50 columnsthe 50 columns2 new columns that keep most of the informationdimensionality reduction
Making a model fasterhundreds of featuresa few combined featuresdimensionality reduction
Unusual card paymentsthe amount, place and time of paymentspayments that look unlike the othersanomaly detection
A machine that is about to failthe measurements of sensorsmeasurements that look unlike the normal onesanomaly detection

6.4How to tell supervised and unsupervised apart

Ask one question: does the data contain the answer that I want to predict?

  • "I have 5,000 customers, and for each I know whether they left." The answer is in the data: supervised.
  • "I have 5,000 customers and I want to see what kinds of customers there are." No answer column exists: unsupervised.

The same table can serve both. The table of flats is a supervised dataset when you predict the price. If you delete the price column and ask "what kinds of flats are on the market?", it is an unsupervised one.

Try it yourself

Name the kind of task. (a) Putting 10,000 songs into groups of songs that sound alike. (b) Showing a table with 80 columns as a picture with two axes. (c) Finding the few network connections that look unlike all the others. (d) A table of flats without the price column, and the question "what kinds of flats are on the market?": is this supervised or unsupervised?

Show a hint
Groups of similar samples, fewer columns, or the few unusual samples?
Show the solution

Answer: (a) clustering; (b) dimensionality reduction; (c) anomaly detection; (d) unsupervised.

Groups of similar samples are clusters. A picture has two axes, so 80 columns must become 2: dimensionality reduction. The few samples that do not look like the rest are anomalies. In (d) there is no column with the answer, so nothing can be predicted and checked: the task is unsupervised (it is clustering).

7Reinforcement learning

This type is not taught in this course. You should still know what it is, because it is the third member of the family and it is behind some of the best-known results of the field.

In reinforcement learning there is no table of examples. There is an agent (the learner) that acts inside an environment (a game, a road, a warehouse, a market). At every moment the agent sees the state of the environment, chooses an action, and receives a reward: a number that says how good the result was. The reward can be positive or negative. The agent tries again and again, and learns a policy: a way of choosing actions that collects as much reward as possible over a long time.

A child who learns to ride a bicycle does exactly this. Nobody gives the child a table of the right angle of the handlebar for every situation. The child tries, falls (a negative reward), stays up for a few metres (a positive reward), and gradually finds what works.

Three things make it different from the other two types:

  • No answer key. Nobody tells the agent the right action. It only learns afterwards how good its action was.
  • Delayed reward. A move in chess may turn out to be good or bad only thirty moves later. The agent must work out which of its earlier actions deserve the credit.
  • Exploration and exploitation. The agent has to choose between an action that it already knows to be good and a new action that might be better. Too little trying of new actions and it never finds the best one. Too much and it never uses what it knows.

Where it is used: programs that play chess, Go and video games at the level of the best players, robots that learn to walk or to grip objects, the control of traffic lights and of cooling in data centres, and parts of recommendation and advertising systems.

Which type of learning is it?

1 of 8

A bank has 50,000 old loans. For each one it knows whether the loan was repaid. It wants to predict this for new applicants.

Try it yourself

A robot vacuum cleaner learns to clean a room. It gets one point for every clean square of the floor and loses points when it bumps into furniture. Name the parts. (a) The agent. (b) The environment. (c) An action. (d) A reward.

Show a hint
Who learns? Where does it act? What can it do? What tells it how good the result was?
Show the solution

Answer: (a) the robot; (b) the room; (c) turning left; (d) one point for a clean square.

The robot is the learner, the agent. The room with its furniture is the environment it acts in. Turning left is one of the things it can do, an action. The points are the reward: a number that says how good the result was. Nobody gives the robot a table of right movements; it finds a good way of cleaning, a policy, by trying.

8The map of models and tasks

Now the whole picture. Every model of this module has its place in it.

Supervised learning

the data has the right answers

Regression

the answer is a number

  • Linear regression (22)
  • Ridge and Lasso (26)
  • Also, in a regression form: decision trees (29), random forests (31), k-nearest neighbours (33), support vector machines (36), boosting methods (38, 40)

Classification

the answer is a category

  • Logistic regression (27)
  • Decision trees (29)
  • Random forests (30)
  • k-nearest neighbours (32)
  • Naive Bayes (34)
  • Support vector machines, voting (35)
  • Gradient boosting, XGBoost (37)
  • AdaBoost, CatBoost, LightGBM (39)

Unsupervised learning

no answers, only the data

Clustering

find groups

  • k-means (43)
  • Hierarchical clustering (43)
  • DBSCAN (44)

Dimensionality reduction

fewer columns

  • Principal component analysis, PCA (44)

Reinforcement learning

learning by trial and reward

Control and games

which action is best now?

  • Q-learning, policy methods (not in this course)
The map of machine learning: three types, the kinds of tasks of each type, and the models that solve them. The number in brackets is the topic of this module that teaches the model.

The same map as a table, with the tasks:

The map of models and tasks
TypeKind of taskTypical questionModels (topic)
SupervisedRegression"How much?", "How many?"linear regression (22), Ridge and Lasso (26), and the regression forms of trees (29), forests (31), k-nearest neighbours (33), support vector machines (36) and boosting (38, 40)
SupervisedClassification"Which class?", "Yes or no?"logistic regression (27), decision trees (29), random forests (30), k-nearest neighbours (32), Naive Bayes (34), support vector machines and voting (35), gradient boosting and XGBoost (37), AdaBoost, CatBoost and LightGBM (39)
UnsupervisedClustering"Which samples belong together?"k-means and hierarchical clustering (43), DBSCAN (44)
UnsupervisedDimensionality reduction"Can the data be described with fewer columns?"principal component analysis, PCA (44)
ReinforcementControl and games"Which action is best now?"Q-learning, policy methods (not in this course)

Three remarks about the map:

  • A name can mislead. Logistic regression (Topic 27) has "regression" in its name, but it is a model for classification. The name has historical reasons. Look at the answer the model gives, not at its name.
  • Many models do both. Decision trees, random forests, k-nearest neighbours, support vector machines and the boosting methods exist in a version for classification and a version for regression. The idea is the same; only the kind of answer changes.
  • The other topics of the module are not models. Topics 24 and 25 (scaling numerical values; encoding categories and handling outliers) and Topic 41 (imbalanced data) teach how to prepare the data. Topic 23 (train/test split, cross-validation, overfitting and underfitting) and Topic 28 (classification metrics) teach how to measure whether a model is good. Topic 42 (pipelines and hyperparameter tuning) teaches how to join these steps into one object and how to search for the best settings of a model. They apply to every model on the map.

There are also mixed forms that you will meet in Module 5. In semi-supervised learning only a small part of the data has labels. In self-supervised learning the labels are made from the data itself: a large language model learns by predicting the next word of a text, and the "right answer" is simply the word that really comes next.

Try it yourself

Put every model in its box of the map. (a) k-means. (b) Logistic regression. (c) Ridge regression. (d) Principal component analysis (PCA).

Show a hint
Look at the answer the model gives, not at its name.
Show the solution

Answer: (a) clustering; (b) classification; (c) regression; (d) dimensionality reduction.

k-means finds groups, and PCA describes the data with fewer columns: both are unsupervised. Ridge regression predicts a number. Logistic regression carries "regression" in its name, but its answer is a class.

9Classification and regression

Both are supervised learning: both learn from examples with known answers. They differ in what kind of answer is predicted.

Classification: spam or not spamSample emails placed by how many links they have and how many words like FREE or WIN they use. A dashed boundary separates spam from not spam.05100246810Links in the emailWords like FREE or WINNot spamSpam

Classification

the model learns a border

Regression: predicting a house price from its sizeTwelve sample houses. A straight line fitted to them predicts about 171 thousand for a new 95 square meter house.60110160210260406080100120140Size (m²)Price (thousands)45 m², 82k52 m², 95k60 m², 110k68 m², 118k75 m², 140k83 m², 150k90 m², 162k98 m², 175k105 m², 190k112 m², 198k120 m², 215k130 m², 232kNew house: 95 m², predicted about 171kNew house: about 171k

Regression

the model learns a line (or a curve)

Left, classification: the answer is a category. The model learns a border (the dashed line) between the classes, and a new email gets the class of the side it falls on. Right, regression: the answer is a number. The model learns a line through the data, and the price of a new flat is read off the line.

9.1Regression

In regression the target is a number on a continuous scale. The answer could be 118, or 118.4, or 121.75: every value in a range is possible, and it makes sense to say that one answer is larger than another or that a prediction was wrong by 5.

The model learns a line, a curve or a surface that passes close to the data. A new sample is placed on it and the value is read off.

Typical regression tasks: the price of a flat or a car, the sales of next month, the temperature tomorrow, the time a delivery takes, the amount of electricity a city needs in the next hour, the age of a person in a photograph.

How good is a regression model? You measure how far the predictions are from the true values, for example the average size of the error. Topic 22 introduces these measures.

9.2Classification

In classification the target is a category from a fixed list. The categories are called classes. The answer is one of them; there is nothing in between.

  • Binary classification: two classes. Spam or not spam, ill or healthy, will repay or will not repay. Most classification tasks in business are of this kind.
  • Multiclass classification: more than two classes. The digits 0 to 9, three species of a flower, the language of a text.

The model learns borders between the classes. A new sample falls on one side of a border and gets the class of that side. Most classifiers can also say how sure they are: "spam with probability 0.93". That is the probability of Topic 16 at work, and it is often more useful than the bare answer.

How good is a classification model? You count how often it is right, and you look at which kinds of mistakes it makes: a spam email that reaches the inbox is a small problem, an important email that goes to the spam folder is a larger one. Topic 28 is about these measures.

9.3The difference, side by side

The difference, side by side
RegressionClassification
The target isa numbera category (a class)
Question"How much?", "How many?", "How long?""Which one?", "Yes or no?"
Possible answersany value in a rangeone of a fixed list
What the model learnsa line or a curve through the databorders between the classes
A wrong answeris wrong by some amount (a prediction of 120 for 118 is nearly right)is simply wrong (but the probability shows how sure the model was)
How it is measuredthe size of the errors (Topic 22)the share of right answers and the kinds of mistakes (Topic 28)
First model in this courselinear regression (Topic 22)logistic regression (Topic 27)
Examplesprice, temperature, sales, travel timespam, illness, species, digit

9.4How to decide

Look at the target column and ask: is it a quantity, or is it a name?

  • A quantity that you could put on a ruler or add up: regression.
  • A name for a group: classification.

Two cases that confuse beginners:

  • Numbers that are only names. The classes of the digit task are 0, 1, ..., 9. These are numbers, but they are used as names: a "7" is not "a bit more than a 6". The task is classification. The same holds for a postal code or for a column where 0 means "stayed" and 1 means "left".
  • The same subject, two tasks. "What mark will the student get in the exam?" is regression (a number from 0 to 100). "Will the student pass?" is classification (pass or fail). The data is the same; the question decides. A regression task can always be turned into a classification task by cutting the scale into classes, but information is lost on the way.

Regression or classification?

1 of 8

How many minutes will this delivery take?

Try it yourself

(a) Predicting the number of visitors of a museum tomorrow: regression or classification? (b) Deciding whether a card payment is fraud: regression or classification? (c) A model says in which of four languages a text is written. How many classes does the task have? (d) Is the task of (c) binary or multiclass?

Show a hint
A quantity or a name? Binary means exactly two classes.
Show the solution

Answer: (a) regression; (b) classification; (c) 4; (d) multiclass.

A number of visitors is a quantity: regression. "Fraud" and "not fraud" are two names: binary classification. Four languages are four classes, more than two: multiclass classification.

10The machine learning workflow

A machine learning project is much more than "train a model". The training itself is often only a few lines of code. Most of the time goes into understanding the problem and preparing the data. The steps are these:

  1. Define the problemwhat is predicted, and how success is judged
  2. Collect the datadata that contains the answer
  3. Explore and clean the datalook at it, then repair it
  4. Feature engineeringbetter input columns
  5. Split: training and test dataput the test data aside
  6. Preprocessingencode, scale, fill gaps
  7. Train the modelfit on the training data
  8. Evaluate the modelmeasure on the test data
  9. Deploy and monitoruse it, and watch it

Not good enough at step 8? Go back: more data, better cleaning, other features, another model. Only then step 9.After deployment the world changes, and the circle starts again.

The nine steps of a machine learning project. The steps are numbered in the order of the work; after the evaluation the work usually goes back to earlier steps before the model is good enough to be deployed.

10.1Step 1: Define the problem

Before any data: what exactly should be predicted, for whom, and what will be done with the prediction? "Use AI for our customers" is not a problem. "Predict, at the start of each month, which customers will probably cancel in that month, so that we can call them" is one.

In this step you decide:

  • the target: what is predicted;
  • the type of task: supervised or unsupervised, regression or classification (Parts 4 to 9);
  • the measure of success: how you will know that the model is good enough to be used;
  • whether machine learning is needed at all (Part 1).

A wrong decision here cannot be repaired later by a better algorithm.

10.2Step 2: Collect the data

Find or create the data that contains the answer: databases of the company, CSV and Excel files, public datasets, measurements of sensors, data collected from websites or through questionnaires. For a supervised task the data must contain the target; if it does not, somebody has to label it.

Two questions matter more than the number of rows. Is the data representative, that is, does it look like the cases the model will meet later? A model trained only on flats in the city centre will be poor for flats in villages. And is it allowed to use the data? Personal data is protected by law and by simple respect for the people it describes.

10.3Step 3: Explore and clean the data

Real data is messy. In this step you first look at it, then repair it.

  • Exploring (often called exploratory data analysis, EDA): how many rows and columns, what types, the mean, the median and the spread of every column (Topic 18), histograms and scatter plots (Topic 12), the correlation between columns (Topic 20). The aim is to understand the data and to notice problems.
  • Cleaning: remove duplicate rows, repair wrong data types, make spellings uniform ("Baku", "baku", "BAKU"), decide what to do with missing values and with impossible values (an age of 250). This is the work of Topic 11.

People who work in the field often say that this step and the next ones take most of the time of a project. That matches the experience of almost everyone: the model is the short part.

10.4Step 4: Feature engineering

Feature engineering means creating better input columns from the ones you have, using knowledge about the subject. The model can only use what the columns show it.

  • From a date of birth, make the age.
  • From a date and time, make the day of the week and "is it a holiday?".
  • From the price and the area of a flat, make the price per square metre.
  • From the text of an email, make the number of exclamation marks.

It also includes choosing which columns to keep. A column with the customer's identification number carries no pattern and should be left out.

One strict rule: a feature must be something you will know at the moment of the prediction. If you predict whether a customer will leave next month, a column "date of cancellation" cannot be a feature: it is the answer in disguise. Using such information is called data leakage, and it produces models that look perfect in the test and fail in real use.

10.5Step 5: Split the data into a training part and a test part

Before the model sees anything, a part of the data is put aside:

Training data: the model learns from itTest data: kept hidden until the end
Twenty pieces of data. Sixteen of them (80 percent) are the training data, used in steps 6 and 7. Four (20 percent) are the test data, used only in step 8.
  • The training data is what the model learns from.
  • The test data is locked away and used only once, at the end, to measure how well the model works on data it has never seen.

Why? Think of an exam. If the students get the exam questions with the answers a week before, a high mark proves nothing: they may have learned the answers by heart. Only new questions show whether they understood. A model that is tested on the rows it was trained on is in the same position. It can remember the answers without having found the pattern, and its mark would be far too good. This failure has a name, overfitting. Topic 23 is about both: how to split the data in the right way, and how to recognise and avoid overfitting.

10.6Step 6: Preprocessing

Preprocessing turns the cleaned data into the form that the algorithm needs. Algorithms calculate with numbers, and many of them are sensitive to the scale of the numbers.

  • Encoding: categories become numbers. A column with "Baku", "Ganja", "Sumgait" is turned into numerical columns.
  • Scaling: columns are brought to a similar range. An age (20 to 70) and a salary (500 to 9,000) should not be compared as they are, because the salary would dominate only through its large numbers. The z-score of Topic 18, (x - mean)/standard deviation, is the most common way.
  • Filling missing values with a number such as the mean or the median of the column.

Why does this come after the split? Scaling and filling learn something from the data: the mean, the standard deviation, the median. These numbers must be calculated from the training data only and then applied, unchanged, to the test data. If they were calculated from all rows, information about the test data would flow into the training, and the test would no longer be honest. This is another form of data leakage. Topic 24 teaches scaling in detail, and Topic 25 teaches encoding and the handling of outliers.

Cleaning, feature engineering, preprocessing: what is the difference? The three are neighbours, and in everyday speech people do not always separate them. A useful way to think of them: cleaning repairs the data (wrong and missing entries), feature engineering adds meaning (new, better columns), preprocessing changes the form (numbers on a comparable scale that the algorithm can use).

10.7Step 7: Train the model

Now, and only now, the model. You choose one or several algorithms that fit the type of task (the map of Part 8), set their hyperparameters, and train them on the training data. In scikit-learn the training is a single line, as Part 11 shows.

It is good practice to begin with a simple model, such as linear regression or logistic regression. It gives a first result quickly, it is easy to understand, and it is the line that every more complicated model must beat. This first simple result is called a baseline.

10.8Step 8: Evaluate the model

The trained model predicts the test data, and the predictions are compared with the true answers. The result is expressed in a metric that fits the task: the size of the errors for regression, the share of right answers and the kinds of mistakes for classification (Topic 28).

Then the honest question: is this good enough for the purpose of Step 1? Usually the first answer is "not yet". You go back: collect more data, clean better, build other features, try another model, change the hyperparameters. This loop, the line under the picture of the steps, is the normal way of working. A machine learning project is a circle, not a straight line.

(When you compare many models and settings, you need a third part of the data, the validation data, or the method called cross-validation, so that the test data stays untouched until the very end. Topic 23 explains this.)

10.9Step 9: Deploy and monitor

A model in a notebook helps nobody. Deployment means putting it where it is used: inside a website, a telephone application, the software of a bank.

After that, the model has to be monitored. The world changes: prices rise, customers behave differently, senders of spam invent new tricks. A model that was good last year slowly becomes worse, because the new data no longer looks like the data it learned from. When that happens, it is trained again with fresh data, and the circle starts again.

10.10The whole workflow in one table

The whole workflow in one table
StepQuestion it answersWhere you learn it
1. Define the problemWhat do we predict, and how will we judge it?this lesson
2. Collect the dataWhere is the data, and does it contain the answer?Topics 6 and 10 (reading files)
3. Explore and cleanWhat does the data look like, and what is wrong with it?Topics 11, 12, 18, 20
4. Feature engineeringWhich columns help the model?Topics 24 and 25
5. SplitWhich rows are kept for the final test?Topic 23
6. PreprocessingHow does the data get the form the algorithm needs?Topics 24, 25 and 42
7. TrainWhich model, with which settings?Topics 22, 26, 27, 29 to 40, 42 to 44
8. EvaluateHow good is it on new data?Topics 23 and 28
9. Deploy and monitorDoes it still work in real use?the capstone of Module 5

A remark about the order. In real projects the steps overlap: you clean a little while exploring, and you return to the features after the first evaluation. Books also draw the picture in slightly different ways. What must never change is this: the test data is separated before anything is learned from the data, and it is used only for the final evaluation.

Which step of the workflow is it?

1 of 8

You remove the duplicate rows and repair the spellings "Baku", "baku" and "BAKU".

Try it yourself

A dataset has 1,000 rows. It is split so that 20 percent of the rows become the test data. (a) How many rows are in the test data? (b) How many rows are in the training data? (c) The mean and the standard deviation for scaling are calculated from how many rows? (d) A model predicts whether a customer will leave next month. May the column "date of cancellation" be used as a feature?

Show a hint
Whatever learns from data sees the training data only. A feature must be known at the moment of the prediction.
Show the solution

Answer: (a) 200; (b) 800; (c) 800; (d) no.

Twenty percent of 1,000 rows are 200 rows, and 800 remain for the training. The mean and the standard deviation are learned from the data, so they come from the 800 training rows only and are then applied to all rows. The date of cancellation exists only after the customer has left: it is the answer in disguise. Both mistakes are forms of data leakage.

11scikit-learn basics

This part is a first meeting with the library. It shows one very small example, so that you have seen the pattern once. The real work with code begins in Topic 22.

11.1What scikit-learn is

scikit-learn is the standard Python library for machine learning. It is free and open source, and it contains almost every model of this module, together with the tools for splitting, preprocessing and evaluating. It is built on NumPy (Topics 8 and 9) and works directly with pandas DataFrames (Topics 10 and 11).

Two names are in use, and they confuse beginners: the library is installed under the name scikit-learn, and in code it is imported under the name sklearn.

On this website nothing has to be installed: the Python in your browser loads scikit-learn the first time an example imports it. In Google Colab and in Anaconda it is already installed.

11.2The library follows the map and the workflow

scikit-learn is divided into parts, and you import the tool you need from its part. You do not need to learn the names now. Notice only that every box of the map (Part 8) and every step of the workflow (Part 10) has its place:

The library follows the map and the workflow
You want toPart of scikit-learnTopic
split the data into training and test datasklearn.model_selection23
scale and encode featuressklearn.preprocessing24, 25
train a linear or logistic regressionsklearn.linear_model22, 26, 27
train a decision tree or a random forestsklearn.tree, sklearn.ensemble29 to 31
train k-nearest neighbours, Naive Bayes, a support vector machinesklearn.neighbors, sklearn.naive_bayes, sklearn.svm32 to 36
train a boosting modelsklearn.ensemble (XGBoost, CatBoost and LightGBM are libraries of their own that follow the same pattern)37 to 40
join the steps into a pipeline, and search for the best settingssklearn.pipeline, sklearn.compose, sklearn.model_selection42
find clusterssklearn.cluster43, 44
reduce the number of columnssklearn.decomposition44
measure the quality of a modelsklearn.metrics22, 28

11.3The data: X and y

scikit-learn expects the data in the two pieces of Part 3:

  • X: the features, a table with one row per sample and one column per feature. It must be a table (two-dimensional), even when there is only one feature.
  • y: the target, one value per sample (one-dimensional). An unsupervised model gets no y.

11.4One pattern for every model

Every model in scikit-learn is used in the same three steps. Here they are with the five students of Topic 20:

Python
import pandas as pd
from sklearn.linear_model import LinearRegression

students = pd.DataFrame({
    "hours": [2, 4, 5, 6, 8],
    "mark": [50, 60, 65, 75, 80],
})
X = students[["hours"]]     # the features: a table
y = students["mark"]        # the target: one column

model = LinearRegression()      # 1. create the model
model.fit(X, y)                 # 2. train it on the data

new_student = pd.DataFrame({"hours": [7]})
print(model.predict(new_student))   # 3. predict for new data

Output

[76.5]

Change it and run: change the 7 in new_student to 3, then to 9, and run the example again. The first run loads scikit-learn and takes a little longer.

  1. Create the model: model = LinearRegression(). At this moment the model is empty. It knows what kind of rule it is looking for (a line), but it has not seen any data. The brackets are the place for the hyperparameters.
  2. Train it: model.fit(X, y). This is the learning. The model receives the features and the right answers and finds the best line.
  3. Predict: model.predict(new_student). The trained model is given new features and returns its answers.

The prediction for 7 hours is 76.5, exactly what you calculated by hand in Topic 20. scikit-learn found the same line, y^=39.75+5.25 x\hat{y} = 39.75 + 5.25\,x.

One detail about X: students[["hours"]] is written with two pairs of brackets, because that gives a table with one column (Topic 10). With one pair it would be a single column, and scikit-learn would refuse it.

Here is the strength of the library. To use a completely different model, a decision tree or a random forest, you change only the line that creates the model. fit and predict stay as they are. Once you know the pattern, the code of every coming lesson will look familiar, and you can give your attention to the ideas: how the model learns, when it fails, and how to judge it.

11.5The words of the interface

The words of the interface
WordWhat it doesYou will use it from
fit(X, y)learns from features and right answers (supervised models)Topic 22
fit(X)learns from features only (unsupervised models, scalers)Topics 24 and 43
predict(X)gives the answers of a trained model for new samplesTopic 22
score(X, y)predicts, compares with the true answers and returns one number for the qualityTopic 22
transform(X)changes the data with what was learned, for example scales it (preprocessing tools)Topic 24
train_test_splitputs a part of the rows aside as test dataTopic 23

Two rules complete the picture:

  • Train on the training data, judge on the test data. fit gets the training data only. That is Step 5 of the workflow in code.
  • A name that ends in an underscore was learned from the data. After fit, the line that the model found is stored in model.coef_ (the slope, 5.25) and model.intercept_ (39.75). Settings that you chose yourself have no underscore.

Try it yourself

Use the example above. (a) What does the model predict for a student who studies 3 hours? (b) And for 9 hours? Change the number in the example and run it, or calculate with the line the model found. (c) Which line of the example is the learning?

Show a hint
The model found the line y^=39.75+5.25 x\hat{y} = 39.75 + 5.25\,x.
Show the solution

Answer: (a) 55.5; (b) 87; (c) the line with fit.

y^=39.75+5.25×3=39.75+15.75=55.5y^=39.75+5.25×9=39.75+47.25=87\begin{aligned} \hat{y} &= 39.75 + 5.25 \times 3 = 39.75 + 15.75 = 55.5 \\[4pt] \hat{y} &= 39.75 + 5.25 \times 9 = 39.75 + 47.25 = 87 \end{aligned}

LinearRegression() only creates an empty model. fit is the learning: there the model sees the data and finds the line. predict uses the line. One remark about (b): the five students studied between 2 and 8 hours, so 9 hours lies outside the data. As Topic 20 said, a prediction outside the range of the data should be read with care.

12Common mistakes

Common mistakes
MistakeWhy it is wrongRight
"Machine learning and artificial intelligence are the same thing."Machine learning is one part of AI: the part in which rules are learned from data.AI is the wider term; deep learning is in turn a part of machine learning.
"A model with more data is always right."A model learns the patterns of its data, including its errors and gaps.Poor or unrepresentative data gives a poor model: garbage in, garbage out.
Calling a task "supervised" because a person supervises the computer.The word is about the data, not about people.Supervised means: the data contains the right answer for every sample.
"Logistic regression is a regression model."Its answer is a class.It is a classification model, in spite of its name.
Treating class numbers as quantities: "class 2 is twice class 1".The numbers are only names of the classes.A target that names groups is a classification target, whatever symbols are used.
Using regression for "will the customer leave: yes or no?"The answer is a category.Classification. (Regression would fit "how many months will the customer stay?")
Measuring the model on the data it was trained on.The model may have learned the answers by heart; the result is far too good.Keep test data apart and evaluate on it.
Scaling all the data before the split.The mean and the standard deviation then contain information from the test data (data leakage).Split first; calculate them from the training data; apply them to both parts.
Using a feature that is known only after the event.The model gets the answer in disguise and fails in real use.Use only what is known at the moment of the prediction.
Starting with the most complicated model.Without a simple first result you cannot tell whether the complicated one helps.Begin with a simple baseline, then improve.
Using predict before fit.An untrained model has learned nothing; scikit-learn raises an error.Always fit first.
Training the model on the test data.The test data must never be used for training.fit on the training data only.
X = students["hours"]A single column is one-dimensional; scikit-learn needs a table.X = students[["hours"]]
pip install sklearn or import scikit-learnThe two names are the other way round.pip install scikit-learn, and in code import sklearn or from sklearn... import ....
Thinking that training the model is most of the work.Defining the problem and preparing the data take most of the time, and decide most of the quality.Give the first steps of the workflow the attention they need.

13Check yourself

Twenty questions about the ideas of this lesson. Every question has one right answer. Try to answer before you read the explanation.

Question 1

1.What is the main difference between ordinary programming and machine learning?

Question 2

2.Which statement about artificial intelligence (AI), machine learning (ML) and deep learning (DL) is right?

Question 3

3.A table has one row for every customer, with the columns age, city, monthly spending and "left the company (yes/no)". The company wants to predict who will leave. What is "left the company"?

Question 4

4.For which of these tasks is machine learning not a sensible choice?

Question 5

5.What makes a task a supervised learning task?

Question 6

6.A shop has data about what its customers buy and wants to find out what kinds of customers it has. There is no column that says to which kind a customer belongs. Which type of learning is this?

Question 7

7.Which words describe reinforcement learning?

Question 8

8.An estate agency wants to predict the selling price of a flat from its area, its number of rooms and its district. What kind of task is this?

Question 9

9.A model receives a photograph of a handwritten digit and answers with the digit, 0 to 9. What kind of task is this?

Question 10

10.Which of these models is used for classification, although its name suggests something else?

Question 11

11.Which pair consists of two unsupervised methods?

Question 12

12.Why is a part of the data kept apart as test data?

Question 13

13.A team predicts whether a patient will have to return to the hospital within 30 days. One of its features is "number of days until the patient returned". What is the problem?

Question 14

14.A column "salary" has values from 500 to 9,000, and a column "age" has values from 20 to 70. Bringing both to a comparable scale is a part of which step?

Question 15

15.Which order of steps is right?

Question 16

16.In scikit-learn, what shape must the features X have?

Question 17

17.What does model.fit(X_train, y_train) do?

Question 18

18.After model.fit(X, y) a linear regression model has the attributes model.coef_ and model.intercept_. What does the underscore at the end of the names say?

Question 19

19.Which three steps, in this order, are used for every supervised model in scikit-learn?

Question 20

20.k-means is an unsupervised model. What does it receive when it is trained with fit?

0 of 20 answered.

14Summary

Summary
IdeaIn one sentence
Machine learningPrograms that find patterns in data and use them for predictions, without hand-written rules
AI, ML, deep learningDeep learning is a part of machine learning, which is a part of artificial intelligence
Sample, feature, targetA row; a column that describes it; the column to be predicted
Model, training, predictionThe learned rule; finding it from data; using it on a new sample
Supervised learningThe data contains the right answers; the model learns to predict them
RegressionA supervised task with a number as the answer
ClassificationA supervised task with a category as the answer
Unsupervised learningNo answers in the data; the model finds groups or a simpler description
ClusteringDividing the samples into groups of similar samples
Dimensionality reductionDescribing the data with fewer columns
Reinforcement learningAn agent learns from rewards which actions are best
The workflowDefine the problem, collect, explore and clean, engineer features, split, preprocess, train, evaluate, deploy and monitor
Test dataRows kept apart to measure the model on data it has not seen
Data leakageInformation that the model would not have in real use reaches the training
scikit-learnCreate the model, fit, then predict (or transform), and score to evaluate

Rules to keep

  1. Look at the target first. Is there one? Then the task is supervised. Is it a number or a category? That decides between regression and classification.
  2. A model is only as good as its data.
  3. The test data is separated before anything is learned, and it is used only for the final evaluation.
  4. Whatever learns from data (a model, a scaler) is fitted on the training data only.
  5. Begin with a simple model.
  6. In scikit-learn every model follows the same pattern: create, fit, predict.

What comes next

The module follows the workflow of this lesson, so that every new idea arrives when it is needed:

What comes next
TopicsWhat you learn
22The first model: linear regression
23Judging a model honestly: train/test split, cross-validation, overfitting and underfitting
24, 25Preparing the features: scaling numerical values, then encoding categories and handling outliers
26Keeping a model from overfitting: Ridge and Lasso regression
27, 28The first classifier, logistic regression, and the measures for classifiers
29 to 36More models, for classification and for regression: decision trees, random forests, k-nearest neighbours, Naive Bayes, support vector machines, and voting
37 to 40The boosting methods, for classification and for regression: gradient boosting, XGBoost, AdaBoost, CatBoost, LightGBM
41Data in which one class is rare: imbalanced datasets
42Putting the steps together: pipelines and hyperparameter tuning
43, 44Unsupervised learning: clustering and PCA

Topic 22 opens the first box of the map: linear regression. You already know its result from Topic 20, the line through the five students. The next lesson shows where the line comes from, how to use several features at once, how to measure the quality of a regression model, and how to build it with scikit-learn.