Python Implementation of Linear Regression

CK CK 3788 
Created at  
837 0 0

Below code is based on Python 3 to implement Linear Regression based on 

Python Implementation of Linear Regression

where:

  • Y is the dependent variable
  • X is the independent variable
  • β0 is the intercept
  • β1 is the slope

 

Our primary objective while using linear regression is to locate the best-fit line, which implies that the error between the predicted and actual values should be kept to a minimum. There will be the least error in the best-fit line.

The best Fit Line equation provides a straight line that represents the relationship between the dependent and independent variables. The slope of the line indicates how much the dependent variable changes for a unit change in the independent variable(s).

Python Implementation of Linear Regression

Here Y is called a dependent or target variable and X is called an independent variable also known as the predictor of Y. There are many types of functions or modules that can be used for regression. A linear function is the simplest type of function. Here, X may be a single feature or multiple features representing the problem.

Linear regression performs the task to predict a dependent variable value (y) based on a given independent variable (x)). Hence, the name is Linear Regression. In the figure above, X (input) is the work experience and Y (output) is the salary of a person. The regression line is the best-fit line for our model. 

We utilize the cost function to compute the best values in order to get the best fit line since different values for weights or the coefficient of lines result in different regression lines.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.axes as ax
from matplotlib.animation import FuncAnimation

url = 'https://media.geeksforgeeks.org/wp-content/uploads/20240320114716/data_for_lr.csv'
data = pd.read_csv(url)
data

# Drop the missing values
data = data.dropna()

# training dataset and labels
train_input = np.array(data.x[0:500]).reshape(500, 1)
train_output = np.array(data.y[0:500]).reshape(500, 1)

# valid dataset and labels
test_input = np.array(data.x[500:700]).reshape(199, 1)
test_output = np.array(data.y[500:700]).reshape(199, 1)

class LinearRegression: 
    def __init__(self): 
        self.parameters = {} 

    def forward_propagation(self, train_input): 
        m = self.parameters['m'] 
        c = self.parameters['c'] 
        predictions = np.multiply(m, train_input) + c 
        return predictions 

    def cost_function(self, predictions, train_output): 
        cost = np.mean((train_output - predictions) ** 2) 
        return cost 

    def backward_propagation(self, train_input, train_output, predictions): 
        derivatives = {} 
        df = (predictions-train_output) 
        # dm= 2/n * mean of (predictions-actual) * input 
        dm = 2 * np.mean(np.multiply(train_input, df)) 
        # dc = 2/n * mean of (predictions-actual) 
        dc = 2 * np.mean(df) 
        derivatives['dm'] = dm 
        derivatives['dc'] = dc 
        return derivatives 

    def update_parameters(self, derivatives, learning_rate): 
        self.parameters['m'] = self.parameters['m'] - learning_rate * derivatives['dm'] 
        self.parameters['c'] = self.parameters['c'] - learning_rate * derivatives['dc'] 

    def train(self, train_input, train_output, learning_rate, iters): 
        # Initialize random parameters 
        self.parameters['m'] = np.random.uniform(0, 1) * -1
        self.parameters['c'] = np.random.uniform(0, 1) * -1

        # Initialize loss 
        self.loss = [] 

        # Initialize figure and axis for animation 
        fig, ax = plt.subplots() 
        x_vals = np.linspace(min(train_input), max(train_input), 100) 
        line, = ax.plot(x_vals, self.parameters['m'] * x_vals +
                        self.parameters['c'], color='red', label='Regression Line') 
        ax.scatter(train_input, train_output, marker='o', 
                color='green', label='Training Data') 

        # Set y-axis limits to exclude negative values 
        ax.set_ylim(0, max(train_output) + 1) 

        def update(frame): 
            # Forward propagation 
            predictions = self.forward_propagation(train_input) 

            # Cost function 
            cost = self.cost_function(predictions, train_output) 

            # Back propagation 
            derivatives = self.backward_propagation( 
                train_input, train_output, predictions) 

            # Update parameters 
            self.update_parameters(derivatives, learning_rate) 

            # Update the regression line 
            line.set_ydata(self.parameters['m'] 
                        * x_vals + self.parameters['c']) 

            # Append loss and print 
            self.loss.append(cost) 
            print("Iteration = {}, Loss = {}".format(frame + 1, cost)) 

            return line, 
        # Create animation 
        ani = FuncAnimation(fig, update, frames=iters, interval=200, blit=True) 

        # Save the animation as a video file (e.g., MP4) 
        ani.save('linear_regression_A.gif', writer='ffmpeg') 

        plt.xlabel('Input') 
        plt.ylabel('Output') 
        plt.title('Linear Regression') 
        plt.legend() 
        plt.show() 

        return self.parameters, self.loss 
        

#Example usage
linear_reg = LinearRegression()
parameters, loss = linear_reg.train(train_input, train_output, 0.0001, 20)

 

Above code appears to be related to loading and preprocessing data for a machine learning task, specifically for linear regression. Let's break down what each part does:

url = 'https://media.geeksforgeeks.org/wp-content/uploads/20240320114716/data_for_lr.csv': This line assigns a URL string pointing to a CSV file containing data for linear regression.

Python Implementation of Linear Regression

data = pd.read_csv(url): This line uses pandas (pd) library to read the CSV file from the given URL and store it in a DataFrame called data.

data = data.dropna(): This line removes any rows with missing values (NaN) from the DataFrame.

train_input = np.array(data.x[0:500]).reshape(500, 1): This line extracts the first 500 values from the 'x' column of the DataFrame, converts it into a numpy array, and reshapes it into a 2D array with 500 rows and 1 column. This is done to prepare the training input data.

train_output = np.array(data.y[0:500]).reshape(500, 1): Similar to the previous line, this extracts the first 500 values from the 'y' column of the DataFrame, converts it into a numpy array, and reshapes it into a 2D array with 500 rows and 1 column. This is done to prepare the training output data.

test_input = np.array(data.x[500:700]).reshape(199, 1): This line extracts values from index 500 to 699 from the 'x' column of the DataFrame, converts it into a numpy array, and reshapes it into a 2D array with 199 rows and 1 column. This is done to prepare the testing input data.

test_output = np.array(data.y[500:700]).reshape(199, 1): Similar to the previous line, this extracts values from index 500 to 699 from the 'y' column of the DataFrame, converts it into a numpy array, and reshapes it into a 2D array with 199 rows and 1 column. This is done to prepare the testing output data.

So overall, this code is loading data from a CSV file, removing any rows with missing values, and then splitting the data into training and testing sets for a linear regression model.

 

Below is the output:

Iteration = 1, Loss = 9130.407560462196
Iteration = 1, Loss = 1107.1996742908998
Iteration = 1, Loss = 140.31580932842422
Iteration = 1, Loss = 23.795780526084116
Iteration = 2, Loss = 9.753848205147605
Iteration = 3, Loss = 8.061641745006835
Iteration = 4, Loss = 7.8577116490914864
Iteration = 5, Loss = 7.8331350515579015
Iteration = 6, Loss = 7.830172502503967
Iteration = 7, Loss = 7.829814681591015
Iteration = 8, Loss = 7.829770758846183
Iteration = 9, Loss = 7.829764664327399
Iteration = 10, Loss = 7.829763128602258
Iteration = 11, Loss = 7.829762142342088
Iteration = 12, Loss = 7.829761222379141
Iteration = 13, Loss = 7.829760310486438
Iteration = 14, Loss = 7.829759399646989
Iteration = 15, Loss = 7.829758489015161
Iteration = 16, Loss = 7.829757578489033
Iteration = 17, Loss = 7.829756668056319
Iteration = 18, Loss = 7.829755757715535
Iteration = 19, Loss = 7.829754847466484
Iteration = 20, Loss = 7.829753937309139

Python Implementation of Linear Regression

Tags Python Python Linear Regression Facebook X
Comments 0
Similar posts
  1. Understanding and Implementing K-Nearest Neighbors (KNN) Algorithm in Python
    632
  2. Harnessing the Power of Random Forest Algorithm in Python
    657
  3. Mastering Model Persistence: Saving and Loading Trained Machine Learning Models in Python
    1,154
  4. Forecasting with Linear Regression and KNN Regression in Python
    920
  5. Dynamic DNS Made Easy: Building a Python-Based Solution
    793
  6. Building a Basic DNS Server in PHP/Python: A Beginner's Guide
    735
  7. Implementing a Versatile DNS Server in Python: Handling A, AAAA, CNAME, and TXT Records
    1,067
  8. Simple Example to get the total number of records in BigQuery with Python
    665
  9. Learning about Python Multiprocessing Technique
    591
  10. Python script to list files on your Google Drive and download one of them
    939
  11. Method to maximize full CPU performance with Python
    314
  12. Uploading a file to a Google Drive Folder programmatically with Python
    3,305
  13. How to run Python 3.9 on Mac?
    647
  14. Is PyTorch Dead? Deep Learning's Enduring Role Beyond LLMs & Essential Skills
    691
  1. PyTorch example to Forcast Stock Price based on 10 days Dataset
    651
  2. Implementing a Versatile DNS Server in Python: Handling A, AAAA, CNAME, and TXT Records
    1,067
  3. Dynamic DNS Made Easy: Building a Python-Based Solution
    793
  4. Milvus & FAISS: Decoding Their ML Synergy
    276
  5. Save clustering result (aka dictionary) in JSON and Reuse loaded result
    376
  6. Forecasting with Linear Regression and KNN Regression in Python
    920
  7. Forecasting the Weather with PyTorch: A Beginner's Guide to Temperature Prediction
    1,431
  8. Uvicorn, Gunicorn: Proving Your Production Prowess
    395
  9. Mastering Model Persistence: Saving and Loading Trained Machine Learning Models in Python
    1,154
  10. Harnessing the Power of Random Forest Algorithm in Python
    657
  11. Understanding and Implementing K-Nearest Neighbors (KNN) Algorithm in Python
    632
  12. Mastering Random Forest Regression: A Comprehensive Guide with Python Examples
    1,093
  13. Simple Python Clustering Example based on the high school students' score
    339
  14. Getting Started with PyTorch: A Beginner's Guide to Building Your First Neural Network
    799
  15. Memory Problems with Python Arrays? Discover Dask Array
    321
  16. Mastering Supervised Machine Learning with Python: A Comprehensive Guide
    1,054
  17. Mastering AI: A Beginner's Guide to Python Programming and Beyond
    1,031
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    27
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    24
  3. How do I create animated background for Google Meet?
    19,727
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    217
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    85
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    153
  7. Array of arguments passed to script in PHP
    85
  8. Invalid Auction Storms in Ad Tech
    93
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    198
  10. The Two Clocks of Ad Server Architecture
    63
  11. Frequency Cap Architecture Overview
    509
  12. Collecting Proof-of-Play from 100,000 Screens
    141
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    280
  14. What is RedisVL?
    105
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    224
  16. TPU & GPU Cluster Management Tools
    232
  17. The Concept of Scaffolding in AI Agents
    222
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    576
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    253
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    328
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    197
  22. Machine Learning: Training vs. Ranking
    213
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    217
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    189
  25. Designing a Data Curation System Around a Vector Database
    215
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    229
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    649
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    185
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    207
  30. Understanding Data Lineage
    252