AWS Builder Center

Machine Learning from Scratch – Day 6: Understanding Linear Regression

Day 6: Understanding Linear Regression

Series: Machine Learning From Scratch (18 articles)

  1. …
  2. 6
    Machine Learning from Scratch – Day 6: Understanding Linear Regression This article

Introduction

Welcome to Day 6 of our Machine Learning from Scratch series!
So far, we have explored the fundamentals of Machine Learning, its different types, the ML workflow, dataset splitting, and the concepts of overfitting and underfitting.
Today, we're taking our first step into actual Machine Learning algorithms.
Our topic is Linear Regression, one of the simplest and most widely used algorithms in Machine Learning.
But first, let's consider a simple question:
Can we predict the price of a house based on its size?
For example, if we know the prices of houses with different areas, can a computer learn the relationship between house size and price and estimate the price of a new house?
Yes! This is exactly the kind of problem Linear Regression helps solve.

1. What is Linear Regression?

Linear Regression is a Supervised Machine Learning algorithm used to predict continuous numerical values by identifying a linear relationship between input variables and an output variable.
In simple terms, it finds the best-fitting straight line through data points to make predictions.
Real-world applications:
  • Predicting house prices.
  • Estimating salary based on experience.
  • Forecasting sales revenue.
  • Predicting product demand.
  • Estimating temperature trends.

2. Understanding the Linear Regression Equation

The mathematical foundation of Linear Regression is:
\[ y = mx + c \]
Where:
  • \(y\) = Predicted output.
  • \(x\) = Input feature.
  • \(m\) = Slope of the line.
  • \(c\) = Y-intercept.
Let's understand this with an example.
Imagine we want to predict someone's salary based on years of experience.
Suppose our model learns the equation:
\[ Salary = 5000 \times Experience + 20000 \]
If a person has 3 years of experience:
\[ Salary = 5000(3) + 20000 \]
\[ Salary = 35000 \]
The predicted salary is ₹35,000, assuming the equation uses rupees.
This is how Linear Regression uses learned relationships to make predictions.

3. How Does Linear Regression Work?

Linear Regression follows a simple learning process:
  1. Collect historical data.
  1. Identify input and output variables.
  1. Find a line that best represents their relationship.
  1. Calculate prediction errors.
  1. Adjust the model parameters to minimize errors.
  1. Use the trained model to predict new values.
But how does the algorithm decide which line is the best?
It commonly uses a technique called Ordinary Least Squares (OLS).
OLS minimizes the sum of squared differences between actual values and predicted values.
This difference is called the residual or prediction error.
\[ Error = Actual\ Value - Predicted\ Value \]
The objective is to find the line with the smallest total squared error.

4. Types of Linear Regression

There are two commonly discussed types.
A. Simple Linear Regression
Simple Linear Regression uses only one independent variable to predict an output.
Example:
Predicting salary using only years of experience.
\[ y = mx+c \]
B. Multiple Linear Regression
Multiple Linear Regression uses two or more independent variables to predict an output.
Example:
Predicting house prices using:
  • House area.
  • Number of bedrooms.
  • Location.
  • Property age.
Its equation is:
\[ y = b_0+b_1x_1+b_2x_2+\cdots+b_nx_n \]
Here, each input feature has its own coefficient.

5. Understanding the Cost Function

How does a model know whether its predictions are accurate?
One commonly used measurement is Mean Squared Error (MSE).
It calculates the average of squared differences between actual and predicted values.
\[ MSE = \frac{1}{n}\sum_{i=1}^{n}(y_i-\hat y_i)^2 \]
Where:
  • \(n\) = Number of observations.
  • \(y_i\) = Actual value.
  • \(\hat y_i\) = Predicted value.
A lower MSE generally indicates smaller prediction errors.
The model tries to minimize this error while learning the best-fitting line.

6. Practical Implementation Using Python

Now let's build our first Linear Regression model using Python and Scikit-learn.
We'll create a simple model that predicts salary based on years of experience.
Step 1: Import the libraries
import numpy as npimport matplotlib.pyplot as pltfrom sklearn.linear_model import LinearRegression
Step 2: Prepare the dataset
X = np.array([ [1], [2], [3], [4], [5], [6], [7], [8], [9], [10]])y = np.array([ 25000, 30000, 35000, 40000, 45000, 50000, 55000, 60000, 65000, 70000])
Step 3: Train the model
model = LinearRegression()model.fit(X, y)
Step 4: Make a prediction
prediction = model.predict([[11]])print("Predicted Salary:", prediction[0])
Step 5: Visualize the results
plt.scatter(X, y)plt.plot( X, model.predict(X))plt.xlabel("Years of Experience")plt.ylabel("Salary")plt.title("Linear Regression")plt.show()
Expected output:
Predicted salary: ₹75,000
Our model has learned the relationship between experience and salary and can now estimate salaries for new inputs.
Note: This is a small, artificially created dataset designed to demonstrate the algorithm. Real-world predictions require representative data and proper evaluation.

7. Advantages and Limitations

Advantages
Limitations
Easy to understand
Assumes a linear relationship
Simple implementation
Sensitive to outliers
Fast training
May struggle with complex patterns
Highly interpretable
Can be affected by multicollinearity
Linear Regression is a great starting point, but it isn't suitable for every prediction problem.
For example, if the relationship between house size and price is highly nonlinear, a simple straight-line model may not perform well.

8. Where Is Linear Regression Used?

Some real-world applications include:
  • Real Estate: Estimating property prices based on different features.
  • Finance: Forecasting revenue and financial trends.
  • Business: Predicting sales based on advertising expenditure.
  • Education: Studying relationships between study hours and examination scores.
  • Healthcare Research: Analyzing relationships between measurable variables.

Conclusion

Today, we explored our first Machine Learning algorithm: Linear Regression.
We learned that it identifies relationships between input and output variables and uses those relationships to predict continuous numerical values.
Let's remember the important concepts:
  • Linear Regression is a Supervised Learning algorithm.
  • Simple Linear Regression uses one input variable.
  • Multiple Linear Regression uses multiple input variables.
  • The equation \(y=mx+c\) represents a straight line.
  • Mean Squared Error helps measure prediction errors.
  • Python's Scikit-learn library makes implementation easier.
The important takeaway is that Machine Learning isn't just about understanding algorithms theoretically. We also need to implement them, experiment with data, and evaluate their performance.
Coming Next – Day 7: Understanding Logistic Regression – How Machines Make Classification Decisions.
We'll explore how Machine Learning models predict categories such as Spam/Not Spam, Yes/No, and Positive/Negative.

Series: Machine Learning From Scratch (18 articles)

  1. …
  2. 6
    Machine Learning from Scratch – Day 6: Understanding Linear Regression This article
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article