| 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. |