Optimization Techniques

In the previous lesson, we talked about calculus and looked at the gradient.

We saw how this mathematical tool allows us to calculate the rate of change of a function and the direction of steepest descent.

We’ll continue talking about gradients here, but first I’ll explain what we’re actually trying to optimize: the loss function.

This Lesson Will Cover
  • πŸ“‰ Definition and purpose of loss functions
  • πŸ“Š Common loss functions used in machine learning
  • πŸ”„ Gradient descent optimization techniques
  • ✏️ Examples of optimization in linear and logistic regression

What is a Loss Function?

A loss function measures how well a machine learning model predicts outcomes.

It quantifies the error between the predicted values (y^\hat{y}) and the actual values (yy).

i.e.

Loss=Error(y^,y) \text{Loss} = \text{Error}(\hat{y}, y)

By minimizing the loss function: searching over the parameter space for the values that yield the lowest loss, we tune parameters to make better predictions.

This is called optimization.

Common Loss Functions

Mean Squared Error (MSE)

This is commonly used for regression problems.

MSE=1nβˆ‘i=1n(y^iβˆ’yi)2 \text{MSE} = \frac{1}{n} \sum_{i=1}^n (\hat{y}_i - y_i)^2
Mean Squared Error (MSE) Loss
MSE punishes large errors more than small ones by squaring the difference between predicted and true values. It’s great for regression problems where you want to strongly discourage big mistakes.

It requires calculating the residuals: the differences between predicted and actual values.

The squared term ensures that:

  1. Negative residuals (when predictions are too low) and positive residuals (when predictions are too high) are treated equally
  2. Larger errors are penalized more heavily due to the quadratic nature

For example, if a model predicts 3 when the actual value is 5, the residual of -2 becomes 4 after squaring, just like a residual of +2 would.

For example, if we have:

  • Predicted values: y^=[4.2,1.8,3.3]\hat{y} = [4.2, 1.8, 3.3]
  • Actual values: y=[4.0,2.0,3.0]y = [4.0, 2.0, 3.0]
MSE=13[(4.2βˆ’4.0)2+(1.8βˆ’2.0)2+(3.3βˆ’3.0)2]=13[0.04+0.04+0.09]=0.173=0.057 \begin{aligned} \text{MSE} &= \frac{1}{3}[(4.2 - 4.0)^2 + (1.8 - 2.0)^2 + (3.3 - 3.0)^2] \\ &= \frac{1}{3}[0.04 + 0.04 + 0.09] \\ &= \frac{0.17}{3} \\ &= 0.057 \end{aligned}

The resulting error will have different units than the target variable yy that is being modeled. We can fix this by taking the square root and returning the RMSE (Root Mean Squared Error) instead:

RMSE=1nβˆ‘i=1n(y^iβˆ’yi)2 \text{RMSE} = \sqrt{\frac{1}{n} \sum_{i=1}^n (\hat{y}_i - y_i)^2}
Root Mean Squared Error (RMSE) Loss
RMSE is the square root of MSE. It gives error values in the same units as the target variable, making it easier to interpret. It’s commonly used when you care about the scale of the prediction errors.

Cross-Entropy Loss (Log loss)

This is commonly used for classification problems. It requires calculating the product of the actual labels with the logarithm of the predicted labels, e.g.

yΓ—βˆ’log⁑(y^) y \times -\log(\hat{y})

where yy is an actual label (0 or 1) and y^\hat{y} is the predicted probability of that label.

Cross-Entropy Loss
Cross-entropy measures how confident and correct a model's predicted probability is. It gives small loss for confident right answers and high loss for confident wrong ones. It's the go-to for classification problems.

It’s easy to see how this behaves by looking at a f(x)=βˆ’log⁑xf(x)=-\log{x} graph for x<=1x<=1 (as seen above).

When xx is near zero we get a large positive value and when xx is near 1 we get a small positive value.

For example, if a model predicts 0.9 probability for the correct class, then we calculate the log of 0.9 and multiply it by negative one to get a small loss of 0.105, while a prediction of 0.1 for the correct class will give a much larger loss of 2.303.

This asymmetrical treatment helps the model optimize towards confident, correct predictions.

Here’s the full cross-entropy loss for binary classification:

Cross-Entropy=βˆ’βˆ‘i[yilog⁑(y^i)+(1βˆ’yi)log⁑(1βˆ’y^i)] \text{Cross-Entropy} = -\sum_{i} [y_i \log(\hat{y}_i) + (1-y_i) \log(1-\hat{y}_i)]

where:

  • yiy_i is the true label (0 or 1) for the ii-th sample
  • y^i\hat{y}_i is the predicted probability for the ii-th sample
  • ii indexes over all samples in the dataset

For example, if we have:

  • Predicted probabilities: y^=[0.8,0.2,0.9]\hat{y} = [0.8, 0.2, 0.9]
  • Actual labels: y=[1,0,1]y = [1, 0, 1]
Cross-Entropy=βˆ’[(1β‹…log⁑(0.8)+(1βˆ’1)log⁑(0.2))+(0β‹…log⁑(0.2)+(1βˆ’0)log⁑(0.8))+(1β‹…log⁑(0.9)+(1βˆ’1)log⁑(0.1))]=βˆ’[log⁑(0.8)+log⁑(0.8)+log⁑(0.9)]=βˆ’((βˆ’0.223)+(βˆ’0.223)+(βˆ’0.105))=0.551 \begin{aligned} \text{Cross-Entropy} &= -[(1 \cdot \log(0.8) + (1-1) \log(0.2)) + \\ &\quad (0 \cdot \log(0.2) + (1-0) \log(0.8)) + \\ &\quad (1 \cdot \log(0.9) + (1-1) \log(0.1))] \\ &= -[\log(0.8) + \log(0.8) + \log(0.9)] \\ &= -((-0.223) + (-0.223) + (-0.105)) \\ &= 0.551 \end{aligned}
Loss Function Selection Flow
Selecting a loss function from the examples above, depending on the type of ML problem. Also including the multi-class generalization of the binary cross-entropy loss described above.

Gradient Descent Optimization

Now that we understand loss functions, let’s see how we can use them with gradient descent to optimize model parameters.

For simple functions, we can find the minimum analytically by taking the derivative, setting it equal to zero, and solving for the parameters.

For example, with a quadratic function f(x)=x2+2x+1f(x) = x^2 + 2x + 1, we can find the minimum by solving dfdx=2x+2=0\frac{df}{dx} = 2x + 2 = 0, giving us x=βˆ’1x = -1.

However, in machine learning, this approach is typically not feasible because of:

  1. High Dimensionality: Machine learning models often have thousands or even millions of parameters. Computing analytical solutions for the derivatives of loss functions with respect to all these parameters is computationally expensive and, in many cases, impossible.

  2. Complex Loss Surfaces: The loss functions in machine learning are often non-convex, meaning they have many local minima, saddle points, and flat regions. This complexity makes it difficult to find a closed-form solution.

  3. Dynamic and Nonlinear Relationships: The relationship between the model parameters and the loss function is often nonlinear and dynamic, making it hard to compute exact minima.

Instead, gradient descent provides an iterative approach to find the minimum of the loss function.

The Gradient Descent Algorithm

Gradient descent works by iteratively updating the model parameters in the direction of the steepest descent of the loss function.

This direction is given by the negative gradient of the loss function with respect to the parameters.

The update rule for each parameter ΞΈi\theta_i is:

ΞΈi←θiβˆ’Ξ·β‹…βˆ‚Lβˆ‚ΞΈi \theta_i \gets \theta_i - \eta \cdot \frac{\partial L}{\partial \theta_i}

Where:

  • ΞΈi\theta_i is the parameter being updated.
  • Ξ·\eta is the learning rate, which controls the step size of each update.
  • βˆ‚Lβˆ‚ΞΈi\frac{\partial L}{\partial \theta_i} is the gradient of the loss function LL with respect to ΞΈi\theta_i.

This can also be expressed in gradient notation:

ΞΈβ†ΞΈβˆ’Ξ·βˆ‡ΞΈL(ΞΈ) \theta \gets \theta - \eta \nabla_\theta L(\theta)

Where:

  • ΞΈ\theta is the vector of all parameters
  • Ξ·\eta is the learning rate
  • βˆ‡ΞΈL(ΞΈ)\nabla_\theta L(\theta) is the gradient vector containing partial derivatives of the loss with respect to each parameter

The gradient descent algorithm itself is simple:

  1. Initialize Parameters: Start with initial guesses for the model parameters. These can be random values or zeros, depending on the problem.

  2. Compute Gradients: Calculate the gradient of the loss function with respect to each parameter. This step often involves backpropagation in neural networks.

  3. Update Parameters: Adjust each parameter using the update rule.

  4. Repeat: Iterate through steps 2 and 3 until the parameters converge, i.e., the changes in the parameters become negligible or the loss function stops decreasing significantly.

Simplified Gradient Descent Flowchart
Flow chart for gradient descent examples below, where the loss functions are MSE for linear regression and cross-entropy for logistic regression.

Linear Regression with MSE

Let’s optimize a simple linear regression model y^=wx+b\hat{y} = wx + b with MSE loss

Given some training data:

x=[1,2,3]feature valuesy=[2,4,5]target values \begin{aligned} x &= [1, 2, 3] \quad \text{feature values} \\ y &= [2, 4, 5] \quad \text{target values} \\ \end{aligned}

and initial parameter values:

w=1.5initial weightb=0.5initial bias \begin{aligned} w &= 1.5 \quad \text{initial weight} \\ b &= 0.5 \quad \text{initial bias} \end{aligned}

The MSE loss function is:

L(w,b)=13βˆ‘i=13((wxi+b)βˆ’yi)2 L(w,b) = \frac{1}{3}\sum_{i=1}^3 ((wx_i + b) - y_i)^2

The gradients are:

βˆ‚Lβˆ‚w=23βˆ‘i=13((wxi+b)βˆ’yi)xiβˆ‚Lβˆ‚b=23βˆ‘i=13((wxi+b)βˆ’yi) \begin{aligned} \frac{\partial L}{\partial w} &= \frac{2}{3}\sum_{i=1}^3 ((wx_i + b) - y_i)x_i \\ \frac{\partial L}{\partial b} &= \frac{2}{3}\sum_{i=1}^3 ((wx_i + b) - y_i) \end{aligned}

Our initial predictions using y^=wx+b\hat{y} = wx + b are:

y^=[2.0,3.5,5.0](calculated as wx+b for each x value) \begin{aligned} \hat{y} &= [2.0, 3.5, 5.0] \\ &\text{(calculated as } wx + b \text{ for each } x \text{ value)} \end{aligned}

Now we compute the gradients with respect to each parameter.

For the weight ww:

βˆ‚Lβˆ‚w=23[(0.0β‹…1)+(βˆ’0.5β‹…2)+(0.0β‹…3)]=βˆ’0.667 (approximately) \begin{aligned} \frac{\partial L}{\partial w} &= \frac{2}{3}[(0.0 \cdot 1) + (-0.5 \cdot 2) + (0.0 \cdot 3)] \\ &= -0.667 \text{ (approximately)} \end{aligned}

And for the bias bb:

βˆ‚Lβˆ‚b=23[0.0+(βˆ’0.5)+0.0]=βˆ’0.333 (approximately) \begin{aligned} \frac{\partial L}{\partial b} &= \frac{2}{3}[0.0 + (-0.5) + 0.0] \\ &= -0.333 \text{ (approximately)} \end{aligned}

Finally, we update our parameters using learning rate Ξ±=0.1\alpha=0.1:

wnew=1.5βˆ’0.1β‹…(βˆ’2/3)β‰ˆ1.567bnew=0.5βˆ’0.1β‹…(βˆ’1/3)β‰ˆ0.533 \begin{aligned} w_{\text{new}} &= 1.5 - 0.1 \cdot (-2/3) \approx 1.567 \\ b_{\text{new}} &= 0.5 - 0.1 \cdot (-1/3) \approx 0.533 \end{aligned}

These new parameter values will be used in the next iteration of gradient descent.

The process continues until the loss converges or we reach a maximum number of iterations.

Logistic Regression with Cross-Entropy

For logistic regression, we use a sigmoid function Οƒ(z)=11+eβˆ’z\sigma(z) = \frac{1}{1+e^{-z}} to predict probabilities y^\hat{y}:

y^=Οƒ(wx+b) \hat{y} = \sigma(wx + b)

Given some training data:

x=[1,2,3]feature valuesy=[1,0,1]target labels, binary \begin{aligned} x &= [1, 2, 3] \quad \text{feature values} \\ y &= [1, 0, 1] \quad \text{target labels, binary} \end{aligned}

and initial parameter values:

w=0.5initial weightb=βˆ’1.0initial bias \begin{aligned} w &= 0.5 \quad \text{initial weight} \\ b &= -1.0 \quad \text{initial bias} \end{aligned}

The cross-entropy loss function is:

L(w,b)=βˆ’βˆ‘i=13[yilog⁑(Οƒ(wxi+b))+(1βˆ’yi)log⁑(1βˆ’Οƒ(wxi+b))] L(w,b) = -\sum_{i=1}^3 [y_i \log(\sigma(wx_i + b)) + (1-y_i) \log(1-\sigma(wx_i + b))]

The gradients are:

βˆ‚Lβˆ‚w=βˆ‘i=13(Οƒ(wxi+b)βˆ’yi)xiβˆ‚Lβˆ‚b=βˆ‘i=13(Οƒ(wxi+b)βˆ’yi) \begin{aligned} \frac{\partial L}{\partial w} &= \sum_{i=1}^3 (\sigma(wx_i + b) - y_i)x_i \\ \frac{\partial L}{\partial b} &= \sum_{i=1}^3 (\sigma(wx_i + b) - y_i) \end{aligned}

Our initial predictions using z=wx+bz = wx + b and y^=Οƒ(z)\hat{y} = \sigma(z) are shown rounded to two decimal places. The arithmetic below uses those rounded probabilities:

z=[βˆ’0.5,0.0,0.5]y^=[0.38,0.50,0.62](calculated as Οƒ(wx+b) for each x value) \begin{aligned} z &= [-0.5, 0.0, 0.5] \\ \hat{y} &= [0.38, 0.50, 0.62] \\ &\text{(calculated as } \sigma(wx + b) \text{ for each } x \text{ value)} \end{aligned}

Now we compute the gradients with respect to each parameter.

For the weight ww:

βˆ‚Lβˆ‚w=[(0.38βˆ’1)β‹…1+(0.50βˆ’0)β‹…2+(0.62βˆ’1)β‹…3]=βˆ’0.760 \begin{aligned} \frac{\partial L}{\partial w} &= [(0.38-1) \cdot 1 + (0.50-0) \cdot 2 + (0.62-1) \cdot 3] \\ &= -0.760 \end{aligned}

And for the bias bb:

βˆ‚Lβˆ‚b=[(0.38βˆ’1)+(0.50βˆ’0)+(0.62βˆ’1)]=βˆ’0.500 \begin{aligned} \frac{\partial L}{\partial b} &= [(0.38-1) + (0.50-0) + (0.62-1)] \\ &= -0.500 \end{aligned}

Finally, we update our parameters using learning rate Ξ±=0.1\alpha=0.1:

wnew=0.5βˆ’0.1β‹…(βˆ’0.760)=0.576bnew=βˆ’1.0βˆ’0.1β‹…(βˆ’0.500)=βˆ’0.950 \begin{aligned} w_{\text{new}} &= 0.5 - 0.1 \cdot (-0.760) = 0.576 \\ b_{\text{new}} &= -1.0 - 0.1 \cdot (-0.500) = -0.950 \end{aligned}

Just like our example of gradient descent for linear regression, these new parameter values will be used in the next iteration and the process will continue until the loss converges or we reach a maximum number of iterations.

Conclusion

I love plugging toy data into a math equation and watching it come to life.

We learned a lot about loss functions and optimization here, but we should be mindful that these examples are so simple that they hide much of the complexity involved in real-world applications.

Key Takeaways

🎯 Loss functions measure how well a model predicts outcomes.

πŸ“‰ Mean Squared Error (MSE) is commonly used for regression, penalizing large errors more.

πŸ”’ Cross-Entropy Loss is commonly used for classification, encouraging confident predictions.

πŸš€ Gradient Descent is an iterative optimization technique for finding minima in high-dimensional spaces.

βš™οΈ Learning rate is a critical parameter that controls how quickly the model updates.

Next: Optimization in Practice

In the next section, we’ll talk about some of the practical considerations of optimization for machine learning and deep learning.

Comments (0)

No comments yet.