Forecasting the Weather with PyTorch: A Beginner's Guide to Temperature Prediction

CK CK 3788 
Created at  
1,431 0 0

Creating a weather forecasting model using PyTorch involves several steps, including data preprocessing, model design, training, and evaluation. In this simplified example, we'll use PyTorch to forecast weather parameters such as temperature. It's important to note that real-world weather forecasting models would require complex models, extensive datasets, and thorough validation to be reliable.

This example assumes you have access to a weather dataset. For simplicity, let's consider we have a dataset with daily average temperature values, and we aim to predict the temperature of the next day based on the past 30 days. If you don't have a dataset, you can often find them on platforms like Kaggle or by using APIs from weather data providers.

import numpy as np
import torch
import torch.nn as nn
from sklearn.preprocessing import MinMaxScaler

# Data preparation
np.random.seed(0)
data = np.sin(np.arange(365) * 2 * np.pi / 365) + np.random.normal(scale=0.5, size=365)
data = data.reshape(-1, 1)
scaler = MinMaxScaler(feature_range=(-1, 1))
data_normalized = scaler.fit_transform(data)

def create_sequences(data, seq_length=30):
    xs, ys = [], []
    for i in range(len(data)-seq_length):
        x = data[i:(i+seq_length)]
        y = data[i+seq_length]
        xs.append(x)
        ys.append(y)
    return np.array(xs), np.array(ys)

seq_length = 30
X, y = create_sequences(data_normalized, seq_length)
X = torch.from_numpy(X).float()
y = torch.from_numpy(y).float()

# Split the data
test_size = int(len(X) * 0.2)
train_X, test_X = X[:-test_size], X[-test_size:]
train_y, test_y = y[:-test_size], y[-test_size:]

# Model definition
class TempPredictor(nn.Module):
    def __init__(self, input_size=1, hidden_layer_size=100, output_size=1):
        super().__init__()
        self.hidden_layer_size = hidden_layer_size
        self.lstm = nn.LSTM(input_size, hidden_layer_size)
        self.linear = nn.Linear(hidden_layer_size, output_size)
        self.hidden_cell = (torch.zeros(1,1,self.hidden_layer_size),
                            torch.zeros(1,1,self.hidden_layer_size))

    def forward(self, input_seq):
        lstm_out, self.hidden_cell = self.lstm(input_seq.view(len(input_seq) ,1, -1), self.hidden_cell)
        predictions = self.linear(lstm_out.view(len(input_seq), -1))
        return predictions[-1]

# Training
def train_model(model, train_X, train_y, epochs=100, lr=0.001):
    loss_function = nn.MSELoss()
    optimizer = torch.optim.Adam(model.parameters(), lr=lr)
    for i in range(epochs):
        for seq, labels in zip(train_X, train_y):
            optimizer.zero_grad()
            model.hidden_cell = (torch.zeros(1, 1, model.hidden_layer_size),
                                 torch.zeros(1, 1, model.hidden_layer_size))
            y_pred = model(seq)
            single_loss = loss_function(y_pred, labels)
            single_loss.backward()
            optimizer.step()
        if i % 10 == 0:
            print(f'epoch: {i} loss: {single_loss.item()}')

model = TempPredictor()
train_model(model, train_X, train_y)

# Prediction
model.eval()
with torch.no_grad():
    test_seq = test_X[0].unsqueeze(0)
    pred = model(test_seq)
    pred = scaler.inverse_transform(pred.numpy().reshape(-1, 1))
    print(f'Predicted temperature: {pred[0][0]}')

This example demonstrates the basics of using PyTorch for time series forecasting, specifically for predicting temperatures. Real-world scenarios require more sophisticated data preprocessing, model tuning, and validation strategies.

Tags Artificial Intelligence Climate Science Data Science Deep Learning Environmental Science LSTM (Long Short-Term Memory) Machine Learning Meteorology Neural Networks Predictive Modeling PyTorch Python Programming RNN (Recurrent Neural Networks) Time Series Analysis Weather Forecasting Facebook X
Comments 0
Similar posts
  1. Reinforcement Learning–Based Methods for CTR Improvement based on Recommendation System
    262
  2. YouTube's Recommendation System
    258
  3. Forecasting with Linear Regression and KNN Regression in Python
    920
  4. Mastering Model Persistence: Saving and Loading Trained Machine Learning Models in Python
    1,154
  5. Harnessing the Power of Random Forest Algorithm in Python
    657
  6. Wide & Deep / DeepFM for Recommendation Service (aka Ranking Service)
    247
  7. Two-Tower Model for Recommendation Service having a Very Large Catalog
    259
  8. Sequence Models (RNN / Transformer) for Recommendation Service widely used at OTT and e-Commerce
    240
  9. Hybrid Methods for Recommendation Service
    213
  10. Model-Based CF: Matrix Factorization for Recommendation Service
    177
  11. Memory-Based Collaborative Filtering for Recommendation Service
    186
  12. Content-Based Filtering for Recommendation Service (aka User-based Model)
    187
  13. Understanding and Implementing K-Nearest Neighbors (KNN) Algorithm in Python
    632
  14. Vector Databases: From Embeddings to Application
    310
  15. Image Embeddings for Vector Databases
    241
  16. Getting Started with PyTorch: A Beginner's Guide to Building Your First Neural Network
    799
  17. Mastering AI: A Beginner's Guide to Python Programming and Beyond
    1,031
  18. Machine Learning Models for Ad Detection from a Video Stream
    185
  19. FAISS Already Does ANN... So Why Do Top Teams Still Pay for SageMaker?
    307
  20. TikTok's Recommendation System - Monolith
    287
  21. Milvus & FAISS: Decoding Their ML Synergy
    276
  22. PyTorch example to Forcast Stock Price based on 10 days Dataset
    651
  23. Predicting Buyer Preferences with PyTorch: A Deep Learning Approach
    1,231
  24. Mastering Ad Budget Throttling: Static, PID, and ML Strategies
    316
  25. Ad Impression Forecasting (aka Ad Inventory Forecasting): Architecting for Scale, Speed, and Accuracy
    327
  26. AI-Powered Ad Fraud Detection: Architectural Strategies
    331
  27. Brand Safety: AI-Driven Content Moderation on AWS
    710
  28. Building Initial Virtual Environment at Python - The first step you should do for Python Programming
    559
  29. Building a MCP server in PHP
    627
  30. Python ML Technologies used for the target Segmentation
    376
  1. Thread Implementation in Python
    508
  2. A shell script that activates a Python virtual environment and then runs a specific Python script
    741
  3. Learning about Python Multiprocessing Technique
    591
  4. Simple Example to get the total number of records in BigQuery with Python
    665
  5. Using BigQuery in Python
    407
  6. Python Web Programming based on Django from the Scratch
    366
  7. Flink with Python: Core Concepts, Kafka Integration, and Architectural Trade-offs
    184
  8. How do I determine the client IP type in Python - IPv4 or IPv6
    760
  9. Predicting Buyer Preferences with PyTorch: A Deep Learning Approach
    1,231
  10. PyTorch example to Forcast Stock Price based on 10 days Dataset
    651
  11. Implementing a Versatile DNS Server in Python: Handling A, AAAA, CNAME, and TXT Records
    1,067
  12. Dynamic DNS Made Easy: Building a Python-Based Solution
    793
  13. Milvus & FAISS: Decoding Their ML Synergy
    276
  14. Save clustering result (aka dictionary) in JSON and Reuse loaded result
    376
  15. Forecasting with Linear Regression and KNN Regression in Python
    920
  16. Uvicorn, Gunicorn: Proving Your Production Prowess
    395
  17. Mastering Model Persistence: Saving and Loading Trained Machine Learning Models in Python
    1,154
  18. Harnessing the Power of Random Forest Algorithm in Python
    657
  19. Understanding and Implementing K-Nearest Neighbors (KNN) Algorithm in Python
    632
  20. Mastering Random Forest Regression: A Comprehensive Guide with Python Examples
    1,093
  21. Simple Python Clustering Example based on the high school students' score
    339
  22. Getting Started with PyTorch: A Beginner's Guide to Building Your First Neural Network
    799
  23. Memory Problems with Python Arrays? Discover Dask Array
    321
  24. Python Implementation of Linear Regression
    836
  25. Mastering Supervised Machine Learning with Python: A Comprehensive Guide
    1,054
  26. 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,712
  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
    221
  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
    327
  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