Quick answer: To learn machine learning fundamentals, start with a tiny dataset, predict a number with linear regression, predict a class with a decision tree and group points with K-Means. Then learn to split data, measure errors, spot overfitting and use a pipeline. This tutorial takes you through those steps with short Python programs whose results you can check yourself.
This machine learning fundamentals tutorial starts with five students and their marks. The data is tiny on purpose. You can check every answer with a pen before you trust the computer.
By the end, you will have built three kinds of model and tested them fairly. You will also know the words that interviewers use. Type each program yourself instead of only reading it.
What is machine learning?
In normal programming, you write the rules. In machine learning, you give the computer examples and it finds a rule.
Suppose you want to predict exam marks from study hours. You do not know the exact formula. But you have past students, with their hours and marks. A model can find the pattern and use it for a new student.
| Word | Simple meaning | In our example |
|---|---|---|
| Feature | What you know | Study hours |
| Label or target | What you want to predict | Marks |
| Model | The rule learned from data | A straight line |
| Training | Finding the rule | Fitting the line |
| Prediction | Using the rule | Marks for 6 hours |
The main types
- Supervised learning: every example has an answer. Predicting a number is regression. Predicting a group is classification.
- Unsupervised learning: there are no answers. The model looks for structure, such as groups of similar shoppers.
- Reinforcement learning: a program learns by trying actions and getting rewards. It is useful to know the name, but leave it for later.
Step 1: Set up Python
You need Python and scikit-learn. On your computer, run:
python -m pip install scikit-learn pandas
Or use a free online notebook, where these libraries are often ready. If Python is new to you, practise loops and lists with Python basics problems first.
Step 2: Predict a number
Here are five students:
| Hours | Marks |
|---|---|
| 1 | 45 |
| 2 | 50 |
| 3 | 60 |
| 4 | 65 |
| 5 | 70 |
Marks rise as hours rise. We want the straight line that fits best:
marks = slope × hours + intercept
The slope tells us how many marks each extra hour is linked with. The intercept is the line's value at zero hours. Let us find both without a library:
hours = [1, 2, 3, 4, 5]
marks = [45, 50, 60, 65, 70]
mean_h = sum(hours) / len(hours)
mean_m = sum(marks) / len(marks)
top = sum((h - mean_h) * (m - mean_m)
for h, m in zip(hours, marks))
bottom = sum((h - mean_h) ** 2 for h in hours)
slope = top / bottom
intercept = mean_m - slope * mean_h
print(slope, intercept) # 6.5 38.5
print(slope * 6 + intercept) # 77.5
Check it by hand. The average hours are 3 and the average marks are 58. The top sum is 65 and the bottom sum is 10. So the slope is 65 ÷ 10 = 6.5, and the intercept is 58 − 6.5 × 3 = 38.5.
For 6 hours, the line predicts 77.5 marks. That is your first trained model.
Now do the same with scikit-learn:
from sklearn.linear_model import LinearRegression
X = [[1], [2], [3], [4], [5]]
y = [45, 50, 60, 65, 70]
model = LinearRegression()
model.fit(X, y)
print(round(model.coef_[0], 2)) # 6.5
print(round(model.intercept_, 2)) # 38.5
print(round(model.predict([[6]])[0], 2)) # 77.5
Notice that X is a list of lists. Each inner list is one student, and it can hold many features. You will see fit and predict in almost every scikit-learn model.
Common mistake: Predicting far outside the data. For 12 hours, this line gives 116.5 marks. If the exam is out of 100, that is impossible. The model knows only the 1 to 5 hour pattern.
Step 3: Measure the error
How far is each prediction from the real mark?
| Hours | Real | Predicted | Size of error |
|---|---|---|---|
| 1 | 45 | 45.0 | 0.0 |
| 2 | 50 | 51.5 | 1.5 |
| 3 | 60 | 58.0 | 2.0 |
| 4 | 65 | 64.5 | 0.5 |
| 5 | 70 | 71.0 | 1.0 |
Add the errors and divide by five: 5 ÷ 5 = 1. This is the mean absolute error, or MAE. On average, the line misses by one mark.
But these are the same students we trained on. A fair test needs new students. We will fix that in Step 6.
Step 4: See how a model learns
Our formula found the best line in one go. Many models cannot do that. They begin with a guess, measure the error and take small steps that reduce it. This is gradient descent.
Imagine the error is (w - 3) ** 2. The lowest error is at w = 3. The slope of this curve at any point is 2 * (w - 3).
w = 0.0
learning_rate = 0.1
for step in range(20):
gradient = 2 * (w - 3)
w = w - learning_rate * gradient
print(round(w, 2)) # 2.97
The program starts at 0 and walks towards 3. The learning rate controls the size of each step. If it is too small, learning is slow. If it is too large, the steps can jump past the answer and never settle.
Step 5: Predict a class
Now predict pass or fail. Here 0 means fail and 1 means pass. A decision tree learns yes-or-no questions from the data.
from sklearn.tree import DecisionTreeClassifier, export_text
X = [[1], [2], [3], [7], [8], [9]]
y = [0, 0, 0, 1, 1, 1]
tree = DecisionTreeClassifier(random_state=0)
tree.fit(X, y)
print(tree.predict([[4], [6]])) # [0 1]
print(export_text(tree, feature_names=["hours"]))
The tree prints its rule:
|--- hours <= 5.00
| |--- class: 0
|--- hours > 5.00
| |--- class: 1
The tree placed its split halfway between 3 and 7. So 4 hours is predicted as fail and 6 as pass. Real data overlaps more, so trees need more questions and more care.
Accuracy is not enough
Suppose another model checks 100 messages for spam. It gets these results:
| Predicted spam | Predicted safe | |
|---|---|---|
| Really spam | 8 | 4 |
| Really safe | 2 | 86 |
tp, fn, fp, tn = 8, 4, 2, 86
accuracy = (tp + tn) / (tp + tn + fp + fn)
precision = tp / (tp + fp)
recall = tp / (tp + fn)
f1 = 2 * precision * recall / (precision + recall)
print(round(accuracy, 2)) # 0.94
print(round(precision, 2)) # 0.8
print(round(recall, 2)) # 0.67
print(round(f1, 2)) # 0.73
Read it in words:
- Accuracy: 94 of 100 answers were right.
- Precision: of 10 messages called spam, 8 really were.
- Recall: of 12 spam messages, we found 8.
- F1: one number that balances precision and recall.
Interview note: Say which mistake costs more before naming a metric. A disease check usually cares about missed cases. A spam filter also cares about hiding a useful email.
Step 6: Test on new data
The basic rule of testing is simple: train on one part, test on another. scikit-learn includes the Iris flower dataset, which is handy for practice.
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42
)
model = make_pipeline(
StandardScaler(), LogisticRegression(max_iter=1000)
)
model.fit(X_train, y_train)
print(len(X_train), len(X_test)) # 120 30
print(model.score(X_test, y_test)) # your test accuracy
Iris has 150 flowers, so a 20% test set has 30. Run the last line and note your own score.
Three choices here are good habits:
stratify=ykeeps the same mix of flower types in both parts.random_state=42repeats the same split each time you run it.- The pipeline makes the scaler learn from training rows only.
Overfitting and underfitting
A student who memorises answers may fail a new paper. A model can do the same. This is overfitting: excellent on training data, weaker on new data.
Underfitting is the opposite. The model is too simple and does badly on both. Compare the two scores to tell them apart:
print(model.score(X_train, y_train))
print(model.score(X_test, y_test))
Look at the gap here for learning only. When you choose settings, use cross-validation on the training data and keep the test set for the end. The list of machine learning fundamentals mistakes explains this with fixes.
Step 7: Find groups without labels
Now suppose you have six customers. Each has visits per month and money spent in hundreds of rupees. Nobody told you which group they belong to.
from sklearn.cluster import KMeans
X = [[1, 2], [2, 1], [1, 1], [9, 10], [10, 9], [10, 10]]
model = KMeans(n_clusters=2, n_init=10, random_state=0)
labels = model.fit_predict(X)
print(labels[0] == labels[1]) # True
print(labels[0] == labels[5]) # False
The first two customers are in the same group. The first and last are not. The group numbers have no meaning by themselves. "0" is not better than "1", and the numbers could be swapped.
K-Means puts each point with the nearest centre, moves each centre to the average of its points, and repeats. You must choose the number of groups and usually scale the features.
Machine learning fundamentals examples: choose a model
| Your question | Type | First model to try | First measure |
|---|---|---|---|
| What will this house cost? | Regression | Linear regression | MAE |
| Is this email spam? | Classification | Naive Bayes or logistic regression | Precision and recall |
| Will this machine fail? | Classification | Decision tree or random forest | Recall |
| Which customers are alike? | Clustering | K-Means | Are the groups useful? |
Start simple and beat a basic guess before trying a bigger model. For more stories from business, see these machine learning real-time examples.
Practice tasks
Try these without copying:
- Change the fifth student's marks from 70 to 90. Recalculate the slope. Why did it change?
- Write code to calculate the MAE in Step 3. You should get 1.0.
- Set the learning rate to 0.01 in Step 4. How close do you get in 20 steps?
- Make a confusion matrix where accuracy is 95% but recall is zero.
- Use Iris with a decision tree. Compare depths 1, 2 and 4 using cross-validation.
For task 1, the new slope is 10.5. If you got that, you understand the formula.
Pro tip: Before you run a cell, write your guess. When the answer surprises you, stop and find out why. That moment is where the learning happens.
Where to go after this machine learning fundamentals tutorial
Build one project with a real question. Then study the parts that the project forces you to need. This project-based learning gives you stronger memories than reading ten more definitions.
If you want to learn machine learning fundamentals in a fixed time, use our 12-week study plan. Revise with the ML cheat sheet and test yourself with basic ML interview questions. For guided study, our machine learning course guide explains what to expect. Good material on machine learning fundamentals for beginners should always make you write code and check the result.
Frequently asked questions
Can I learn machine learning without knowing Python?
You can understand the ideas, but you need basic Python to build models. Learn variables, lists, loops and functions first. Two to four weeks of daily practice is often enough to follow this tutorial.
How much maths do I need to start?
School-level maths is enough to begin. You should know averages, straight-line graphs and basic probability. Vectors and gradients become easier once you see them used in a model.
Which machine learning algorithm should I learn first?
Start with linear regression because you can see the line and calculate the answer by hand. Learn a decision tree next for classification. Then try K-Means to understand learning without labels.
What is the difference between training and testing?
Training lets the model learn from examples. Testing checks it on examples it has not seen. Keeping them separate tells you whether the model learned a useful pattern or only memorised the data.
What should I build after this tutorial?
Choose a small public dataset and predict one column. Build a simple baseline, train two models, compare them with cross-validation and write down where they fail. Put the notebook and a clear README on GitHub.
Know what to learn after this tutorial. Follow the machine learning engineer roadmap, or book a free demo class for the project-based Artificial Intelligence course.
