All courses › Machine Learning and Data Analysis
Machine Learning and Data Analysis (ML): free practice, theory and problems
Machine learning means letting the computer find patterns in data instead of us writing the rules. You give the model many examples, and it learns a relationship it can apply to new cases: spotting faults on a production line, estimating tomorrow's power use or sorting email.
Contents
1. Data and core concepts
What is it about?
Machine learning means letting the computer find patterns in data instead of us writing the rules. You give the model many examples, and it learns a relationship it can apply to new cases: spotting faults on a production line, estimating tomorrow's power use or sorting email.
In short
- Features are what the model receives. The label is the answer we want it to give.
- Supervised learning: the examples have a known answer . Regression gives a number, classification gives a category.
- Unsupervised learning: no answers. For example clustering, which finds groups.
- Training and test sets: the model learns on training data and is measured on test data it has never seen, often split 80/20.
- Overfitting: the model memorizes the training data, noise included, and does poorly on new data.
- Min–max normalization: gives values between 0 and 1.
- Standardization: gives mean 0 and standard deviation 1.
- Mean squared error: .
What is machine learning?
In ordinary programming we write the rules ourselves. In machine learning we give the computer examples, and it finds the rules – a model – by adjusting parameters so that the error is as small as possible. Three main forms:
- Supervised learning: the data have labels. Regression predicts a number (house price), classification a category (spam/not spam).
- Unsupervised learning: no labels. The model finds structure, for example clusters of similar customers or fewer dimensions (PCA).
- Reinforcement learning: an agent learns by trial and reward – games, robot control.
Data matter most
"Garbage in, garbage out." Most of the work in an ML project is collecting, cleaning and understanding the data:
- Features are the inputs; the target is what we want to predict.
- Missing values must be removed or imputed; outliers must be investigated.
- Categorical variables are converted to numbers, for example with one-hot encoding.
- Scaling (normalisation or standardisation) stops features with large numbers from dominating and helps gradient descent converge faster.
- Bias in the data gives biased models: if a group is under-represented, the model performs worse for it.
Training, validation and test
The data are split into a training set (the model learns), a validation set (choosing model and hyperparameters) and a test set (one final, honest assessment). Test data must never be used during development – otherwise you only measure how well the model has memorised the test set. Cross-validation rotates which part is used for validation and gives a more stable estimate when data are scarce. Also watch out for data leakage: information from the future or from the target sneaking into the features.
Under- and overfitting
- Underfitting: the model is too simple and misses on both training and test data.
- Overfitting: the model memorises the noise in the training data and generalises poorly – low training error, high test error.
- Remedies: more data, a simpler model, regularisation (a penalty on large weights), early stopping and dropout in neural networks.
This is the bias–variance trade-off: simple models have high bias, complex ones high variance. The goal is the balance that gives the lowest error on new data.
How to solve the problems
- Work out what is and what is, and whether the answer is a number or a category.
- For normalization: find min and max (or and ) and insert.
- For error measures: compute the error for each point, square it, and take the mean.
Example
The temperatures 10, 15 and 30 °C are to be min–max normalized. What does 15 become?
- , .
- .
Common mistakes
- Testing the model on the same data it was trained on. It then looks much better than it is.
- Normalizing with min and max from the whole dataset, test data included. That leaks information.
- Believing a more complex model is always better. It can easily overfit.
Concepts in this part
2. Linear regression and gradient descent
What is it about?
The simplest model that learns from data is a straight line: . The model adjusts the weight and the intercept so the line fits the points as well as possible. Exactly the same idea, just with many more weights, is behind large neural networks.
In short
- Model: . is the slope, is the intercept with the -axis.
- Loss function: . The goal is to make as small as possible.
- Least squares gives the answer directly:
- Gradient descent: take a small step against the gradient, over and over:
where is the learning rate.
- For MSE, .
- Coefficient of determination between 0 and 1: how much of the variation in the model explains.
From one to many variables
With several features the model becomes , compactly . Each weight says how much changes when that feature increases by one while the others are held fixed. Polynomial regression adds features such as and and can then fit curves – but the model is still linear in the weights, so the same methods work.
Why squared error?
MSE punishes large errors much harder than small ones, is smooth and has a single minimum for linear regression (the loss surface is a "bowl"). The downside is that outliers have great influence. MAE (mean absolute error) is more robust. The square root of MSE, RMSE, has the same unit as and is easier to interpret.
Gradient descent in practice
The gradient points in the direction where the loss rises fastest; we go the opposite way. Variants:
- Batch: uses all data in each step – stable, but slow on large datasets.
- Stochastic (SGD): one example at a time – fast and noisy, can jump out of poor local minima.
- Mini-batch: for example 32–256 examples per step – the standard in practice, especially for neural networks.
- Momentum and Adam adapt the step size along the way and often converge faster.
An epoch is one pass through the whole training set. Watch a loss curve for training and validation: if training loss falls while validation loss rises, the model is overfitting.
The learning rate
The learning rate is the most important hyperparameter. Too large: the loss oscillates or diverges. Too small: training crawls. Common practice is to start at, say, 0.01 and try ten times larger and smaller, or let decay during training. Scaling the features makes the bowl rounder and gradient descent far more efficient.
Regularisation
- Ridge (L2) adds to the loss: weights shrink towards zero and the model becomes more stable.
- Lasso (L1) adds : some weights become exactly zero, so the model selects features.
From regression to neural networks
A neural network is many linear layers with a non-linear activation function (such as ReLU) in between. Gradients are computed by backpropagation (the chain rule), and the weights are updated with exactly the same gradient descent as here.
How to solve the problems
- Compute the means and .
- Compute the deviations from the mean and insert into the formula for , then .
- For one gradient step: compute the gradient, multiply by and subtract.
Example
The points , and . Find .
- , .
- and .
- , and .
Common mistakes
- Too large a learning rate: the loss jumps back and forth and can blow up. Too small: it takes forever.
- Forgetting the minus sign in the update. We go downhill, towards lower loss.
- Reading a good fit as cause and effect.
Concepts in this part
Practise linear regression and gradient descent in the app →
3. Classification and evaluation
What is it about?
A classification model says "yes" or "no": is the part defective, is the tumour malignant, is the transaction fraud? To know whether the model is good, we must count where it hits and where it misses. And we must choose how strict it should be.
In short
- The confusion matrix counts four outcomes:
true positive (TP), false positive (FP), true negative (TN) and false negative (FN).
- Accuracy: .
- Precision: . Of those the model said yes to, how many were right?
- Recall: . Of all the real positives, how many did the model find?
- F1 score: , a compromise between precision and recall .
- Logistic regression gives a probability with the sigmoid function . Above a threshold (often 0.5) the model says yes.
- k nearest neighbours (k-NN): a new point gets the class of the majority of the nearest points.
Logistic regression
For classification we need a probability between 0 and 1. Logistic regression passes the linear combination through the sigmoid function . If the probability is above a threshold (often 0.5), class 1 is chosen. The model is trained by minimising cross-entropy (log loss), which punishes confident mistakes hard. With many classes, softmax is used.
Other classifiers
- k-nearest neighbours (kNN): look at the classes of the nearest training points. Simple, but slow on large datasets and dependent on scaling.
- Decision trees: a sequence of yes/no questions. Easy to interpret, but overfit easily. Random forests and gradient boosting combine many trees and are among the strongest methods for tabular data.
- Support vector machines (SVM): find the boundary with the largest margin.
- Neural networks: dominate for images, sound and text.
The confusion matrix
For two classes we count true positives (TP), false positives (FP), true negatives (TN) and false negatives (FN). From these:
- Accuracy .
- Precision : of those we called positive, how many were?
- Recall/sensitivity : of all positives, how many did we find?
- F1 is the harmonic mean of precision and recall.
When accuracy misleads
With imbalanced classes accuracy is misleading. If 1 % of transactions are fraud, a model that always says "not fraud" gets 99 % accuracy – and finds nothing. Then you must look at precision, recall and F1, and perhaps weight the classes or change the threshold.
Threshold and ROC
Lowering the threshold gives more positives: higher recall but lower precision. What is right depends on the cost of errors: in cancer screening a missed case (FN) is much worse than an extra check (FP); in a spam filter it is worse to discard an important email (FP). The ROC curve shows recall against false positive rate for all thresholds, and the AUC (area under it) summarises how well the model separates the classes – 0.5 is random guessing, 1 is perfect.
Responsible use
Models can amplify biases in the data and make decisions that affect people. Evaluate performance for different groups, be open about limitations, and let humans have the final say in important decisions. The EU AI Act sets specific requirements for high-risk systems.
How to solve the problems
- Set up the four numbers TP, FP, TN and FN.
- Pick the right formula: precision looks at the positive answers, recall at the positive cases.
- Think about what is worse: a false alarm or a missed case?
Example
A model finds 40 of 50 defective parts and raises a false alarm on 10 good parts. Precision and recall?
- , , .
- Precision . Recall .
Common mistakes
- Trusting accuracy when the classes are imbalanced. If only 1 % is fraud, a model that always says "no" gets 99 %.
- Swapping precision and recall.
- Believing the threshold must be 0.5. A lower threshold gives higher recall but lower precision.
Concepts in this part
Example problems with solutions
Here are some of the problems in machine Learning and Data Analysis. In the app, calculation problems get new numbers every time, so you can practise until it sticks – and take a practice exam with an indicative grade as you prepare for the exam.
Data and core concepts: The temperatures 10, 15 and 30 °C are min–max normalized. What does 15 become?
Answer: 0.25
.
Linear regression and gradient descent: The points , and . What is the slope by least squares?
Answer: 1.5
, . , , so .
Classification and evaluation: TP = 40, FP = 10, FN = 20. What is the precision?
Answer: 0.8
.
Data and core concepts: A model is to estimate the price of a home. What kind of task is it?
Answer: Regression
The answer is a number (a price), and we have examples with known answers. It is supervised regression.
Matches these university courses
The content follows the syllabus found in, for example:
- TDT4172 (NTNU)