Skip to content

Algorithms for machine learning

How supervised learning fits a model: hypothesis function, cost function, gradient descent, feature scaling, overfitting and cross-validation.

5 min readUpdated

Supervised machine learning trains a model on labelled examples so that it can predict the label of new inputs. This note walks through the core ideas behind it, using linear regression as the example: the hypothesis function, the cost function that scores it, gradient descent that trains it, and the tools for dealing with underfitting and overfitting. It follows the structure of the InfoWorld article listed under References.

Types of machine learning

Machine learning is usually split into three families. Supervised learning uses labelled data for classification (spam detection) and regression (price prediction). Unsupervised learning finds structure in unlabelled data through clustering, association analysis and dimensionality reduction. Reinforcement learning learns from states, actions and rewards. The overview below lists popular algorithms for each family; the rest of this note covers supervised learning.

Machine learning types (supervised, unsupervised, reinforcement) with popular algorithms and example uses for each

How a model predicts

The task in supervised learning is to find the function that maps the input variables xx to the predicted value yy. This hypothesis function hθh_{\theta} is the output of the training process. It is also called the target function, prediction function or model.

y=hθ(x)y = h_{\theta}(x)

where:

  • hθ(x)h_{\theta}(x) is the hypothesis function (model).
  • xx is the feature vector.
  • θ\theta is the parameter vector that training adjusts.

xx holds several values {x1,x2,… }\{x_1, x_2, \dots\}, for example { 101.0, 3.0 } for a house of 101 m² with 3 rooms. This array is the feature vector.

Linear regression

Linear regression predicts a value as a weighted sum of the features. The cheat sheet below compares it with related methods: polynomial, Bayesian, ridge and LASSO regression, and logistic regression, which despite its name is a classification method.

Regression analysis cheat sheet comparing linear, polynomial, Bayesian, ridge, LASSO and logistic regression with their error functions

The linear regression function sums each element of the feature vector multiplied by its θ\theta parameter. Training tunes the θ\theta values to fit the training data.

hθ(x)=θ0x0+θ1x1+⋯+θnxnh_{\theta}(x) = \theta_{0} x_{0} + \theta_{1} x_{1} + \dots + \theta_{n} x_{n}

The subscript gives the position of each parameter and feature in its vector. The feature x0x_0 is a constant offset term, always 11, so that θ0\theta_0 acts as the intercept.

To know whether one θ\theta vector fits better than another, you need a function that scores how well the model performs.

Score the model with a cost function

The cost function J(θ)J(\theta) measures the error of a model over the mm training samples. For linear regression it is half the mean squared error:

J(θ)=12m∑i=1m(hθ(x(i))−y(i))2J(\theta) = \frac{1}{2m} \sum_{i=1}^{m} \left(h_{\theta}(x^{(i)}) - y^{(i)}\right)^2

For each sample ii, the error is the difference between the predicted and the actual yy. Squaring makes all errors positive and penalizes large ones more. The lower J(θ)J(\theta), the better the model fits the training data. The factor 12\frac{1}{2} only simplifies the derivative used below.

Train the model with gradient descent

The cost function scores a given θ\theta; gradient descent finds the θ\theta that minimizes it. Starting from initial values, it repeatedly moves every parameter a small step against the slope of the cost function:

repeat until convergence {θj:=θj−α1m∑i=1m(hθ(x(i))−y(i))xj(i)for j=0,…,n}\begin{aligned} &\text{repeat until convergence } \{ \\ &\qquad \theta_{j} := \theta_{j} - \alpha \frac{1}{m} \sum_{i=1}^{m} \left(h_{\theta}(x^{(i)}) - y^{(i)}\right) x_{j}^{(i)} \qquad \text{for } j = 0, \dots, n \\ &\} \end{aligned}

All θj\theta_j are updated simultaneously from the same old values. The learning rate α\alpha sets the step size.

To check that training works, compute J(θ)J(\theta) after each step: it must decrease with every iteration. If it grows or oscillates, the learning rate is too large and the algorithm overshoots the minimum. If it decreases very slowly, the learning rate is too small.

When the cost stops decreasing but is still high, the model underfits: it does not capture the underlying trend of the data. Underfitting is usually caused by a model that is too simple.

Add features and scale them

A common fix for underfitting is to add features. Instead of a single feature such as {size}, use several, such as {size, number-of-rooms, age}.

If the data has no more features to offer, add polynomial features computed from existing ones. With x1x_1 as the size of a house:

hθ(x)=θ0+θ1x1+θ2x12=θ0+θ1⋅size+θ2⋅size2h_{\theta}(x) = \theta_{0} + \theta_{1} x_{1} + \theta_{2} x_{1}^{2} = \theta_{0} + \theta_{1} \cdot \text{size} + \theta_{2} \cdot \text{size}^{2}

Features with very different ranges need feature scaling. The values of size2\text{size}^{2} are orders of magnitude larger than those of size\text{size}, so without scaling they dominate the cost function and slow down gradient descent. A simple method is mean normalization:

x′=x−avg⁡(x)max⁡(x)−min⁡(x)x' = \frac{x - \operatorname{avg}(x)}{\max(x) - \min(x)}

where x′x' is the normalized value. Apply it to every feature, using the same average, minimum and maximum for training and for prediction.

Adding features usually improves the fit on the training data. Add too many, and the model starts to overfit.

Detect overfitting with cross-validation

A model overfits when it fits the training data too closely, including its noise and random fluctuations. It scores well on the training data but predicts poorly on data it has not seen. To reduce overfitting:

  • Use more training data.
  • Use regularization, which adds a penalty for large θ\theta values to the cost function (ridge and LASSO in the cheat sheet above).
  • Use fewer features: remove those that do not improve accuracy.

With one or two features you can spot overfitting on a plot. With more features that stops working, so overfitting is detected with cross-validation: the trained model is evaluated on labelled data it was not trained on. Split the labelled data into three sets:

  • Training set: used to fit the θ\theta parameters.
  • Validation set: used to compare models and settings, such as the choice of features, the regularization strength or the learning rate.
  • Test set: used once at the end to estimate how the chosen model performs on new data.

If the error on the validation set is much higher than on the training set, the model overfits. If both are high, it underfits.

References

Related notes

4 min readTürkçe

Ollama

GPU'suz, yalnız CPU ile çalışan makinelerde Ollama ile yerel LLM çalıştırma ve hızı belirleyen ayarlar.

  • AI & Data
  • DevOps & Containers
2 min read

Distance measures

Formulas for the distance measures used in data science: Manhattan, Euclidean, Minkowski, Chebyshev, cosine, Hamming and Jaccard.

  • AI & Data
4 min read

Hadoop

Install Hadoop on macOS with Homebrew, configure a single-node HDFS and YARN setup, enable SSH to localhost and run basic HDFS commands.

  • AI & Data

Type to search the whole site.