Compare commits
No files matched your search
Vendored
+4
-1
@@ -1,3 +1,6 @@
|
||||
{
|
||||
"recommendations": ["ms-python.python", "ms-toolsai.jupyter"]
|
||||
"recommendations": [
|
||||
"ms-python.python",
|
||||
"ms-toolsai.jupyter"
|
||||
]
|
||||
}
|
||||
@@ -14,8 +14,10 @@ how to git? do not `push --force`. prefer pull requests. its like github
|
||||
|
||||
we will plan to do this in multiple different ways using scikit-learn and pytorch. tensorflow is ancient.
|
||||
|
||||
> [!IMPORTANT]
|
||||
> phase out tensorflow. dont use it.
|
||||
> [!NOTE]
|
||||
> ~phase out tensorflow. dont use it.~
|
||||
>
|
||||
> its 2 different platforms for 2 different types of people. use whatever ig
|
||||
|
||||
maybe also fit more weather related stats? this dataset is taken from nasa so sources are there
|
||||
|
||||
|
||||
-14429
File diff suppressed because it is too large.
Load diff
+71
-9
@@ -1,12 +1,45 @@
|
||||
import sys
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from datetime import datetime
|
||||
import logging
|
||||
from global_config import DATA_FILE_NAME
|
||||
|
||||
# Configure logging
|
||||
logging.basicConfig(
|
||||
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
|
||||
)
|
||||
|
||||
# Define parameters
|
||||
latitude, longitude = 21.04815477090267, 105.80123159165096 # lmao
|
||||
start_date = "2010-01-01"
|
||||
latitude, longitude = 21.04815477090267, 105.80123159165096 # Default: Hanoi
|
||||
# start_date = "1981-01-01"
|
||||
start_date = "2001-01-01"
|
||||
end_date = datetime.now().strftime("%Y-%m-%d") # Today's date
|
||||
|
||||
# most used parameters from NASA POWER API:
|
||||
# T2M MERRA-2 Temperature at 2 Meters (C)
|
||||
# T2M_MAX MERRA-2 Maximum Temperature at 2 Meters (C)
|
||||
# T2M_MIN MERRA-2 Minimum Temperature at 2 Meters (C)
|
||||
# T2MDEW MERRA-2 Dew/Frost Point at 2 Meters (C)
|
||||
# T2MWET MERRA-2 Wet Bulb Temperature at 2 Meters (C)
|
||||
# PRECTOTCORR MERRA-2 Precipitation Corrected (mm/day)
|
||||
# ALLSKY_SFC_SW_DWN All Sky Surface Shortwave Downward Irradiance (kW-hr/m^2/day)
|
||||
# CLRSKY_SFC_SW_DWN Clear Sky Surface Shortwave Downward Irradiance (kW-hr/m^2/day)
|
||||
# RH2M MERRA-2 Relative Humidity at 2 Meters (%)
|
||||
# QV2M MERRA-2 Specific Humidity at 2 Meters (g/kg)
|
||||
# PS MERRA-2 Surface Pressure (kPa)
|
||||
# WS10M MERRA-2 Wind Speed at 10 Meters (m/s)
|
||||
# WS50M MERRA-2 Wind Speed at 50 Meters (m/s)
|
||||
# WD10M MERRA-2 Wind Direction at 10 Meters (Degrees)
|
||||
# WD50M MERRA-2 Wind Direction at 50 Meters (Degrees)
|
||||
# TS MERRA-2 Earth Skin Temperature (C)
|
||||
# PRECTOT MERRA-2 Precipitation (mm/day)
|
||||
# ALLSKY_KT All Sky Insolation Clearness Index (dimensionless)
|
||||
# CLRSKY_KT Clear Sky Insolation Clearness Index (dimensionless)
|
||||
# ALLSKY_SFC_LW_DWN All Sky Surface Longwave Downward Irradiance (W/m^2)
|
||||
# CLOUD_AMT Cloud amount (%)
|
||||
|
||||
|
||||
# Define desired parameters
|
||||
# T2M MERRA-2 Temperature at 2 Meters (C)
|
||||
# PRECTOTCORR MERRA-2 Precipitation Corrected (mm/day)
|
||||
@@ -16,9 +49,29 @@ end_date = datetime.now().strftime("%Y-%m-%d") # Today's date
|
||||
# WS10M MERRA-2 Wind Speed at 10 Meters (m/s)
|
||||
# WD10M MERRA-2 Wind Direction at 10 Meters (Degrees)
|
||||
# more at https://power.larc.nasa.gov/data-access-viewer/
|
||||
weather_params = [
|
||||
"T2M",
|
||||
"T2M_MAX",
|
||||
"T2M_MIN",
|
||||
"T2MDEW",
|
||||
"PRECTOTCORR",
|
||||
"QV2M",
|
||||
"RH2M",
|
||||
"PS",
|
||||
"CLOUD_AMT",
|
||||
"WS10M",
|
||||
"WD10M",
|
||||
"ALLSKY_KT",
|
||||
"ALLSKY_SFC_SW_DWN",
|
||||
]
|
||||
|
||||
|
||||
if len(weather_params) > 20:
|
||||
logging.error("too much! %d params bigger than 20", len(weather_params))
|
||||
sys.exit(1)
|
||||
|
||||
params = {
|
||||
"parameters": "QV2M,T2M,PRECTOTCORR",
|
||||
"parameters": ",".join(weather_params),
|
||||
"community": "RE",
|
||||
"longitude": longitude,
|
||||
"latitude": latitude,
|
||||
@@ -37,13 +90,22 @@ url = f"{base_url}?{query_string}"
|
||||
|
||||
# Make the API request using urllib
|
||||
try:
|
||||
logging.info("Requesting data from NASA POWER API...")
|
||||
with urllib.request.urlopen(url) as response:
|
||||
if response.status == 200:
|
||||
csv_data = response.read().decode("utf-8")
|
||||
with open("hanoi_weather_data.csv", "w", encoding="utf-8") as file:
|
||||
file.write(csv_data)
|
||||
print("Data successfully downloaded and saved to 'hanoi_weather_data.csv'.")
|
||||
# Save data to file
|
||||
with open(DATA_FILE_NAME, "wb") as file:
|
||||
while chunk := response.read(1024): # Read 1 KB at a time
|
||||
file.write(chunk)
|
||||
logging.info(
|
||||
"Data successfully downloaded and saved to '%s'.", DATA_FILE_NAME
|
||||
)
|
||||
else:
|
||||
print(f"Failed to retrieve data: HTTP Status Code {response.status}")
|
||||
print("re", response.read().decode())
|
||||
logging.error(
|
||||
"Failed to retrieve data: HTTP Status Code %s", response.status
|
||||
)
|
||||
except urllib.error.URLError as e:
|
||||
print(f"Failed to retrieve data: {e.reason}")
|
||||
logging.error("Failed to retrieve data: %s", e)
|
||||
except Exception as e:
|
||||
logging.error("An unexpected error occurred: %s", e)
|
||||
@@ -0,0 +1 @@
|
||||
DATA_FILE_NAME = "hanoi_weather_data.csv"
|
||||
+16200
File diff suppressed because it is too large.
Load diff
+23
-15
@@ -7,12 +7,14 @@ from typing import Union
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from global_config import DATA_FILE_NAME
|
||||
|
||||
|
||||
def cut_headers(stream: Union[io.StringIO, io.FileIO, io.TextIOWrapper]):
|
||||
headers = []
|
||||
exist_startheader = False
|
||||
|
||||
while line := stream.readline():
|
||||
p99_header = 123 # should there be header
|
||||
while (line := stream.readline()) and p99_header > 0:
|
||||
if "-BEGIN HEADER-" in line and not exist_startheader:
|
||||
exist_startheader = True
|
||||
headers.append(str(line.strip()))
|
||||
@@ -23,8 +25,9 @@ def cut_headers(stream: Union[io.StringIO, io.FileIO, io.TextIOWrapper]):
|
||||
# print(f"{line = }")
|
||||
headers.append(str(line.strip()))
|
||||
elif not exist_startheader:
|
||||
continue
|
||||
if not exist_startheader:
|
||||
p99_header -= 1
|
||||
# continue
|
||||
if not exist_startheader or p99_header == 0:
|
||||
# If no headers are found, reset the stream and return
|
||||
stream.seek(0)
|
||||
return "", stream
|
||||
@@ -53,10 +56,15 @@ def load_data(
|
||||
return data
|
||||
|
||||
|
||||
def date_combine(data: pd.DataFrame):
|
||||
def date_combine(data: pd.DataFrame, verbose=False):
|
||||
data["Date"] = pd.to_datetime(data[["Year", "Month", "Day"]])
|
||||
data = data.drop(columns=["Year", "Month", "Day"])
|
||||
if verbose:
|
||||
print("b4 set index", data.columns)
|
||||
data = data.set_index("Date")
|
||||
if verbose:
|
||||
print("after set index", data.columns)
|
||||
|
||||
return data
|
||||
|
||||
|
||||
@@ -73,15 +81,15 @@ def validate_view(data: pd.DataFrame, verbose=False):
|
||||
return data
|
||||
|
||||
|
||||
# if __name__ == "__main__":
|
||||
def load_this_data(filename, verbose=False):
|
||||
d = load_data(filename)
|
||||
# if verbose:
|
||||
# print(d.columns)
|
||||
d = date_combine(d)
|
||||
# if verbose:
|
||||
# print(d.columns)
|
||||
def load_this_data(filename=DATA_FILE_NAME, verbose=False, *a):
|
||||
d = load_data(filename, *a)
|
||||
d = date_combine(d, verbose)
|
||||
d = validate_view(d, verbose)
|
||||
# if verbose:
|
||||
# print(d.columns)
|
||||
if verbose:
|
||||
print(d.head())
|
||||
print(d.columns)
|
||||
return d
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
load_this_data(verbose=True)
|
||||
+1260
-321
File diff suppressed because it is too large.
Load diff
+37
-16
@@ -1,3 +1,5 @@
|
||||
import os
|
||||
|
||||
from sklearn.model_selection import train_test_split
|
||||
import torch
|
||||
|
||||
@@ -8,7 +10,7 @@ from sklearn.preprocessing import MinMaxScaler
|
||||
import numpy as np
|
||||
from load_data import load_this_data
|
||||
|
||||
a = load_this_data("dataset.csv")
|
||||
a = load_this_data()
|
||||
|
||||
# time series forecasting
|
||||
|
||||
@@ -19,23 +21,23 @@ scaled_data = scaler.fit_transform(a)
|
||||
|
||||
|
||||
def create_sequences(data, seq_length):
|
||||
xs = []
|
||||
ys = []
|
||||
"see this? return[0] is the big x and return[1] is the big y. and h(x) = y. and h(x) is the model."
|
||||
xs, ys, dates = [], [], []
|
||||
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)
|
||||
xs.append(data[i : i + seq_length])
|
||||
ys.append(data[i + seq_length])
|
||||
dates.append(i + seq_length) # index of target
|
||||
return np.array(xs), np.array(ys), np.array(dates)
|
||||
|
||||
|
||||
seq_length = 20
|
||||
|
||||
X, y = create_sequences(scaled_data, seq_length)
|
||||
X, y, y_indices = create_sequences(scaled_data, seq_length)
|
||||
|
||||
X_train, X_test, y_train, y_test = train_test_split(
|
||||
X, y, test_size=0.2, random_state=42
|
||||
)
|
||||
|
||||
from torch.utils.data import TensorDataset, DataLoader
|
||||
|
||||
X_train_tensor = torch.tensor(X_train, dtype=torch.float32)
|
||||
@@ -65,21 +67,28 @@ class LSTMModel(nn.Module):
|
||||
return out
|
||||
|
||||
|
||||
model = LSTMModel(
|
||||
modfile = "data/model.pth"
|
||||
yesmod = os.path.isfile(modfile)
|
||||
if yesmod:
|
||||
model = torch.load(modfile)
|
||||
else:
|
||||
model = LSTMModel(
|
||||
input_size=X_train.shape[2],
|
||||
hidden_size=64,
|
||||
num_layers=2,
|
||||
output_size=y_train.shape[1],
|
||||
)
|
||||
)
|
||||
model.to(device)
|
||||
criterion = nn.MSELoss()
|
||||
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
|
||||
|
||||
train_losses = []
|
||||
val_losses = []
|
||||
|
||||
criterion = nn.MSELoss()
|
||||
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
|
||||
|
||||
for epoch in range(100):
|
||||
if not yesmod:
|
||||
|
||||
for epoch in range(100):
|
||||
model.train()
|
||||
running_train_loss = 0.0
|
||||
|
||||
@@ -102,6 +111,9 @@ for epoch in range(100):
|
||||
epoch_train_loss = running_train_loss / len(train_loader.dataset)
|
||||
train_losses.append(epoch_train_loss)
|
||||
|
||||
torch.save(model, modfile)
|
||||
# yesmod = True
|
||||
|
||||
model.eval()
|
||||
|
||||
X_test_tensor = torch.tensor(X_test, dtype=torch.float32).to(device)
|
||||
@@ -151,8 +163,17 @@ ax1.legend()
|
||||
ax1.grid(True)
|
||||
|
||||
# Prediction vs Actual on the right
|
||||
ax2.plot(y_test_rescaled, label="Actual")
|
||||
ax2.plot(predictions_rescaled, label="Predicted")
|
||||
|
||||
# 2024 - 25
|
||||
_, X_test_idx, _, y_test_idx = train_test_split(
|
||||
X, y_indices, test_size=0.2, random_state=42
|
||||
)
|
||||
dates_test = a["Date"].iloc[y_test_idx].values # Actual datetime values
|
||||
|
||||
mask = (dates_test >= "2024-01-01") & (dates_test <= "2025-12-31")
|
||||
# Plot the results
|
||||
ax2.plot(dates_test[mask], y_test_rescaled[mask], label="Actual")
|
||||
ax2.plot(dates_test[mask], predictions_rescaled[mask], label="Predicted")
|
||||
ax2.set_title("Actual vs. Predicted")
|
||||
ax2.set_xlabel("Sample")
|
||||
ax2.set_ylabel("Value")
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,304 +0,0 @@
|
||||
"""
|
||||
This script demonstrates how to port a TensorFlow LSTM model to PyTorch.
|
||||
It includes detailed explanations for every step.
|
||||
"""
|
||||
|
||||
# Step 1: Import necessary libraries
|
||||
# ----------------------------------
|
||||
# PyTorch is the core library for building and training neural networks.
|
||||
# Torch.nn contains modules for defining layers and loss functions.
|
||||
# Torch.optim provides optimizers like Adam for training.
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
import torch
|
||||
from sklearn.model_selection import train_test_split
|
||||
from sklearn.preprocessing import MinMaxScaler
|
||||
from torch import nn, optim
|
||||
from torch.utils.data import DataLoader, TensorDataset
|
||||
|
||||
import sys
|
||||
|
||||
sys.path.append(r"c:\Users\Admin\Documents\lecture ass shit\ml1\codemidterm\ml_midterm")
|
||||
|
||||
from load_data import load_this_data
|
||||
|
||||
# Step 2: Data Preparation
|
||||
# ------------------------
|
||||
# In PyTorch, data must be converted into tensors. We'll simulate the data
|
||||
# preprocessing steps from your TensorFlow code.
|
||||
|
||||
|
||||
# Simulate some data (replace this with your actual data loading logic)
|
||||
np.random.seed(42) # For reproducibility
|
||||
# data = np.sin(np.linspace(0, 100, 1000)) # Example: Sine wave data
|
||||
# data = data.reshape(-1, 1) # Reshape to (samples, features)
|
||||
|
||||
|
||||
# Load the dataset (replace "dataset.csv" with your actual file path)
|
||||
data = load_this_data("dataset.csv")
|
||||
|
||||
|
||||
# Extract the "Humidity" column as the target variable
|
||||
data = data["Humidity"].values.reshape(-1, 1)
|
||||
|
||||
# Normalize the data using MinMaxScaler (same as in TensorFlow)
|
||||
scaler = MinMaxScaler()
|
||||
data_scaled = scaler.fit_transform(data)
|
||||
|
||||
# Define lookback window (sequence length for LSTM)
|
||||
n_lookback = 100 # Number of past timesteps to consider
|
||||
n_features = 1 # Number of features (e.g., 1 for univariate time series)
|
||||
|
||||
|
||||
# Helper function to create sequences
|
||||
def create_sequences(data, n_lookback):
|
||||
"""
|
||||
Create sequences of length n_lookback for LSTM input.
|
||||
|
||||
Args:
|
||||
data: Scaled data as a NumPy array or PyTorch tensor.
|
||||
n_lookback: Number of past timesteps to consider.
|
||||
|
||||
Returns:
|
||||
x: Input sequences of shape (num_samples, n_lookback, n_features).
|
||||
y: Target values of shape (num_samples, 1).
|
||||
"""
|
||||
x, y = [], []
|
||||
for i in range(len(data) - n_lookback):
|
||||
x.append(data[i : i + n_lookback])
|
||||
y.append(data[i + n_lookback])
|
||||
return np.array(x), np.array(y)
|
||||
|
||||
|
||||
# Split into training and testing sets
|
||||
split_index = int(0.8 * len(data_scaled))
|
||||
train_data = data_scaled[:split_index]
|
||||
test_data = data_scaled[split_index:]
|
||||
|
||||
# Create sequences for training and testing
|
||||
train_x, train_y = create_sequences(train_data, n_lookback)
|
||||
test_x, test_y = create_sequences(test_data, n_lookback)
|
||||
|
||||
# train_y = scaler.transform(train_y)
|
||||
# test_y = scaler.transform(test_y)
|
||||
# Convert sequences to PyTorch tensors
|
||||
train_x = torch.tensor(train_x, dtype=torch.float32)
|
||||
train_y = torch.tensor(train_y, dtype=torch.float32)
|
||||
test_x = torch.tensor(test_x, dtype=torch.float32)
|
||||
test_y = torch.tensor(test_y, dtype=torch.float32)
|
||||
|
||||
|
||||
# Create datasets and dataloaders
|
||||
train_dataset = TensorDataset(train_x, train_y)
|
||||
test_dataset = TensorDataset(test_x, test_y)
|
||||
|
||||
train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)
|
||||
test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)
|
||||
|
||||
# Step 3: Define the LSTM Model
|
||||
# -----------------------------
|
||||
# PyTorch models are defined by subclassing `nn.Module`.
|
||||
# The forward method specifies how data flows through the model.
|
||||
|
||||
|
||||
# class LSTMModel(nn.Module):
|
||||
# def __init__(self, n_features, n_lookback, n_neurons):
|
||||
# """
|
||||
# Initialize the LSTM model.
|
||||
|
||||
# Args:
|
||||
# n_features: Number of input features (e.g., 1 for univariate time series).
|
||||
# n_lookback: Number of past timesteps to consider.
|
||||
# n_neurons: Number of neurons in each LSTM layer.
|
||||
# """
|
||||
# super(LSTMModel, self).__init__()
|
||||
# self.lstm1 = nn.LSTM(
|
||||
# n_features,
|
||||
# n_neurons,
|
||||
# batch_first=True,
|
||||
# dropout=0.2,
|
||||
# )
|
||||
# self.lstm2 = nn.LSTM(
|
||||
# n_neurons,
|
||||
# n_neurons,
|
||||
# batch_first=True,
|
||||
# )
|
||||
# self.lstm3 = nn.LSTM(n_neurons, n_neurons, batch_first=True)
|
||||
# self.lstm4 = nn.LSTM(n_neurons, n_neurons, batch_first=True)
|
||||
# self.fc = nn.Linear(n_neurons, 1)
|
||||
# self.dropout = nn.Dropout(0.2)
|
||||
|
||||
# def forward(self, x):
|
||||
# """
|
||||
# Forward pass through the model.
|
||||
|
||||
# Args:
|
||||
# x: Input tensor of shape (batch, seq_len, n_features).
|
||||
|
||||
# Returns:
|
||||
# Output tensor of shape (batch, 1).
|
||||
# """
|
||||
# x, _ = self.lstm1(x)
|
||||
# x, _ = self.lstm2(x)
|
||||
# x, _ = self.lstm3(x)
|
||||
# x, _ = self.lstm4(x)
|
||||
# x = self.dropout(x)
|
||||
# x = self.fc(x[:, -1, :]) # Use the last timestep's output
|
||||
# return x
|
||||
|
||||
print("Input sequences (x):", train_x.shape)
|
||||
print("Target values (y):", train_y.shape)
|
||||
|
||||
print("Sample input:", train_x[0])
|
||||
print("Corresponding target:", train_y[0])
|
||||
|
||||
class LSTMModel(nn.Module):
|
||||
def __init__(self, n_features, n_lookback, n_neurons):
|
||||
super(LSTMModel, self).__init__()
|
||||
self.lstm = nn.LSTM(n_features, n_neurons, batch_first=True, dropout=0.2)
|
||||
self.lstm2 = nn.LSTM(n_neurons, n_neurons, batch_first=True, dropout=0.2)
|
||||
|
||||
self.fc = nn.Linear(n_neurons, 1)
|
||||
|
||||
def forward(self, x):
|
||||
x, _ = self.lstm(x)
|
||||
x, _ = self.lstm2(x)
|
||||
x = self.fc(x[:, -1, :]) # Use the last timestep's output
|
||||
return x
|
||||
|
||||
|
||||
# Instantiate the model
|
||||
n_neurons = 128 # Number of neurons in the LSTM
|
||||
model = LSTMModel(n_features, n_lookback, n_neurons)
|
||||
|
||||
# Step 4: Define Loss Function and Optimizer
|
||||
# ------------------------------------------
|
||||
# Loss function: Mean Squared Error (MSE) for regression tasks.
|
||||
# Optimizer: Adam optimizer for efficient training.
|
||||
criterion = nn.MSELoss()
|
||||
optimizer = optim.Adam(model.parameters(), lr=0.001)
|
||||
|
||||
# Step 5: Train the Model
|
||||
# -----------------------
|
||||
# PyTorch requires an explicit training loop. This gives you full control
|
||||
# over the training process.
|
||||
|
||||
epochs = 50 # Number of training epochs
|
||||
|
||||
# Check for CUDA and set the device
|
||||
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
print(f"Using device: {device}")
|
||||
|
||||
# Move the model to the device
|
||||
model = LSTMModel(n_features, n_lookback, n_neurons).to(device)
|
||||
|
||||
# scheduler = optim.lr_scheduler.ReduceLROnPlateau(
|
||||
# optimizer, mode="min", patience=5, factor=0.5, min_lr=1e-6
|
||||
# )
|
||||
# Move data to the device during training and evaluation
|
||||
for epoch in range(epochs):
|
||||
model.train() # Set the model to training mode
|
||||
train_loss = 0.0
|
||||
|
||||
for x_batch, y_batch in train_loader:
|
||||
# Move data to the device
|
||||
x_batch = x_batch.to(device)
|
||||
y_batch = y_batch.to(device)
|
||||
# Reshape input to (batch, seq_len, n_features)
|
||||
x_batch = x_batch.view(-1, n_lookback, n_features)
|
||||
# y_batch = y_batch.view(-1, 1)
|
||||
# print("x_batch shape:", x_batch.shape)
|
||||
# print("y_batch shape:", y_batch.shape)
|
||||
# print("x_batch dtype:", x_batch.dtype)
|
||||
# print("y_batch dtype:", y_batch.dtype)
|
||||
# break
|
||||
# Zero the gradients from the previous step
|
||||
optimizer.zero_grad()
|
||||
|
||||
# Forward pass: Compute predictions
|
||||
predictions = model(x_batch)
|
||||
# if epoch == 32:
|
||||
# for name, param in model.named_parameters():
|
||||
# if param.grad is not None:
|
||||
# print(f"{name} gradient mean: {param.grad.mean().item()}")
|
||||
# else:
|
||||
# print(f"{name} has no gradient")
|
||||
# print("Predictions device:", predictions.device)
|
||||
# print("y_batch device:", y_batch.device)
|
||||
# print("Predictions shape:", predictions.shape)
|
||||
# print("y_batch shape:", y_batch.shape)
|
||||
# Compute the loss
|
||||
loss = criterion(predictions, y_batch)
|
||||
|
||||
# Backward pass: Compute gradients
|
||||
loss.backward()
|
||||
|
||||
# Clip gradients to prevent exploding gradients
|
||||
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
|
||||
|
||||
# Update model parameters
|
||||
optimizer.step()
|
||||
# scheduler.step(train_loss / len(train_loader))
|
||||
# Accumulate the loss for reporting
|
||||
train_loss += loss.item()
|
||||
|
||||
# Print epoch loss
|
||||
print(f"Epoch {epoch+1}/{epochs}, Loss: {train_loss/len(train_loader):.4f}")
|
||||
|
||||
if epoch % 10 == 0: # Print every 10 epochs
|
||||
print(
|
||||
f"Sample prediction: {predictions[0].item()}, Actual: {y_batch[0].item()}"
|
||||
)
|
||||
# Step 6: Evaluate the Model
|
||||
# --------------------------
|
||||
# Switch to evaluation mode and disable gradient computation.
|
||||
model.eval()
|
||||
with torch.no_grad():
|
||||
predictions = []
|
||||
actuals = []
|
||||
|
||||
for x_batch, y_batch in test_loader:
|
||||
# Move data to the device
|
||||
x_batch = x_batch.to(device)
|
||||
y_batch = y_batch.to(device)
|
||||
|
||||
# Reshape input to (batch, seq_len, n_features)
|
||||
# x_batch = x_batch.view(-1, n_lookback, n_features)
|
||||
|
||||
# Make predictions
|
||||
preds = model(x_batch)
|
||||
|
||||
# Move predictions and actuals back to CPU for further processing
|
||||
predictions.append(preds.cpu().numpy())
|
||||
actuals.append(y_batch.cpu().numpy())
|
||||
|
||||
# Convert predictions and actuals to NumPy arrays for comparison
|
||||
predictions = np.concatenate(predictions)
|
||||
actuals = np.concatenate(actuals)
|
||||
|
||||
# Step 7: Post-Processing and Visualization
|
||||
# -----------------------------------------
|
||||
# Inverse transform the predictions and actuals to get original scale
|
||||
predictions = scaler.inverse_transform(predictions)
|
||||
actuals = scaler.inverse_transform(actuals)
|
||||
|
||||
# Plot the results
|
||||
print("Sample scaled train_y:", train_y[:5])
|
||||
print("Sample scaled test_y:", test_y[:5])
|
||||
|
||||
print("Predictions shape:", predictions.shape)
|
||||
print("Actuals shape:", actuals.shape)
|
||||
|
||||
print("Sample inverse-transformed predictions:", predictions[:5])
|
||||
print("Sample inverse-transformed actuals:", actuals[:5])
|
||||
|
||||
plt.figure(figsize=(20, 5))
|
||||
plt.plot(actuals, label="Actual")
|
||||
plt.plot(predictions, label="Predicted")
|
||||
plt.legend()
|
||||
plt.show()
|
||||
|
||||
from sklearn.metrics import r2_score, mean_squared_error
|
||||
|
||||
print("R² Score:", r2_score(actuals, predictions))
|
||||
print("MSE:", mean_squared_error(actuals, predictions))
|
||||
@@ -1,124 +0,0 @@
|
||||
"""this uses new tech
|
||||
make by conda new -p path python=3.12; conda activate -p path; conda install all those shi
|
||||
|
||||
conda install pytorch torchvision torchaudio pytorch-cuda -c pytorch -c nvidia
|
||||
"""
|
||||
|
||||
import sys
|
||||
|
||||
sys.path.append(".")
|
||||
from load_data import load_this_data
|
||||
import torch
|
||||
|
||||
# a = load_this_data("dataset.csv")
|
||||
|
||||
x = torch.tensor([[1, 2], [3, 4]])
|
||||
print(x)
|
||||
|
||||
|
||||
print(x.shape) # Output: torch.Size([2, 2])
|
||||
print(x.dtype) # Output: torch.int64
|
||||
print(x.device) # Output: cpu
|
||||
|
||||
y = torch.ones_like(x)
|
||||
print(x + y)
|
||||
print(x * y)
|
||||
|
||||
|
||||
x = torch.randn(3, requires_grad=True)
|
||||
y = x * 2
|
||||
z = y.mean()
|
||||
z.backward()
|
||||
print(x.grad)
|
||||
|
||||
import torch.nn as nn
|
||||
|
||||
class SimpleNet(nn.Module):
|
||||
def __init__(self):
|
||||
super(SimpleNet, self).__init__()
|
||||
self.fc = nn.Linear(2, 1)
|
||||
|
||||
def forward(self, x):
|
||||
return self.fc(x)
|
||||
|
||||
|
||||
model = SimpleNet()
|
||||
sample_input = torch.tensor([[1.0, 2.0]])
|
||||
output = model(sample_input)
|
||||
print(output)
|
||||
|
||||
import torch.optim as optim
|
||||
|
||||
criterion = nn.MSELoss()
|
||||
optimizer = optim.SGD(model.parameters(), lr=0.01)
|
||||
|
||||
for epoch in range(100):
|
||||
optimizer.zero_grad()
|
||||
outputs = model(sample_input)
|
||||
loss = criterion(outputs, torch.tensor([[1.0]]))
|
||||
loss.backward()
|
||||
optimizer.step()
|
||||
if (epoch+1) % 10 == 0:
|
||||
print(f'Epoch [{epoch+1}/100], Loss: {loss.item():.4f}')
|
||||
|
||||
model.eval()
|
||||
|
||||
sample_input_2 = torch.tensor([[1.0, 2.0], [3.0, 4.0]])
|
||||
output_2 = model(sample_input_2)
|
||||
print(output_2)
|
||||
|
||||
|
||||
from torchvision import datasets, transforms
|
||||
from torch.utils.data import DataLoader
|
||||
|
||||
# Define a transform to normalize the data
|
||||
transform = transforms.Compose([transforms.ToTensor()])
|
||||
|
||||
# Download and load the training data
|
||||
train_dataset = datasets.MNIST(root='data', train=True, download=True, transform=transform)
|
||||
train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)
|
||||
|
||||
|
||||
# import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
class Net(nn.Module):
|
||||
def __init__(self):
|
||||
super(Net, self).__init__()
|
||||
self.fc1 = nn.Linear(28 * 28, 128)
|
||||
self.fc2 = nn.Linear(128, 10)
|
||||
|
||||
def forward(self, x):
|
||||
x = x.view(-1, 28 * 28) # Flatten the input
|
||||
x = F.relu(self.fc1(x))
|
||||
x = self.fc2(x)
|
||||
return x
|
||||
|
||||
model_2 = Net()
|
||||
criterion_2 = nn.CrossEntropyLoss()
|
||||
optimizer_2 = torch.optim.SGD(model.parameters(), lr=0.01)
|
||||
|
||||
|
||||
for epoch in range(35): # loop over the dataset multiple times
|
||||
for inputs, labels in train_loader:
|
||||
optimizer_2.zero_grad() # zero the parameter gradients
|
||||
outputs = model_2(inputs) # forward
|
||||
loss = criterion_2(outputs, labels) # compute loss
|
||||
loss.backward() # backward
|
||||
optimizer_2.step() # optimize
|
||||
print(f'Epoch {epoch+1}, Loss: {loss.item()}')
|
||||
|
||||
|
||||
test_dataset = datasets.MNIST(root='data', train=False, download=True, transform=transform)
|
||||
test_loader = DataLoader(test_dataset, batch_size=64, shuffle=False)
|
||||
|
||||
|
||||
correct = 0
|
||||
total = 0
|
||||
with torch.no_grad():
|
||||
for inputs, labels in test_loader:
|
||||
outputs = model_2(inputs)
|
||||
_, predicted = torch.max(outputs.data, 1)
|
||||
total += labels.size(0)
|
||||
correct += (predicted == labels).sum().item()
|
||||
print(f'Accuracy: {100 * correct / total}%')
|
||||
Reference in new issue
Block a user