Thursday, December 3, 2026 | London 10°C · Drizzle
DailyGlimpse

AI

Demystifying the Cost Function: A Beginner's Guide to Linear Regression

Fundamentally Clear 2 min read

In machine learning, the cost function is a fundamental concept that measures how well a model's predictions match the actual data. For linear regression, it quantifies the error between predicted and actual values.

What is a Cost Function?

A cost function, also known as a loss function, calculates the difference between the model's predictions and the true outcomes. The goal is to minimize this cost during training, so the model becomes more accurate.

Why Does Machine Learning Need It?

Without a cost function, a model wouldn't know whether its predictions are improving. It provides a numeric value that the optimization algorithm (like gradient descent) uses to adjust the model's parameters.

How Prediction Error is Calculated

In linear regression, the most common cost function is the mean squared error (MSE). It computes the average squared difference between each predicted value and the actual value. The formula is:

J(θ) = (1/2m) Σ (h(xᵢ) - yᵢ)²

where h(x) is the hypothesis function, y is the actual value, and m is the number of data points.

Low vs. High Cost

  • Low cost: The model fits the data well, making accurate predictions.
  • High cost: The model's predictions are far off, indicating poor fit or underfitting.

Relationship with Gradient Descent

Gradient descent is an optimization algorithm that iteratively updates model parameters to reduce the cost function. It moves in the direction of steepest descent (downhill) to find the minimum cost.

How Models Find the Best-Fit Line

By minimizing the cost function, linear regression finds the line that best fits the data. The parameters (slope and intercept) are adjusted until the cost is as low as possible.

Understanding the cost function is crucial for anyone learning machine learning, AI, data science, or deep learning. It's the foundation that enables models to learn from data.

React