From Theory to Code in Machine Learning (Part 1): Maximum Likelihood Estimation in Regression
Implementing Linear Regression from Scratch in Python
The Maximum Likelihood Estimation (MLE) principle provides a general starting point to determine certain criterion (optimization objectives) for optimization, which lead to the estimated values of parameters (characteristics of population). This article will introduce it from scratch and estimate the parameters of linear regression.
Section 2: When Do We Need Statistical Estimation?
Section 2.1: No Statistical Estimation. First-principle, Physical Formulas
Firstly, let’s consider the case without statistical estimation. Normally, when we want to model something, we “reason” over the case and develop professional domain knowledge through the study of underlying first principles for both physical formulas and parameters. This method relies heavily on a deep understanding of the theoretical foundations of a problem. The major advantage of this approach is its reliance on established scientific laws and principles, which can provide accurate and explainable models. However, this method might be limited in scenarios where the underlying principles are not well understood or too complex to model directly.
An Example: The concept of mass-energy equivalence is encapsulated in the famous equation formulated by Albert Einstein, E=m c². The equation directly relates the mass of an object (m) to its energy equivalence (E) with c representing the speed of light in a vacuum, approximately 3.00×10⁸ meters per second. The insight of relating m to E was not directly derived from experimental data but from Einstein’s deep reflections on the nature of space, time, and energy.
Limitation: Although first-principle derivation excels in areas with well-understood physical laws and offers models with high interpretability and theoretical justification, complex or poorly understood phenomena require leveraging data to uncover patterns and relationships that may not be apparent from theoretical analysis alone. That’s where we need statistical estimation.
Sometimes, only function forms can be determined by first-principle reasoning. Hence, statistical estimation is still required as a complementary approach to estimate parameters. Often, this first-principle approach may involve statistical analysis: Understanding Underlying Data Distribution, as discussed in the beginning.
Section 2.2: Statistical Estimation for Parameters
When the exact physical formulas or principles are unknown or too complex, a general universal approximator (neural network) or a hypothesized formula are commonly developed. Then, statistical estimation methods can be used to approximate their parameters using existing data.
Pros & Cons: Statistical estimation offers flexibility and is particularly powerful in handling large datasets and complex relationships that are not easily modeled using first principles alone. However, it may lack the interpretability and theoretical grounding of models derived from first principles, and its accuracy is heavily dependent on the quality and quantity of available data.
An Example: Let’s take an intuitive example from the Natural Language Processing (NLP) domain to illustrate the concept of statistical estimation: sentiment analysis.
Imagine you’re tasked with developing a model that can automatically determine whether a piece of text (like a product review) expresses a positive, negative, or neutral sentiment. The first-principle derivation approach would require understanding and modeling the complex rules of language, including grammar, idioms, sarcasm, and other nuanced features that contribute to sentiment. This is highly challenging due to the vast complexity and variability of natural language.
So we need to apply statistical estimation. Instead of trying to manually codify these rules, you opt for a statistical estimation approach. You collect a large dataset of text reviews, each labeled with its corresponding sentiment (positive, negative, or neutral) by human annotators. You then use this dataset to train a machine learning model, such as a neural network, to estimate the function fθ that maps input text to sentiment labels.
Section 3: Objective — Maximizing Likelihood
The intuitive objective is to choose a set of model parameters θ that is most probable according to the observed data: features x and the labels y, i.e., maximizing the posterior probability of P(θ∣x,y). It is barely impossible to know this. However, according to the Bayes rule, we know
P(θ∣x,y)-> P(y,x∣θ): Utilizing Bayes’ theorem allows us to express the posterior probability P(θ∣x,y) in terms of the likelihood P(y,x∣θ), the prior probability P(θ), and the marginal likelihood P(x,y). When the goal is to find the parameter set θ that maximizes the posterior probability given the data (features x and labels y), we can simplify the optimization problem by focusing on maximizing the numerator of the Bayes’ formula because the denominator P(x,y) is independent of θ and acts as a constant normalization factor. Specifically, in the context of parameter estimation, the focus often shifts to maximizing P(y,x∣θ)⋅P(θ) because it directly influences the value of P(θ∣x,y). However, when assuming a uniform prior (where P(θ) is constant) or in situations where the prior knowledge about θ is not specifically leveraged, the problem simplifies further to maximizing the likelihood P(y,x∣θ) alone. This underlies the principle of Maximum Likelihood Estimation (MLE), where P(θ) is effectively considered constant and does not influence the optimization of θ.
P(y,x∣θ) -> P(y∣x, θ): Since x is known and fixed in supervised learning tasks, we often consider x as a given context rather than a variable we seek to model the distribution of. Thus, the model focuses on y’s distribution conditioned on x and θ .
The total likelihood L on the sample (X, Y) is the product of P(y∣x, θ) for all n examples (x, y) in (X, Y) .
Note that the likelihood is not a probability distribution over
θ(since it does not integrate to 1 overθ, but it is used to compare different values ofθin terms of how plausible they make the observed data appear.
Section 4: MLE for Regression Tasks
Here is a function for linear regression: The predicted y \hat{yi}=β0+β1xi. To get the true y, we add the error term ϵi :
, where (xi, yi) is an example in training data.
Get Xinzhe Li, PhD in Language Intelligence’s stories in your inbox
Join Medium for free to get updates from this writer.
In the context of linear regression, ϵi is typically assumed to be normally distributed around 0. It is intuitive considering that the random error is unlikely to be big if the linear regression model is a good choice.
Now, we can derive the distribution of P(y∣x, θ) :
Now, we can specify P(yi∣xi, β0, β1) for the calculation of likelihood, where the right side of the equation below PDF for normal distribution:
The likelihood function for the entire dataset of n observations is the product of the individual probabilities for each data point, given the parameters:
To simplify the optimization, it’s common to take the logarithm of the likelihood function, converting the product into a sum:
The maximization of the above function equals to minimize:
Essentially, this process turns out to be equivalent to minimizing the sum of squared residuals, which is Ordinary Least Squares (OLS) objective when the variance is assumed to be constant.
With this MLE objective for linear regression (or OLS objective), we can easily know what are the optimal values for β0, β1 because this is a convex function for both β0, and β1 . According to some calculus knowledge, we can take the derivatives w.r.t. both β0, β1 as 0, and then will have two equations for solving the problem. Below are the results:
You can watch my YouTube video for the step-by-step derivation of the results.
Section 5: Python Implementation
Below is the code:
def mle_estimate_for_linear_regression(X, Y):
"""
Parameters:
- X: numpy array of independent variable values.
- Y: numpy array of dependent variable values.
Returns:
- beta_0: Estimated intercept of the regression line.
- beta_1: Estimated slope of the regression line.
"""
# Mean of X and Y
X_mean = np.mean(X)
Y_mean = np.mean(Y)
# Calculate beta_1 (slope)
beta_1 = np.sum((X - X_mean) * (Y - Y_mean)) / np.sum((X - X_mean) ** 2)
# Calculate beta_0 (intercept)
beta_0 = Y_mean - beta_1 * X_mean
return beta_0, beta_1Final Verification
Below is the test code to verify the result.
ture_beta_1 = 10
ture_beta_0 = 5
x = np.array([1, 2, 3, 4, 5])
y = ture_beta_0 + ture_beta_1 * x
plot_regression_line(ture_beta_1, ture_beta_0, x, y)
beta_0, beta_1 = ols_estimate_for_linear_regression(x, y)
print(f"beta_0: {beta_0}, beta_1: {beta_1}")Here is the output. beta_0: 5.0, beta_1: 10.0, same as the ture_beta_0 and ture_beta_1 . So, our closed-form solution is mathematically sound and works perfect.









