Forecasting with Linear Regression and KNN Regression in Python

CK CK 3788 
Created at  
926 0 0

In the realm of machine learning, making accurate predictions based on historical data is a common and crucial task. Two popular methods for tackling such problems are Linear Regression and K-Nearest Neighbors (KNN) Regression. Both come with their unique strengths and applications. In this post, we'll dive into how to implement these models for forecasting using Python's scikit-learn library, focusing on a simple example without the complexity of graphs to keep our focus on the predictions.

Setting Up

Before we start, make sure you have the scikit-learn library installed in your environment:

pip install scikit-learn

The Dataset

Our dataset is straightforward, consisting of ten points, making it easier to understand how our models will learn and predict. We have an input array X and an output array y, with a simple relationship: y = 2x.

X = np.array([[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]])
y = np.array([2, 4, 6, 8, 10, 12, 14, 16, 18, 20])

Linear Regression for Forecasting

Linear Regression works by establishing a linear relationship between the input variables and the target variable. After training our model with the given dataset, we aim to predict the output for a new input, X_new = [[11]].

Implementation

from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression

# Splitting dataset into training and testing set
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Linear Regression
model = LinearRegression()
model.fit(X_train, y_train)

# Forecasting
X_new = np.array([[11]])  # New sample X
y_new_pred = model.predict(X_new)

print(f"Forecasted value for X_new = {X_new.flatten()}: {y_new_pred.flatten()}")

 

KNN Regression for Forecasting

KNN Regression predicts the value for a new point based on the closest k neighbors' values. It's particularly useful in scenarios where the relationship between the data points is not linear.

Implementation

from sklearn.neighbors import KNeighborsRegressor

# KNN Regression
knn_model = KNeighborsRegressor(n_neighbors=3)
knn_model.fit(X_train, y_train)

# Forecasting
y_new_pred_knn = knn_model.predict(X_new)

print(f"Forecasted value for X_new = {X_new.flatten()} with KNN: {y_new_pred_knn.flatten()}")

Conclusion

Both Linear Regression and KNN Regression offer valuable tools for forecasting in machine learning. The choice between them depends on the specific characteristics of your data and the nature of the problem at hand. In our simple example, given the linear relationship between X and y, Linear Regression is expected to perform exceptionally well. However, KNN Regression can be particularly useful in cases where the relationship is more complex or nonlinear.

Remember, the key to successful machine learning projects lies in understanding your data and choosing the right model based on that understanding. Happy forecasting!

Tags Forecasting KNN Linear Regression Machine Learning Python scikit-learn Facebook X
Comments 0
Similar posts
  1. Forecasting the Weather with PyTorch: A Beginner's Guide to Temperature Prediction
    1,434
  2. Vector Databases: From Embeddings to Application
    315
  3. YouTube's Recommendation System
    263
  4. Mastering Model Persistence: Saving and Loading Trained Machine Learning Models in Python
    1,156
  5. Harnessing the Power of Random Forest Algorithm in Python
    658
  6. Wide & Deep / DeepFM for Recommendation Service (aka Ranking Service)
    253
  7. Two-Tower Model for Recommendation Service having a Very Large Catalog
    263
  8. Sequence Models (RNN / Transformer) for Recommendation Service widely used at OTT and e-Commerce
    248
  9. Hybrid Methods for Recommendation Service
    217
  10. Model-Based CF: Matrix Factorization for Recommendation Service
    180
  11. Memory-Based Collaborative Filtering for Recommendation Service
    193
  12. Content-Based Filtering for Recommendation Service (aka User-based Model)
    189
  13. Machine Learning Models for Ad Detection from a Video Stream
    188
  14. FAISS Already Does ANN... So Why Do Top Teams Still Pay for SageMaker?
    309
  15. Milvus & FAISS: Decoding Their ML Synergy
    278
  16. Dynamic DNS Made Easy: Building a Python-Based Solution
    795
  17. Building a Basic DNS Server in PHP/Python: A Beginner's Guide
    739
  18. Implementing a Versatile DNS Server in Python: Handling A, AAAA, CNAME, and TXT Records
    1,071
  19. Understanding and Implementing K-Nearest Neighbors (KNN) Algorithm in Python
    633
  20. PyTorch example to Forcast Stock Price based on 10 days Dataset
    651
  21. Predicting Buyer Preferences with PyTorch: A Deep Learning Approach
    1,233
  22. Mastering Ad Budget Throttling: Static, PID, and ML Strategies
    321
  23. Ad Impression Forecasting (aka Ad Inventory Forecasting): Architecting for Scale, Speed, and Accuracy
    330
  24. AI-Powered Ad Fraud Detection: Architectural Strategies
    334
  25. Brand Safety: AI-Driven Content Moderation on AWS
    719
  26. Simple Example to get the total number of records in BigQuery with Python
    666
  27. Learning about Python Multiprocessing Technique
    592
  28. Python script to list files on your Google Drive and download one of them
    941
  29. Method to maximize full CPU performance with Python
    317
  30. Uploading a file to a Google Drive Folder programmatically with Python
    3,307
  1. Simple Web Server based in Python
    373
  2. Thread Implementation in Python
    509
  3. A shell script that activates a Python virtual environment and then runs a specific Python script
    742
  4. Learning about Python Multiprocessing Technique
    592
  5. Simple Example to get the total number of records in BigQuery with Python
    666
  6. Using BigQuery in Python
    410
  7. Python Web Programming based on Django from the Scratch
    373
  8. Flink with Python: Core Concepts, Kafka Integration, and Architectural Trade-offs
    187
  9. How do I determine the client IP type in Python - IPv4 or IPv6
    762
  10. Predicting Buyer Preferences with PyTorch: A Deep Learning Approach
    1,233
  11. PyTorch example to Forcast Stock Price based on 10 days Dataset
    651
  12. Implementing a Versatile DNS Server in Python: Handling A, AAAA, CNAME, and TXT Records
    1,071
  13. Dynamic DNS Made Easy: Building a Python-Based Solution
    795
  14. Milvus & FAISS: Decoding Their ML Synergy
    278
  15. Save clustering result (aka dictionary) in JSON and Reuse loaded result
    378
  16. Forecasting the Weather with PyTorch: A Beginner's Guide to Temperature Prediction
    1,434
  17. Uvicorn, Gunicorn: Proving Your Production Prowess
    397
  18. Mastering Model Persistence: Saving and Loading Trained Machine Learning Models in Python
    1,156
  19. Harnessing the Power of Random Forest Algorithm in Python
    658
  20. Understanding and Implementing K-Nearest Neighbors (KNN) Algorithm in Python
    633
  21. Mastering Random Forest Regression: A Comprehensive Guide with Python Examples
    1,096
  22. Simple Python Clustering Example based on the high school students' score
    340
  23. Getting Started with PyTorch: A Beginner's Guide to Building Your First Neural Network
    800
  24. Memory Problems with Python Arrays? Discover Dask Array
    323
  25. Python Implementation of Linear Regression
    840
  26. Mastering Supervised Machine Learning with Python: A Comprehensive Guide
    1,057
  27. Mastering AI: A Beginner's Guide to Python Programming and Beyond
    1,034
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    40
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    34
  3. How do I create animated background for Google Meet?
    20,613
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    244
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    94
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    157
  7. Array of arguments passed to script in PHP
    90
  8. Invalid Auction Storms in Ad Tech
    98
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    202
  10. The Two Clocks of Ad Server Architecture
    70
  11. Frequency Cap Architecture Overview
    514
  12. Collecting Proof-of-Play from 100,000 Screens
    146
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    287
  14. What is RedisVL?
    109
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    230
  16. TPU & GPU Cluster Management Tools
    244
  17. The Concept of Scaffolding in AI Agents
    233
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    583
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    259
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    339
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    202
  22. Machine Learning: Training vs. Ranking
    221
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    222
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    195
  25. Designing a Data Curation System Around a Vector Database
    220
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    256
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    656
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    195
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    217
  30. Understanding Data Lineage
    260