Module 1 · Beginner · Getting started with machine learning

Machine learning for beginners, with Python

Machine learning for beginners: how models learn from data, the three types, your first Python model, plus practice and interview questions.

By theprogrammers team · · 11 min read

Your email app moves a message to spam before you see it. Nobody at the company wrote a rule saying "an email with these exact words is spam". Instead, the app was shown millions of emails that people had already marked as spam or not spam, and it worked out the patterns itself. That's machine learning for beginners in one sentence: instead of writing the rules yourself, you show the computer examples and let it find the rules from the data.

The same idea powers product recommendations, voice assistants, UPI fraud checks and the AI chat tools everyone is talking about. Below you'll see what's actually going on, then train and test two real models in Python.

What you need first: basic Python: variables, lists and functions, as in the Python course. No maths beyond school arithmetic. If Python isn't installed yet, set up a machine learning environment first, or read this lesson now and run the code later.

Key terms

  • Machine learning (ML): building software that learns its behaviour from examples instead of hand-written rules.
  • Features: the inputs the model looks at, such as the words in an email or the size of a house.
  • Label: the answer you want to predict, such as "spam" or the house price.
  • Training: showing the model examples so it can adjust itself. What training produces is the model.
  • Prediction (or inference): using the trained model on new data.

Machine learning for beginners: rules versus learning

Imagine writing a program to flag spam email. The traditional approach is to write rules by hand:

def is_spam(email):
    text = email.lower()
    return "free money" in text or "click here" in text

print(is_spam("Claim your FREE MONEY now"))
print(is_spam("Claim your fr33 m0ney now"))
True
False

email.lower() turns the text into lower case, so "FREE MONEY" still matches "free money". But the second email is obviously spam too, and the rule misses it. Spammers change their wording, and you end up with hundreds of fragile rules.

The machine learning approach is different. You collect thousands of emails already labelled "spam" or "not spam", and a learning algorithm works out which patterns separate the two. The result is a model: a function whose behaviour came from data rather than from rules you typed.

Traditional programmingMachine learning
You provideRulesExamples (data)
The computer producesAnswersRules (a model)
Works well whenThe rules are clearThe rules are hard to write down

The picture shows the swap. In normal programming, the rules go in and answers come out. In machine learning, answers go in with the data, and the rules come out.

Two rows of boxes. Traditional programming: rules and data go into a program, which produces answers. Machine learning: data and answers go into a learning algorithm, which produces rules, called a model.

The three main types of machine learning

Supervised learning

The training data comes with the right answers (labels). The model learns to map inputs to answers.

  • Classification predicts a category: spam or not, which digit is in an image.
  • Regression predicts a number: a flat's rent, tomorrow's temperature.

Most ML used in industry is supervised.

Unsupervised learning

The data has no labels. The model looks for structure on its own, for example grouping customers with similar buying habits (clustering), or compressing many features into a few (dimensionality reduction).

Reinforcement learning

An agent learns by trial and error, getting rewards for good actions. It's used for games and robotics, and to fine-tune large language models with human feedback.

Types of machine learning covers all three in more depth.

Your first machine learning model in Python

Start with something you could do by hand. Six students recorded their study hours and exam scores:

HoursScore
135
245
352
461
570
678

Each extra hour adds roughly 8 or 9 marks. So a student who studies 7 hours should score about 78 + 8.5, around 87. You just learned a rule from examples. Now let a model do the same, with scikit-learn, the standard Python library for classic machine learning:

from sklearn.linear_model import LinearRegression

hours = [[1], [2], [3], [4], [5], [6]]     # features: one list per student
scores = [35, 45, 52, 61, 70, 78]          # labels: the real scores

model = LinearRegression()
model.fit(hours, scores)                   # training: find the best straight line

print(model.predict([[7]]))                # prediction for a new student
print(model.coef_, model.intercept_)       # the rule it learned
[86.73333333]
[8.54285714] 26.93333333333333
  • LinearRegression() creates an empty model that will fit a straight line.
  • Each student's features go in their own inner list, [1], because a student could have several features (hours, sleep, attendance). scikit-learn always expects a table: one row per example, one column per feature.
  • model.fit(...) is the training step. model.predict(...) uses what it learned.
  • coef_ and intercept_ are the rule it found: score ≈ 8.54 × hours + 26.9. That's "about 8.5 marks per hour", the same pattern you spotted by eye.

Three lines do the real work: create a model, fit it on examples, and predict on something new. Almost every scikit-learn model follows this same pattern.

How do you know if a model is good?

A model that memorises its training data can look perfect and still fail on new data. This is called overfitting. Think of a student who memorises last year's answers word for word: perfect on those questions, lost on new ones. To catch it, you always keep some data aside:

  1. Split the data into a training set (often 80%) and a test set (20%).
  2. Train only on the training set.
  3. Measure accuracy on the test set, which the model has never seen.

The test score is the honest estimate of how the model will do in the real world.

scikit-learn does the split for you. This example uses the classic iris flower dataset, which comes with scikit-learn, to predict a flower's species (one of three) from four measurements of its petals and sepals:

Download the data: iris.csv (4 KB), or from the original source, the UCI Machine Learning Repository. The code below loads it for you, so you only need the file to open it in a spreadsheet or work offline: load it with pd.read_csv("iris.csv").

Predict first: a decision tree is a flowchart of yes/no questions that can keep splitting until every training flower is classified correctly. What do you expect its accuracy on the training flowers to be, and will the test flowers score as high?

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier

X, y = load_iris(return_X_y=True)                  # 150 flowers
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42)           # 120 to train, 30 to test

model = DecisionTreeClassifier(random_state=42)
model.fit(X_train, y_train)
print(model.score(X_train, y_train))    # accuracy on data it has seen
print(model.score(X_test, y_test))      # accuracy on data it hasn't
1.0
1.0
  • return_X_y=True gives the features (X, a table of 150 rows and 4 columns) and the labels (y, the species) separately. A capital X is the convention for a table of features; a small y for the labels.
  • test_size=0.2 keeps 20% of the flowers aside for testing.
  • random_state=42 makes the random split the same every time you run it. Any number works; 42 is just a habit.
  • model.score gives the accuracy: the fraction of flowers it labels correctly.

Both scores are 1.0, meaning 100% correct. Iris is a small, clean dataset where the species really are easy to tell apart. On real, messy data, the gap between the training and test scores is what reveals overfitting: a model that scores 0.99 on training data and 0.70 on test data has memorised rather than learned.

Experiment: keep only 10% of the flowers for training by changing test_size=0.2 to test_size=0.9. Predict whether the test score will drop, then run it:

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.9, random_state=42)           # 15 to train, 135 to test

model = DecisionTreeClassifier(random_state=42)
model.fit(X_train, y_train)
print(model.score(X_train, y_train), round(model.score(X_test, y_test), 3))
1.0 0.956

The tree still scores 100% on the 15 flowers it trained on, because it can always memorise a handful of examples. But on new flowers the score drops to 0.956: about 6 of the 135 test flowers are now wrong, where before it got every test flower right. With fewer examples, the rules it learned are rougher. Iris is an easy dataset, so the drop is small here; on harder data it's usually much bigger. More (good) data is one of the most reliable ways to make a model better.

Machine learning, deep learning and AI

  • AI is the broad goal of making computers do things that seem intelligent.
  • Machine learning is the main way modern AI is built: learning from data.
  • Deep learning is a kind of ML that uses large neural networks. It's behind image recognition and large language models.

You don't need deep learning to get started. Many real problems are solved well by simpler models. AI vs machine learning vs deep learning explains how they fit together.

Practice

Try each one before opening the answer.

  1. Is each of these supervised, unsupervised or reinforcement learning? (a) Predicting a flat's rent from its size and area. (b) Grouping shoppers by what they buy, with no labels. (c) Marking emails as spam or not spam. (d) A program learning to play a game by trial and error.
Show the answer

(a) Supervised: regression, because rent is a number. (b) Unsupervised: clustering. (c) Supervised: classification, because the answer is a category. (d) Reinforcement learning.

  1. Predict, then check: in the exam-score example, ask the model for 20 hours of study with model.predict([[20]]). What will it say, and what's wrong with it?
Show the answer

The rule is score ≈ 8.54 × hours + 26.9, so 20 hours gives about 8.54 × 20 + 26.9 ≈ 198. But a score can't go above 100. The model learned a straight line from 1 to 6 hours, and using it far outside that range (extrapolation) gives nonsense. A model is only reliable on data similar to what it was trained on.

  1. Your model scores 0.98 on the training set and 0.62 on the test set. What's happening, and what could you try?
Show the answer

It's overfitting: it has memorised the training data. Try a simpler model (for a decision tree, set max_depth), get more training data, or use fewer, better features.

  1. Why would a spam filter built with machine learning keep working better than the is_spam rule as spammers change their wording?
Show the answer

The rule only catches the exact phrases someone typed in. A model learns from many examples, so it picks up on many weaker signals at once (odd spellings, links, the sender). And when spammers change tactics, you retrain it on new labelled emails instead of writing new rules by hand.

  1. A friend reports 100% accuracy for their model but used the same data for training and testing. Why isn't that convincing?
Show the answer

The model has already seen every answer, so it can score 100% just by memorising, as the iris tree did on its 15 training flowers. Only a score on data the model never saw during training shows whether it learned a pattern that works on new cases.

Interview questions

What is the difference between classification and regression?

Both are supervised learning. Classification predicts a category, such as spam or not spam. Regression predicts a number, such as a price.

What is overfitting, and how do you prevent it?

Overfitting is when a model fits its training data so closely, noise included, that it does badly on new data. You spot it with a held-out test set or cross-validation, and reduce it with simpler models, more data, regularisation or early stopping.

Why do we need a separate test set?

Scoring a model on the data it trained on rewards memorising. A test set the model has never seen gives an honest estimate of how it will perform on new, real data.

Key takeaways

  • Machine learning finds rules from labelled examples instead of you writing them by hand.
  • Supervised learning has labels (classification for categories, regression for numbers); unsupervised learning finds structure without labels; reinforcement learning learns from rewards.
  • In scikit-learn, every model follows the same pattern: create it, fit it on examples, predict on new data.
  • Always judge a model on a test set it never trained on; a big gap between training and test scores means overfitting.
  • More good data usually helps, and models are unreliable far outside the data they learned from.

Frequently asked questions

Can I learn machine learning without a maths background?

Yes, to start. You need school-level maths and some Python, and you pick up statistics, a little linear algebra and calculus as each idea needs them. This course links each maths lesson just before the machine learning lesson that uses it.

Which programming language is best for machine learning?

Python. Almost every ML library (scikit-learn, pandas, PyTorch, TensorFlow) is used from Python, and most tutorials, courses and job descriptions assume it.

How long does it take to learn machine learning?

Building and judging simple models like the ones above takes a few weeks of steady practice if you already know some Python. Becoming job-ready usually takes several months of projects on real datasets.

What to learn next

  1. AI vs machine learning vs deep learning: how the terms fit together, the next lesson.
  2. Types of machine learning: supervised, unsupervised and reinforcement learning with examples.
  3. Brush up on pandas DataFrames, which you'll use for almost every dataset.