Ai Cheat Sheet
  • Home
  • Statistics ↓↑
    • Types of Measure
    • Population and Sample
    • Outliers
    • Variance
    • Standard Deviation
    • Skewness
    • Percentiles
    • Deciles
    • Quartiles
    • Box and Whisker Plots
    • Correlation and Covariance
    • Hypothesis Test
    • P Value
    • Statistical Significance
    • Bootstrapping
    • Confidence Interval
    • Central Limit Theorem
    • F1 Score (F Measure)
    • ROC and AUC
    • Random Variable
    • Expected Value
    • Central Limit Theorem
  • Probability ↓↑
    • What is Probability
    • Joint Probability
    • Marginal Probability
    • Conditional Probability
    • Bayesian Statistics
    • Naive Bayes
  • Data Science ↓↑
    • Probability Distribution
    • Bernoulli Distribution
    • Uniform Distribution
    • Binomial Distribution
    • Poisson Distribution
    • Normal Distribution
    • T-SNE
  • Data Engineering ↓↑
    • Data Science vs Data Engineering
    • Data Architecture
    • Data Governance
    • Data Quality
    • Data Compliance
    • Business Intelligence
    • Data Modeling
    • Data Catalog
    • Data Cleaning
    • Data Format
      • Apache Avro
    • Tools
      • Data Fusion
      • Dataflow
      • Dataproc
      • BigQuery
    • Cloud Platforms
      • GCP
    • SQL
      • ACID
      • SQL Transaction
      • Query Optimization
    • Data Engineering Interview Questions
  • Vector and Matrix
    • Vector
    • Matrix
  • Machine Learning ↓↑
    • L1 and L2 Loss Function
    • Linear Regression
    • Logistic Regression
    • Naive Bayes Classifier
    • Resources
  • Deep Learning ↓↑
    • Neural Networks and Deep Learning
    • Improving Deep Neural Networks
    • Structuring Machine Learning Projects
    • Convolutional Neural Networks
    • Sequence Models
    • Bias
    • Activation Function
    • Softmax
    • Cross Entropy
  • Natural Language Processing ↓↑
    • Linguistics and NLP
    • Text Augmentation
    • CNN for NLP
    • Transformers
      • Implementation
  • Computer Vision ↓↑
    • Object Localization
    • Object Detection
    • Bounding Box Prediction
    • Evaluating Object Localization
    • Anchor Boxes
    • YOLO Algorithm
    • R-CNN
    • Face Recognition
  • Time Series
    • Resources
  • Reinforcement Learning
    • Reinforcement Learning
  • System Design
    • SW Diagramming
    • Feed
  • Tools
    • PyTorch
    • Tensorflow
    • Hugging Face
  • MLOps
    • Vertex AI
      • Dataset
      • Feature Store
      • Pipelines
      • Training
      • Experiments
      • Model Registry
      • Serving
        • Batch Predictions
        • Online Predictions
      • Metadata
      • Matching Engine
      • Monitoring and Alerting
  • Interview Questions ↓↑
    • Questions by Shared Experience
  • Contact
    • My Personal Website
Powered by GitBook
On this page
  • 1. Regression Model
  • 2. Define Loss Function
  • 3. Utilize the Gradient Descent Algorithm
  • Python Implementation

Was this helpful?

  1. Machine Learning ↓↑

Linear Regression

PreviousL1 and L2 Loss FunctionNextLogistic Regression

Last updated 4 years ago

Was this helpful?

1. Regression Model

In statistics, linear regression is a linear approach to modelling the relationship between a dependent variable and one or more independent variables. Let x1x_1x1​ be the independent variable and yyy be the dependent variable. We will define a linear relationship between these two variables as follows:

y=θ0+θ1x1y = \theta_0+\theta_1 x_1y=θ0​+θ1​x1​

2. Define Loss Function

We will use the Mean Squared Error function.

L=1n∑i=1n(ytrue−ypredicted)2L = \frac{1}{n}\sum_{i=1}^n (y_{true}-y_{predicted})^2L=n1​i=1∑n​(ytrue​−ypredicted​)2

3. Utilize the Gradient Descent Algorithm

You might know that the partial derivative of a function at its minimum value is equal to 0. So gradient descent basically uses this concept to estimate the parameters or weights of our model by minimizing the loss function.

  1. Initialize the weights, θ0=0\theta_0 = 0θ0​=0and θ1=0\theta_1 =0θ1​=0

  2. Calculate the partial derivatives w.r.t. to θ0\theta_0θ0​and θ1\theta_1θ1​ dθ0=−2n∑i=1n(yi−yiˉ)dθ1=−2n∑i=1n(yi−yiˉ)×xid_{\theta_0} = -\frac{2}{n} \sum_{i=1}^n(y_i - \bar{y_i}) \\ d_{\theta_1} = -\frac{2}{n} \sum_{i=1}^n(y_i - \bar{y_i}) \times x_idθ0​​=−n2​∑i=1n​(yi​−yi​ˉ​)dθ1​​=−n2​∑i=1n​(yi​−yi​ˉ​)×xi​

  3. Update the weights θ0=θ0−l×dθ0θ1=θ1−l×dθ1\theta_0 = \theta_0 - l \times d_{\theta_0} \\ \theta_1 = \theta_1 - l \times d_{\theta_1}θ0​=θ0​−l×dθ0​​θ1​=θ1​−l×dθ1​​

Python Implementation

# Importing libraries
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split

# Preparing the dataset
data = pd.DataFrame({'feature' : [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15], 'label' : [2,4,6,8,10,12,14,16,18,20,22,24,26,28,30]})
# Divide the data to training set and test set
X_train, X_test, y_train, y_test = train_test_split(data['feature'], data['label'], test_size=0.30)

# Method to make predictions
def predict(X, theta0, theta1):
    # Here the predict function is: theta0+theta1*x
    return np.array([(theta0 + theta1*x) for x in X])

def linear_regression(X, Y):
    # Initializing variables
    theta0 = 0
    theta1 = 0
    learning_rate = 0.001
    epochs = 300
    n = len(X)

    # Training iteration
    for epoch in range(epochs):
        y_pred = predict(X, theta0, theta1)

        ## Here the loss function is: 1/n*sum(y-y_pred)^2 a.k.a mean squared error (mse)
        # Derivative of loss w.r.t. theta0
        theta0_d = -(2/n) * sum(Y-y_pred)
        # Derivative of loss w.r.t. theta1
        theta1_d = -(2/n) * sum(X*(Y-y_pred))

        theta0 = theta0 - learning_rate * theta0_d
        theta1 = theta1 - learning_rate * theta1_d   

    return theta0, theta1

# Training the model
theta0, theta1 = linear_regression(X_train, y_train)   

# Making predictions
y_pred = predict(X_test, theta0, theta1)

# Evaluating the model
print(list(y_test))
print(y_pred)

Linear Regression using Gradient DescentMedium
Logo