mirror of
https://github.com/aladdinpersson/Machine-Learning-Collection.git
synced 2026-02-20 13:50:41 +00:00
add lightning code, finetuning whisper, recommender system neural collaborative filtering
This commit is contained in:
110
ML/Pytorch/pytorch_lightning/1. start code/simple_fc.py
Normal file
110
ML/Pytorch/pytorch_lightning/1. start code/simple_fc.py
Normal file
@@ -0,0 +1,110 @@
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
import torchvision.datasets as datasets
|
||||
import torchvision.transforms as transforms
|
||||
from torch import nn, optim
|
||||
from torch.utils.data import DataLoader
|
||||
from tqdm import tqdm
|
||||
from torch.utils.data import random_split
|
||||
|
||||
|
||||
class NN(nn.Module):
|
||||
def __init__(self, input_size, num_classes):
|
||||
super().__init__()
|
||||
self.fc1 = nn.Linear(input_size, 50)
|
||||
self.fc2 = nn.Linear(50, num_classes)
|
||||
|
||||
def forward(self, x):
|
||||
x = F.relu(self.fc1(x))
|
||||
x = self.fc2(x)
|
||||
return x
|
||||
|
||||
|
||||
# Set device cuda for GPU if it's available otherwise run on the CPU
|
||||
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
|
||||
# Hyperparameters
|
||||
input_size = 784
|
||||
num_classes = 10
|
||||
learning_rate = 0.001
|
||||
batch_size = 64
|
||||
num_epochs = 3
|
||||
|
||||
# Load Data
|
||||
entire_dataset = datasets.MNIST(
|
||||
root="dataset/", train=True, transform=transforms.ToTensor(), download=True
|
||||
)
|
||||
train_ds, val_ds = random_split(entire_dataset, [50000, 10000])
|
||||
test_ds = datasets.MNIST(
|
||||
root="dataset/", train=False, transform=transforms.ToTensor(), download=True
|
||||
)
|
||||
train_loader = DataLoader(dataset=train_ds, batch_size=batch_size, shuffle=True)
|
||||
val_loader = DataLoader(dataset=train_ds, batch_size=batch_size, shuffle=True)
|
||||
test_loader = DataLoader(dataset=test_ds, batch_size=batch_size, shuffle=False)
|
||||
|
||||
# Initialize network
|
||||
model = NN(input_size=input_size, num_classes=num_classes).to(device)
|
||||
|
||||
# Loss and optimizer
|
||||
criterion = nn.CrossEntropyLoss()
|
||||
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
|
||||
|
||||
# Train Network
|
||||
for epoch in range(num_epochs):
|
||||
for batch_idx, (data, targets) in enumerate(tqdm(train_loader)):
|
||||
# Get data to cuda if possible
|
||||
data = data.to(device=device)
|
||||
targets = targets.to(device=device)
|
||||
|
||||
# Get to correct shape
|
||||
data = data.reshape(data.shape[0], -1)
|
||||
|
||||
# Forward
|
||||
scores = model(data)
|
||||
loss = criterion(scores, targets)
|
||||
|
||||
# Backward
|
||||
optimizer.zero_grad()
|
||||
loss.backward()
|
||||
|
||||
# Gradient descent or adam step
|
||||
optimizer.step()
|
||||
|
||||
|
||||
# Check accuracy on training & test to see how good our model
|
||||
def check_accuracy(loader, model):
|
||||
num_correct = 0
|
||||
num_samples = 0
|
||||
model.eval()
|
||||
|
||||
# We don't need to keep track of gradients here so we wrap it in torch.no_grad()
|
||||
with torch.no_grad():
|
||||
# Loop through the data
|
||||
for x, y in loader:
|
||||
|
||||
# Move data to device
|
||||
x = x.to(device=device)
|
||||
y = y.to(device=device)
|
||||
|
||||
# Get to correct shape
|
||||
x = x.reshape(x.shape[0], -1)
|
||||
|
||||
# Forward pass
|
||||
scores = model(x)
|
||||
_, predictions = scores.max(1)
|
||||
|
||||
# Check how many we got correct
|
||||
num_correct += (predictions == y).sum()
|
||||
|
||||
# Keep track of number of samples
|
||||
num_samples += predictions.size(0)
|
||||
|
||||
model.train()
|
||||
return num_correct / num_samples
|
||||
|
||||
|
||||
# Check accuracy on training & test to see how good our model
|
||||
model.to(device)
|
||||
print(f"Accuracy on training set: {check_accuracy(train_loader, model)*100:.2f}")
|
||||
print(f"Accuracy on validation set: {check_accuracy(val_loader, model)*100:.2f}")
|
||||
print(f"Accuracy on test set: {check_accuracy(test_loader, model)*100:.2f}")
|
||||
12
ML/Pytorch/pytorch_lightning/10. Multi-GPU/callbacks.py
Normal file
12
ML/Pytorch/pytorch_lightning/10. Multi-GPU/callbacks.py
Normal file
@@ -0,0 +1,12 @@
|
||||
from pytorch_lightning.callbacks import EarlyStopping, Callback
|
||||
|
||||
class MyPrintingCallback(Callback):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
def on_train_start(self, trainer, pl_module):
|
||||
print("Starting to train!")
|
||||
|
||||
def on_train_end(self, trainer, pl_module):
|
||||
print("Training is done.")
|
||||
|
||||
15
ML/Pytorch/pytorch_lightning/10. Multi-GPU/config.py
Normal file
15
ML/Pytorch/pytorch_lightning/10. Multi-GPU/config.py
Normal file
@@ -0,0 +1,15 @@
|
||||
# Training hyperparameters
|
||||
INPUT_SIZE = 784
|
||||
NUM_CLASSES = 10
|
||||
LEARNING_RATE = 0.001
|
||||
BATCH_SIZE = 64
|
||||
NUM_EPOCHS = 3
|
||||
|
||||
# Dataset
|
||||
DATA_DIR = "dataset/"
|
||||
NUM_WORKERS = 4
|
||||
|
||||
# Compute related
|
||||
ACCELERATOR = "gpu"
|
||||
DEVICES = [0, 1]
|
||||
PRECISION = 16
|
||||
64
ML/Pytorch/pytorch_lightning/10. Multi-GPU/dataset.py
Normal file
64
ML/Pytorch/pytorch_lightning/10. Multi-GPU/dataset.py
Normal file
@@ -0,0 +1,64 @@
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
import torchvision.datasets as datasets
|
||||
import torchvision.transforms as transforms
|
||||
from torch import nn, optim
|
||||
from torch.utils.data import DataLoader
|
||||
from torch.utils.data import random_split
|
||||
import pytorch_lightning as pl
|
||||
from torchvision.transforms import RandomHorizontalFlip, RandomVerticalFlip
|
||||
|
||||
|
||||
class MnistDataModule(pl.LightningDataModule):
|
||||
def __init__(self, data_dir, batch_size, num_workers):
|
||||
super().__init__()
|
||||
self.data_dir = data_dir
|
||||
self.batch_size = batch_size
|
||||
self.num_workers = num_workers
|
||||
|
||||
def prepare_data(self):
|
||||
datasets.MNIST(self.data_dir, train=True, download=True)
|
||||
datasets.MNIST(self.data_dir, train=False, download=True)
|
||||
|
||||
def setup(self, stage):
|
||||
entire_dataset = datasets.MNIST(
|
||||
root=self.data_dir,
|
||||
train=True,
|
||||
transform=transforms.Compose([
|
||||
transforms.RandomVerticalFlip(),
|
||||
transforms.RandomHorizontalFlip(),
|
||||
transforms.ToTensor(),
|
||||
]),
|
||||
download=False,
|
||||
)
|
||||
self.train_ds, self.val_ds = random_split(entire_dataset, [50000, 10000])
|
||||
self.test_ds = datasets.MNIST(
|
||||
root=self.data_dir,
|
||||
train=False,
|
||||
transform=transforms.ToTensor(),
|
||||
download=False,
|
||||
)
|
||||
|
||||
def train_dataloader(self):
|
||||
return DataLoader(
|
||||
self.train_ds,
|
||||
batch_size=self.batch_size,
|
||||
num_workers=self.num_workers,
|
||||
shuffle=True,
|
||||
)
|
||||
|
||||
def val_dataloader(self):
|
||||
return DataLoader(
|
||||
self.val_ds,
|
||||
batch_size=self.batch_size,
|
||||
num_workers=self.num_workers,
|
||||
shuffle=False,
|
||||
)
|
||||
|
||||
def test_dataloader(self):
|
||||
return DataLoader(
|
||||
self.test_ds,
|
||||
batch_size=self.batch_size,
|
||||
num_workers=self.num_workers,
|
||||
shuffle=False,
|
||||
)
|
||||
89
ML/Pytorch/pytorch_lightning/10. Multi-GPU/model.py
Normal file
89
ML/Pytorch/pytorch_lightning/10. Multi-GPU/model.py
Normal file
@@ -0,0 +1,89 @@
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
import torchvision.datasets as datasets
|
||||
import torchvision.transforms as transforms
|
||||
from torch import nn, optim
|
||||
from torch.utils.data import DataLoader
|
||||
from tqdm import tqdm
|
||||
import pytorch_lightning as pl
|
||||
import torchmetrics
|
||||
from torchmetrics import Metric
|
||||
import torchvision
|
||||
|
||||
|
||||
class NN(pl.LightningModule):
|
||||
def __init__(self, input_size, learning_rate, num_classes):
|
||||
super().__init__()
|
||||
self.lr = learning_rate
|
||||
self.fc1 = nn.Linear(input_size, 1_000_000)
|
||||
self.fc2 = nn.Linear(1_000_000, num_classes)
|
||||
self.loss_fn = nn.CrossEntropyLoss()
|
||||
self.accuracy = torchmetrics.Accuracy(
|
||||
task="multiclass", num_classes=num_classes
|
||||
)
|
||||
self.f1_score = torchmetrics.F1Score(task="multiclass", num_classes=num_classes)
|
||||
|
||||
def forward(self, x):
|
||||
x = F.relu(self.fc1(x))
|
||||
x = self.fc2(x)
|
||||
return x
|
||||
|
||||
def training_step(self, batch, batch_idx):
|
||||
x, y = batch
|
||||
loss, scores, y = self._common_step(batch, batch_idx)
|
||||
|
||||
self.log_dict(
|
||||
{
|
||||
"train_loss": loss,
|
||||
},
|
||||
on_step=False,
|
||||
on_epoch=True,
|
||||
prog_bar=True,
|
||||
)
|
||||
|
||||
if batch_idx % 100 == 0:
|
||||
x = x[:8]
|
||||
grid = torchvision.utils.make_grid(x.view(-1, 1, 28, 28))
|
||||
self.logger.experiment.add_image("mnist_images", grid, self.global_step)
|
||||
|
||||
return {"loss": loss, "scores": scores, "y": y}
|
||||
|
||||
def training_epoch_end(self, outputs):
|
||||
scores = torch.cat([x["scores"] for x in outputs])
|
||||
y = torch.cat([x["y"] for x in outputs])
|
||||
self.log_dict(
|
||||
{
|
||||
"train_acc": self.accuracy(scores, y),
|
||||
"train_f1": self.f1_score(scores, y),
|
||||
},
|
||||
on_step=False,
|
||||
on_epoch=True,
|
||||
prog_bar=True,
|
||||
)
|
||||
|
||||
def validation_step(self, batch, batch_idx):
|
||||
loss, scores, y = self._common_step(batch, batch_idx)
|
||||
self.log("val_loss", loss)
|
||||
return loss
|
||||
|
||||
def test_step(self, batch, batch_idx):
|
||||
loss, scores, y = self._common_step(batch, batch_idx)
|
||||
self.log("test_loss", loss)
|
||||
return loss
|
||||
|
||||
def _common_step(self, batch, batch_idx):
|
||||
x, y = batch
|
||||
x = x.reshape(x.size(0), -1)
|
||||
scores = self.forward(x)
|
||||
loss = self.loss_fn(scores, y)
|
||||
return loss, scores, y
|
||||
|
||||
def predict_step(self, batch, batch_idx):
|
||||
x, y = batch
|
||||
x = x.reshape(x.size(0), -1)
|
||||
scores = self.forward(x)
|
||||
preds = torch.argmax(scores, dim=1)
|
||||
return preds
|
||||
|
||||
def configure_optimizers(self):
|
||||
return optim.Adam(self.parameters(), lr=self.lr)
|
||||
43
ML/Pytorch/pytorch_lightning/10. Multi-GPU/train.py
Normal file
43
ML/Pytorch/pytorch_lightning/10. Multi-GPU/train.py
Normal file
@@ -0,0 +1,43 @@
|
||||
import torch
|
||||
import pytorch_lightning as pl
|
||||
from model import NN
|
||||
from dataset import MnistDataModule
|
||||
import config
|
||||
from callbacks import MyPrintingCallback, EarlyStopping
|
||||
from pytorch_lightning.loggers import TensorBoardLogger
|
||||
from pytorch_lightning.profilers import PyTorchProfiler
|
||||
from pytorch_lightning.strategies import DeepSpeedStrategy
|
||||
|
||||
torch.set_float32_matmul_precision("medium") # to make lightning happy
|
||||
|
||||
if __name__ == "__main__":
|
||||
logger = TensorBoardLogger("tb_logs", name="mnist_model_v1")
|
||||
strategy = DeepSpeedStrategy()
|
||||
profiler = PyTorchProfiler(
|
||||
on_trace_ready=torch.profiler.tensorboard_trace_handler("tb_logs/profiler0"),
|
||||
schedule=torch.profiler.schedule(skip_first=10, wait=1, warmup=1, active=20),
|
||||
)
|
||||
model = NN(
|
||||
input_size=config.INPUT_SIZE,
|
||||
learning_rate=config.LEARNING_RATE,
|
||||
num_classes=config.NUM_CLASSES,
|
||||
)
|
||||
dm = MnistDataModule(
|
||||
data_dir=config.DATA_DIR,
|
||||
batch_size=config.BATCH_SIZE,
|
||||
num_workers=config.NUM_WORKERS,
|
||||
)
|
||||
trainer = pl.Trainer(
|
||||
strategy=strategy,
|
||||
profiler=profiler,
|
||||
logger=logger,
|
||||
accelerator=config.ACCELERATOR,
|
||||
devices=config.DEVICES,
|
||||
min_epochs=1,
|
||||
max_epochs=config.NUM_EPOCHS,
|
||||
precision=config.PRECISION,
|
||||
callbacks=[MyPrintingCallback(), EarlyStopping(monitor="val_loss")],
|
||||
)
|
||||
trainer.fit(model, dm)
|
||||
trainer.validate(model, dm)
|
||||
trainer.test(model, dm)
|
||||
154
ML/Pytorch/pytorch_lightning/2. LightningModule/simple_fc.py
Normal file
154
ML/Pytorch/pytorch_lightning/2. LightningModule/simple_fc.py
Normal file
@@ -0,0 +1,154 @@
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
import torchvision.datasets as datasets
|
||||
import torchvision.transforms as transforms
|
||||
from torch import nn, optim
|
||||
from torch.utils.data import DataLoader
|
||||
from tqdm import tqdm
|
||||
from torch.utils.data import random_split
|
||||
import pytorch_lightning as pl
|
||||
|
||||
class NN(nn.Module):
|
||||
def __init__(self, input_size, num_classes):
|
||||
super().__init__()
|
||||
self.fc1 = nn.Linear(input_size, 50)
|
||||
self.fc2 = nn.Linear(50, num_classes)
|
||||
|
||||
def forward(self, x):
|
||||
x = F.relu(self.fc1(x))
|
||||
x = self.fc2(x)
|
||||
return x
|
||||
|
||||
class NN(pl.LightningModule):
|
||||
def __init__(self, input_size, num_classes):
|
||||
super().__init__()
|
||||
self.fc1 = nn.Linear(input_size, 50)
|
||||
self.fc2 = nn.Linear(50, num_classes)
|
||||
self.loss_fn = nn.CrossEntropyLoss()
|
||||
|
||||
def forward(self, x):
|
||||
x = F.relu(self.fc1(x))
|
||||
x = self.fc2(x)
|
||||
return x
|
||||
|
||||
def training_step(self, batch, batch_idx):
|
||||
loss, scores, y = self._common_step(batch, batch_idx)
|
||||
self.log('train_loss', loss)
|
||||
return loss
|
||||
|
||||
def validation_step(self, batch, batch_idx):
|
||||
loss, scores, y = self._common_step(batch, batch_idx)
|
||||
self.log('val_loss', loss)
|
||||
return loss
|
||||
|
||||
def test_step(self, batch, batch_idx):
|
||||
loss, scores, y = self._common_step(batch, batch_idx)
|
||||
self.log('test_loss', loss)
|
||||
return loss
|
||||
|
||||
def _common_step(self, batch, batch_idx):
|
||||
x, y = batch
|
||||
x = x.reshape(x.size(0), -1)
|
||||
scores = self.forward(x)
|
||||
loss = self.loss_fn(scores, y)
|
||||
return loss, scores, y
|
||||
|
||||
def predict_step(self, batch, batch_idx):
|
||||
x, y = batch
|
||||
x = x.reshape(x.size(0), -1)
|
||||
scores = self.forward(x)
|
||||
preds = torch.argmax(scores, dim=1)
|
||||
return preds
|
||||
|
||||
def configure_optimizers(self):
|
||||
return optim.Adam(self.parameters(), lr=0.001)
|
||||
|
||||
# Set device cuda for GPU if it's available otherwise run on the CPU
|
||||
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
|
||||
# Hyperparameters
|
||||
|
||||
input_size = 784
|
||||
num_classes = 10
|
||||
learning_rate = 0.001
|
||||
batch_size = 64
|
||||
num_epochs = 3
|
||||
|
||||
# Load Data
|
||||
entire_dataset = datasets.MNIST(
|
||||
root="dataset/", train=True, transform=transforms.ToTensor(), download=True
|
||||
)
|
||||
train_ds, val_ds = random_split(entire_dataset, [50000, 10000])
|
||||
test_ds = datasets.MNIST(
|
||||
root="dataset/", train=False, transform=transforms.ToTensor(), download=True
|
||||
)
|
||||
train_loader = DataLoader(dataset=train_ds, batch_size=batch_size, shuffle=True)
|
||||
val_loader = DataLoader(dataset=train_ds, batch_size=batch_size, shuffle=True)
|
||||
test_loader = DataLoader(dataset=test_ds, batch_size=batch_size, shuffle=False)
|
||||
|
||||
# Initialize network
|
||||
model = NN(input_size=input_size, num_classes=num_classes).to(device)
|
||||
|
||||
# Loss and optimizer
|
||||
criterion = nn.CrossEntropyLoss()
|
||||
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
|
||||
|
||||
# Train Network
|
||||
for epoch in range(num_epochs):
|
||||
for batch_idx, (data, targets) in enumerate(tqdm(train_loader)):
|
||||
# Get data to cuda if possible
|
||||
data = data.to(device=device)
|
||||
targets = targets.to(device=device)
|
||||
|
||||
# Get to correct shape
|
||||
data = data.reshape(data.shape[0], -1)
|
||||
|
||||
# Forward
|
||||
scores = model(data)
|
||||
loss = criterion(scores, targets)
|
||||
|
||||
# Backward
|
||||
optimizer.zero_grad()
|
||||
loss.backward()
|
||||
|
||||
# Gradient descent or adam step
|
||||
optimizer.step()
|
||||
|
||||
|
||||
# Check accuracy on training & test to see how good our model
|
||||
def check_accuracy(loader, model):
|
||||
num_correct = 0
|
||||
num_samples = 0
|
||||
model.eval()
|
||||
|
||||
# We don't need to keep track of gradients here so we wrap it in torch.no_grad()
|
||||
with torch.no_grad():
|
||||
# Loop through the data
|
||||
for x, y in loader:
|
||||
|
||||
# Move data to device
|
||||
x = x.to(device=device)
|
||||
y = y.to(device=device)
|
||||
|
||||
# Get to correct shape
|
||||
x = x.reshape(x.shape[0], -1)
|
||||
|
||||
# Forward pass
|
||||
scores = model(x)
|
||||
_, predictions = scores.max(1)
|
||||
|
||||
# Check how many we got correct
|
||||
num_correct += (predictions == y).sum()
|
||||
|
||||
# Keep track of number of samples
|
||||
num_samples += predictions.size(0)
|
||||
|
||||
model.train()
|
||||
return num_correct / num_samples
|
||||
|
||||
|
||||
# Check accuracy on training & test to see how good our model
|
||||
model.to(device)
|
||||
print(f"Accuracy on training set: {check_accuracy(train_loader, model)*100:.2f}")
|
||||
print(f"Accuracy on validation set: {check_accuracy(val_loader, model)*100:.2f}")
|
||||
print(f"Accuracy on test set: {check_accuracy(test_loader, model)*100:.2f}")
|
||||
126
ML/Pytorch/pytorch_lightning/3. Lightning Trainer/simple_fc.py
Normal file
126
ML/Pytorch/pytorch_lightning/3. Lightning Trainer/simple_fc.py
Normal file
@@ -0,0 +1,126 @@
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
import torchvision.datasets as datasets
|
||||
import torchvision.transforms as transforms
|
||||
from torch import nn, optim
|
||||
from torch.utils.data import DataLoader
|
||||
from tqdm import tqdm
|
||||
from torch.utils.data import random_split
|
||||
import pytorch_lightning as pl
|
||||
|
||||
|
||||
class NN(pl.LightningModule):
|
||||
def __init__(self, input_size, num_classes):
|
||||
super().__init__()
|
||||
self.fc1 = nn.Linear(input_size, 50)
|
||||
self.fc2 = nn.Linear(50, num_classes)
|
||||
self.loss_fn = nn.CrossEntropyLoss()
|
||||
|
||||
def forward(self, x):
|
||||
x = F.relu(self.fc1(x))
|
||||
x = self.fc2(x)
|
||||
return x
|
||||
|
||||
def training_step(self, batch, batch_idx):
|
||||
loss, scores, y = self._common_step(batch, batch_idx)
|
||||
self.log('train_loss', loss)
|
||||
return loss
|
||||
|
||||
def validation_step(self, batch, batch_idx):
|
||||
loss, scores, y = self._common_step(batch, batch_idx)
|
||||
self.log('val_loss', loss)
|
||||
return loss
|
||||
|
||||
def test_step(self, batch, batch_idx):
|
||||
loss, scores, y = self._common_step(batch, batch_idx)
|
||||
self.log('test_loss', loss)
|
||||
return loss
|
||||
|
||||
def _common_step(self, batch, batch_idx):
|
||||
x, y = batch
|
||||
x = x.reshape(x.size(0), -1)
|
||||
scores = self.forward(x)
|
||||
loss = self.loss_fn(scores, y)
|
||||
return loss, scores, y
|
||||
|
||||
def predict_step(self, batch, batch_idx):
|
||||
x, y = batch
|
||||
x = x.reshape(x.size(0), -1)
|
||||
scores = self.forward(x)
|
||||
preds = torch.argmax(scores, dim=1)
|
||||
return preds
|
||||
|
||||
def configure_optimizers(self):
|
||||
return optim.Adam(self.parameters(), lr=0.001)
|
||||
|
||||
# Set device cuda for GPU if it's available otherwise run on the CPU
|
||||
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
|
||||
# Hyperparameters
|
||||
input_size = 784
|
||||
num_classes = 10
|
||||
learning_rate = 0.001
|
||||
batch_size = 64
|
||||
num_epochs = 3
|
||||
|
||||
# Load Data
|
||||
entire_dataset = datasets.MNIST(
|
||||
root="dataset/", train=True, transform=transforms.ToTensor(), download=True
|
||||
)
|
||||
train_ds, val_ds = random_split(entire_dataset, [50000, 10000])
|
||||
test_ds = datasets.MNIST(
|
||||
root="dataset/", train=False, transform=transforms.ToTensor(), download=True
|
||||
)
|
||||
train_loader = DataLoader(dataset=train_ds, batch_size=batch_size, shuffle=True)
|
||||
val_loader = DataLoader(dataset=val_ds, batch_size=batch_size, shuffle=False)
|
||||
test_loader = DataLoader(dataset=test_ds, batch_size=batch_size, shuffle=False)
|
||||
|
||||
# Initialize network
|
||||
model = NN(input_size=input_size, num_classes=num_classes).to(device)
|
||||
|
||||
# Loss and optimizer
|
||||
criterion = nn.CrossEntropyLoss()
|
||||
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
|
||||
|
||||
trainer = pl.Trainer(accelerator="gpu", devices=1, min_epochs=1, max_epochs=3, precision=16)
|
||||
trainer.fit(model, train_loader, val_loader)
|
||||
trainer.validate(model, val_loader)
|
||||
trainer.test(model, test_loader)
|
||||
|
||||
# Check accuracy on training & test to see how good our model
|
||||
def check_accuracy(loader, model):
|
||||
num_correct = 0
|
||||
num_samples = 0
|
||||
model.eval()
|
||||
|
||||
# We don't need to keep track of gradients here so we wrap it in torch.no_grad()
|
||||
with torch.no_grad():
|
||||
# Loop through the data
|
||||
for x, y in loader:
|
||||
|
||||
# Move data to device
|
||||
x = x.to(device=device)
|
||||
y = y.to(device=device)
|
||||
|
||||
# Get to correct shape
|
||||
x = x.reshape(x.shape[0], -1)
|
||||
|
||||
# Forward pass
|
||||
scores = model(x)
|
||||
_, predictions = scores.max(1)
|
||||
|
||||
# Check how many we got correct
|
||||
num_correct += (predictions == y).sum()
|
||||
|
||||
# Keep track of number of samples
|
||||
num_samples += predictions.size(0)
|
||||
|
||||
model.train()
|
||||
return num_correct / num_samples
|
||||
|
||||
|
||||
# Check accuracy on training & test to see how good our model
|
||||
model.to(device)
|
||||
print(f"Accuracy on training set: {check_accuracy(train_loader, model)*100:.2f}")
|
||||
print(f"Accuracy on validation set: {check_accuracy(val_loader, model)*100:.2f}")
|
||||
print(f"Accuracy on test set: {check_accuracy(test_loader, model)*100:.2f}")
|
||||
150
ML/Pytorch/pytorch_lightning/4. Metrics/simple_fc.py
Normal file
150
ML/Pytorch/pytorch_lightning/4. Metrics/simple_fc.py
Normal file
@@ -0,0 +1,150 @@
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
import torchvision.datasets as datasets
|
||||
import torchvision.transforms as transforms
|
||||
from torch import nn, optim
|
||||
from torch.utils.data import DataLoader
|
||||
from tqdm import tqdm
|
||||
from torch.utils.data import random_split
|
||||
import pytorch_lightning as pl
|
||||
import torchmetrics
|
||||
from torchmetrics import Metric
|
||||
|
||||
|
||||
class MyAccuracy(Metric):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.add_state("total", default=torch.tensor(0), dist_reduce_fx="sum")
|
||||
self.add_state("correct", default=torch.tensor(0), dist_reduce_fx="sum")
|
||||
|
||||
def update(self, preds, target):
|
||||
preds = torch.argmax(preds, dim=1)
|
||||
assert preds.shape == target.shape
|
||||
self.correct += torch.sum(preds == target)
|
||||
self.total += target.numel()
|
||||
|
||||
def compute(self):
|
||||
return self.correct.float() / self.total.float()
|
||||
|
||||
|
||||
class NN(pl.LightningModule):
|
||||
def __init__(self, input_size, num_classes):
|
||||
super().__init__()
|
||||
self.fc1 = nn.Linear(input_size, 50)
|
||||
self.fc2 = nn.Linear(50, num_classes)
|
||||
self.loss_fn = nn.CrossEntropyLoss()
|
||||
self.accuracy = torchmetrics.Accuracy(task="multiclass", num_classes=num_classes)
|
||||
self.my_accuracy = MyAccuracy()
|
||||
self.f1_score = torchmetrics.F1Score(task="multiclass", num_classes=num_classes)
|
||||
|
||||
def forward(self, x):
|
||||
x = F.relu(self.fc1(x))
|
||||
x = self.fc2(x)
|
||||
return x
|
||||
|
||||
def training_step(self, batch, batch_idx):
|
||||
loss, scores, y = self._common_step(batch, batch_idx)
|
||||
accuracy = self.my_accuracy(scores, y)
|
||||
f1_score = self.f1_score(scores, y)
|
||||
self.log_dict({'train_loss': loss, 'train_accuracy': accuracy, 'train_f1_score': f1_score},
|
||||
on_step=False, on_epoch=True, prog_bar=True)
|
||||
return {'loss': loss, "scores": scores, "y": y}
|
||||
|
||||
def validation_step(self, batch, batch_idx):
|
||||
loss, scores, y = self._common_step(batch, batch_idx)
|
||||
self.log('val_loss', loss)
|
||||
return loss
|
||||
|
||||
def test_step(self, batch, batch_idx):
|
||||
loss, scores, y = self._common_step(batch, batch_idx)
|
||||
self.log('test_loss', loss)
|
||||
return loss
|
||||
|
||||
def _common_step(self, batch, batch_idx):
|
||||
x, y = batch
|
||||
x = x.reshape(x.size(0), -1)
|
||||
scores = self.forward(x)
|
||||
loss = self.loss_fn(scores, y)
|
||||
return loss, scores, y
|
||||
|
||||
def predict_step(self, batch, batch_idx):
|
||||
x, y = batch
|
||||
x = x.reshape(x.size(0), -1)
|
||||
scores = self.forward(x)
|
||||
preds = torch.argmax(scores, dim=1)
|
||||
return preds
|
||||
|
||||
def configure_optimizers(self):
|
||||
return optim.Adam(self.parameters(), lr=0.001)
|
||||
|
||||
# Set device cuda for GPU if it's available otherwise run on the CPU
|
||||
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
|
||||
# Hyperparameters
|
||||
input_size = 784
|
||||
num_classes = 10
|
||||
learning_rate = 0.001
|
||||
batch_size = 64
|
||||
num_epochs = 3
|
||||
|
||||
# Load Data
|
||||
entire_dataset = datasets.MNIST(
|
||||
root="dataset/", train=True, transform=transforms.ToTensor(), download=True
|
||||
)
|
||||
train_ds, val_ds = random_split(entire_dataset, [50000, 10000])
|
||||
test_ds = datasets.MNIST(
|
||||
root="dataset/", train=False, transform=transforms.ToTensor(), download=True
|
||||
)
|
||||
train_loader = DataLoader(dataset=train_ds, batch_size=batch_size, shuffle=True)
|
||||
val_loader = DataLoader(dataset=val_ds, batch_size=batch_size, shuffle=False)
|
||||
test_loader = DataLoader(dataset=test_ds, batch_size=batch_size, shuffle=False)
|
||||
|
||||
# Initialize network
|
||||
model = NN(input_size=input_size, num_classes=num_classes).to(device)
|
||||
|
||||
# Loss and optimizer
|
||||
criterion = nn.CrossEntropyLoss()
|
||||
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
|
||||
|
||||
trainer = pl.Trainer(accelerator="gpu", devices=1, min_epochs=1, max_epochs=3, precision=16)
|
||||
trainer.fit(model, train_loader, val_loader)
|
||||
trainer.validate(model, val_loader)
|
||||
trainer.test(model, test_loader)
|
||||
|
||||
# Check accuracy on training & test to see how good our model
|
||||
def check_accuracy(loader, model):
|
||||
num_correct = 0
|
||||
num_samples = 0
|
||||
model.eval()
|
||||
|
||||
# We don't need to keep track of gradients here so we wrap it in torch.no_grad()
|
||||
with torch.no_grad():
|
||||
# Loop through the data
|
||||
for x, y in loader:
|
||||
|
||||
# Move data to device
|
||||
x = x.to(device=device)
|
||||
y = y.to(device=device)
|
||||
|
||||
# Get to correct shape
|
||||
x = x.reshape(x.shape[0], -1)
|
||||
|
||||
# Forward pass
|
||||
scores = model(x)
|
||||
_, predictions = scores.max(1)
|
||||
|
||||
# Check how many we got correct
|
||||
num_correct += (predictions == y).sum()
|
||||
|
||||
# Keep track of number of samples
|
||||
num_samples += predictions.size(0)
|
||||
|
||||
model.train()
|
||||
return num_correct / num_samples
|
||||
|
||||
|
||||
# Check accuracy on training & test to see how good our model
|
||||
model.to(device)
|
||||
print(f"Accuracy on training set: {check_accuracy(train_loader, model)*100:.2f}")
|
||||
print(f"Accuracy on validation set: {check_accuracy(val_loader, model)*100:.2f}")
|
||||
print(f"Accuracy on test set: {check_accuracy(test_loader, model)*100:.2f}")
|
||||
146
ML/Pytorch/pytorch_lightning/5. DataModule/simple_fc.py
Normal file
146
ML/Pytorch/pytorch_lightning/5. DataModule/simple_fc.py
Normal file
@@ -0,0 +1,146 @@
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
import torchvision.datasets as datasets
|
||||
import torchvision.transforms as transforms
|
||||
from torch import nn, optim
|
||||
from torch.utils.data import DataLoader
|
||||
from tqdm import tqdm
|
||||
from torch.utils.data import random_split
|
||||
import pytorch_lightning as pl
|
||||
import torchmetrics
|
||||
from torchmetrics import Metric
|
||||
|
||||
|
||||
class MyAccuracy(Metric):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.add_state("total", default=torch.tensor(0), dist_reduce_fx="sum")
|
||||
self.add_state("correct", default=torch.tensor(0), dist_reduce_fx="sum")
|
||||
|
||||
def update(self, preds, target):
|
||||
preds = torch.argmax(preds, dim=1)
|
||||
assert preds.shape == target.shape
|
||||
self.correct += torch.sum(preds == target)
|
||||
self.total += target.numel()
|
||||
|
||||
def compute(self):
|
||||
return self.correct.float() / self.total.float()
|
||||
|
||||
|
||||
class NN(pl.LightningModule):
|
||||
def __init__(self, input_size, num_classes):
|
||||
super().__init__()
|
||||
self.fc1 = nn.Linear(input_size, 50)
|
||||
self.fc2 = nn.Linear(50, num_classes)
|
||||
self.loss_fn = nn.CrossEntropyLoss()
|
||||
self.accuracy = torchmetrics.Accuracy(task="multiclass", num_classes=num_classes)
|
||||
self.my_accuracy = MyAccuracy()
|
||||
self.f1_score = torchmetrics.F1Score(task="multiclass", num_classes=num_classes)
|
||||
|
||||
def forward(self, x):
|
||||
x = F.relu(self.fc1(x))
|
||||
x = self.fc2(x)
|
||||
return x
|
||||
|
||||
def training_step(self, batch, batch_idx):
|
||||
loss, scores, y = self._common_step(batch, batch_idx)
|
||||
accuracy = self.my_accuracy(scores, y)
|
||||
f1_score = self.f1_score(scores, y)
|
||||
self.log_dict({'train_loss': loss, 'train_accuracy': accuracy, 'train_f1_score': f1_score},
|
||||
on_step=False, on_epoch=True, prog_bar=True)
|
||||
return {'loss': loss, "scores": scores, "y": y}
|
||||
|
||||
def validation_step(self, batch, batch_idx):
|
||||
loss, scores, y = self._common_step(batch, batch_idx)
|
||||
self.log('val_loss', loss)
|
||||
return loss
|
||||
|
||||
def test_step(self, batch, batch_idx):
|
||||
loss, scores, y = self._common_step(batch, batch_idx)
|
||||
self.log('test_loss', loss)
|
||||
return loss
|
||||
|
||||
def _common_step(self, batch, batch_idx):
|
||||
x, y = batch
|
||||
x = x.reshape(x.size(0), -1)
|
||||
scores = self.forward(x)
|
||||
loss = self.loss_fn(scores, y)
|
||||
return loss, scores, y
|
||||
|
||||
def predict_step(self, batch, batch_idx):
|
||||
x, y = batch
|
||||
x = x.reshape(x.size(0), -1)
|
||||
scores = self.forward(x)
|
||||
preds = torch.argmax(scores, dim=1)
|
||||
return preds
|
||||
|
||||
def configure_optimizers(self):
|
||||
return optim.Adam(self.parameters(), lr=0.001)
|
||||
|
||||
|
||||
class MnistDataModule(pl.LightningDataModule):
|
||||
def __init__(self, data_dir, batch_size, num_workers):
|
||||
super().__init__()
|
||||
self.data_dir = data_dir
|
||||
self.batch_size = batch_size
|
||||
self.num_workers = num_workers
|
||||
|
||||
def prepare_data(self):
|
||||
datasets.MNIST(self.data_dir, train=True, download=True)
|
||||
datasets.MNIST(self.data_dir, train=False, download=True)
|
||||
|
||||
def setup(self, stage):
|
||||
entire_dataset = datasets.MNIST(
|
||||
root=self.data_dir,
|
||||
train=True,
|
||||
transform=transforms.ToTensor(),
|
||||
download=False,
|
||||
)
|
||||
self.train_ds, self.val_ds = random_split(entire_dataset, [50000, 10000])
|
||||
self.test_ds = datasets.MNIST(
|
||||
root=self.data_dir,
|
||||
train=False,
|
||||
transform=transforms.ToTensor(),
|
||||
download=False,
|
||||
)
|
||||
|
||||
def train_dataloader(self):
|
||||
return DataLoader(
|
||||
self.train_ds,
|
||||
batch_size=self.batch_size,
|
||||
num_workers=self.num_workers,
|
||||
shuffle=True,
|
||||
)
|
||||
|
||||
def val_dataloader(self):
|
||||
return DataLoader(
|
||||
self.val_ds,
|
||||
batch_size=self.batch_size,
|
||||
num_workers=self.num_workers,
|
||||
shuffle=False,
|
||||
)
|
||||
|
||||
def test_dataloader(self):
|
||||
return DataLoader(
|
||||
self.test_ds,
|
||||
batch_size=self.batch_size,
|
||||
num_workers=self.num_workers,
|
||||
shuffle=False,
|
||||
)
|
||||
|
||||
# Set device cuda for GPU if it's available otherwise run on the CPU
|
||||
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
|
||||
# Hyperparameters
|
||||
input_size = 784
|
||||
num_classes = 10
|
||||
learning_rate = 0.001
|
||||
batch_size = 64
|
||||
num_epochs = 3
|
||||
|
||||
model = NN(input_size=input_size, num_classes=num_classes)
|
||||
dm = MnistDataModule(data_dir="dataset/", batch_size=batch_size, num_workers=4)
|
||||
trainer = pl.Trainer(accelerator="gpu", devices=1, min_epochs=1, max_epochs=3, precision=16)
|
||||
trainer.fit(model, dm)
|
||||
trainer.validate(model, dm)
|
||||
trainer.test(model, dm)
|
||||
15
ML/Pytorch/pytorch_lightning/6. Restructuring/config.py
Normal file
15
ML/Pytorch/pytorch_lightning/6. Restructuring/config.py
Normal file
@@ -0,0 +1,15 @@
|
||||
# Training hyperparameters
|
||||
INPUT_SIZE = 784
|
||||
NUM_CLASSES = 10
|
||||
LEARNING_RATE = 0.001
|
||||
BATCH_SIZE = 64
|
||||
NUM_EPOCHS = 3
|
||||
|
||||
# Dataset
|
||||
DATA_DIR = "dataset/"
|
||||
NUM_WORKERS = 4
|
||||
|
||||
# Compute related
|
||||
ACCELERATOR = "gpu"
|
||||
DEVICES = [0]
|
||||
PRECISION = 16
|
||||
59
ML/Pytorch/pytorch_lightning/6. Restructuring/dataset.py
Normal file
59
ML/Pytorch/pytorch_lightning/6. Restructuring/dataset.py
Normal file
@@ -0,0 +1,59 @@
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
import torchvision.datasets as datasets
|
||||
import torchvision.transforms as transforms
|
||||
from torch import nn, optim
|
||||
from torch.utils.data import DataLoader
|
||||
from torch.utils.data import random_split
|
||||
import pytorch_lightning as pl
|
||||
|
||||
|
||||
class MnistDataModule(pl.LightningDataModule):
|
||||
def __init__(self, data_dir, batch_size, num_workers):
|
||||
super().__init__()
|
||||
self.data_dir = data_dir
|
||||
self.batch_size = batch_size
|
||||
self.num_workers = num_workers
|
||||
|
||||
def prepare_data(self):
|
||||
datasets.MNIST(self.data_dir, train=True, download=True)
|
||||
datasets.MNIST(self.data_dir, train=False, download=True)
|
||||
|
||||
def setup(self, stage):
|
||||
entire_dataset = datasets.MNIST(
|
||||
root=self.data_dir,
|
||||
train=True,
|
||||
transform=transforms.ToTensor(),
|
||||
download=False,
|
||||
)
|
||||
self.train_ds, self.val_ds = random_split(entire_dataset, [50000, 10000])
|
||||
self.test_ds = datasets.MNIST(
|
||||
root=self.data_dir,
|
||||
train=False,
|
||||
transform=transforms.ToTensor(),
|
||||
download=False,
|
||||
)
|
||||
|
||||
def train_dataloader(self):
|
||||
return DataLoader(
|
||||
self.train_ds,
|
||||
batch_size=self.batch_size,
|
||||
num_workers=self.num_workers,
|
||||
shuffle=True,
|
||||
)
|
||||
|
||||
def val_dataloader(self):
|
||||
return DataLoader(
|
||||
self.val_ds,
|
||||
batch_size=self.batch_size,
|
||||
num_workers=self.num_workers,
|
||||
shuffle=False,
|
||||
)
|
||||
|
||||
def test_dataloader(self):
|
||||
return DataLoader(
|
||||
self.test_ds,
|
||||
batch_size=self.batch_size,
|
||||
num_workers=self.num_workers,
|
||||
shuffle=False,
|
||||
)
|
||||
71
ML/Pytorch/pytorch_lightning/6. Restructuring/model.py
Normal file
71
ML/Pytorch/pytorch_lightning/6. Restructuring/model.py
Normal file
@@ -0,0 +1,71 @@
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
import torchvision.datasets as datasets
|
||||
import torchvision.transforms as transforms
|
||||
from torch import nn, optim
|
||||
from torch.utils.data import DataLoader
|
||||
from tqdm import tqdm
|
||||
import pytorch_lightning as pl
|
||||
import torchmetrics
|
||||
from torchmetrics import Metric
|
||||
|
||||
|
||||
class NN(pl.LightningModule):
|
||||
def __init__(self, input_size, learning_rate, num_classes):
|
||||
super().__init__()
|
||||
self.lr = learning_rate
|
||||
self.fc1 = nn.Linear(input_size, 50)
|
||||
self.fc2 = nn.Linear(50, num_classes)
|
||||
self.loss_fn = nn.CrossEntropyLoss()
|
||||
self.accuracy = torchmetrics.Accuracy(
|
||||
task="multiclass", num_classes=num_classes
|
||||
)
|
||||
self.f1_score = torchmetrics.F1Score(task="multiclass", num_classes=num_classes)
|
||||
|
||||
def forward(self, x):
|
||||
x = F.relu(self.fc1(x))
|
||||
x = self.fc2(x)
|
||||
return x
|
||||
|
||||
def training_step(self, batch, batch_idx):
|
||||
loss, scores, y = self._common_step(batch, batch_idx)
|
||||
accuracy = self.accuracy(scores, y)
|
||||
f1_score = self.f1_score(scores, y)
|
||||
self.log_dict(
|
||||
{
|
||||
"train_loss": loss,
|
||||
"train_accuracy": accuracy,
|
||||
"train_f1_score": f1_score,
|
||||
},
|
||||
on_step=False,
|
||||
on_epoch=True,
|
||||
prog_bar=True,
|
||||
)
|
||||
return {"loss": loss, "scores": scores, "y": y}
|
||||
|
||||
def validation_step(self, batch, batch_idx):
|
||||
loss, scores, y = self._common_step(batch, batch_idx)
|
||||
self.log("val_loss", loss)
|
||||
return loss
|
||||
|
||||
def test_step(self, batch, batch_idx):
|
||||
loss, scores, y = self._common_step(batch, batch_idx)
|
||||
self.log("test_loss", loss)
|
||||
return loss
|
||||
|
||||
def _common_step(self, batch, batch_idx):
|
||||
x, y = batch
|
||||
x = x.reshape(x.size(0), -1)
|
||||
scores = self.forward(x)
|
||||
loss = self.loss_fn(scores, y)
|
||||
return loss, scores, y
|
||||
|
||||
def predict_step(self, batch, batch_idx):
|
||||
x, y = batch
|
||||
x = x.reshape(x.size(0), -1)
|
||||
scores = self.forward(x)
|
||||
preds = torch.argmax(scores, dim=1)
|
||||
return preds
|
||||
|
||||
def configure_optimizers(self):
|
||||
return optim.Adam(self.parameters(), lr=self.lr)
|
||||
27
ML/Pytorch/pytorch_lightning/6. Restructuring/train.py
Normal file
27
ML/Pytorch/pytorch_lightning/6. Restructuring/train.py
Normal file
@@ -0,0 +1,27 @@
|
||||
import torch
|
||||
import pytorch_lightning as pl
|
||||
from model import NN
|
||||
from dataset import MnistDataModule
|
||||
import config
|
||||
|
||||
if __name__ == "__main__":
|
||||
model = NN(
|
||||
input_size=config.INPUT_SIZE,
|
||||
learning_rate=config.LEARNING_RATE,
|
||||
num_classes=config.NUM_CLASSES,
|
||||
)
|
||||
dm = MnistDataModule(
|
||||
data_dir=config.DATA_DIR,
|
||||
batch_size=config.BATCH_SIZE,
|
||||
num_workers=config.NUM_WORKERS,
|
||||
)
|
||||
trainer = pl.Trainer(
|
||||
accelerator=config.ACCELERATOR,
|
||||
devices=config.DEVICES,
|
||||
min_epochs=1,
|
||||
max_epochs=3,
|
||||
precision=config.PRECISION,
|
||||
)
|
||||
trainer.fit(model, dm)
|
||||
trainer.validate(model, dm)
|
||||
trainer.test(model, dm)
|
||||
12
ML/Pytorch/pytorch_lightning/7. Callbacks/callbacks.py
Normal file
12
ML/Pytorch/pytorch_lightning/7. Callbacks/callbacks.py
Normal file
@@ -0,0 +1,12 @@
|
||||
from pytorch_lightning.callbacks import EarlyStopping, Callback
|
||||
|
||||
class MyPrintingCallback(Callback):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
def on_train_start(self, trainer, pl_module):
|
||||
print("Starting to train!")
|
||||
|
||||
def on_train_end(self, trainer, pl_module):
|
||||
print("Training is done.")
|
||||
|
||||
15
ML/Pytorch/pytorch_lightning/7. Callbacks/config.py
Normal file
15
ML/Pytorch/pytorch_lightning/7. Callbacks/config.py
Normal file
@@ -0,0 +1,15 @@
|
||||
# Training hyperparameters
|
||||
INPUT_SIZE = 784
|
||||
NUM_CLASSES = 10
|
||||
LEARNING_RATE = 0.001
|
||||
BATCH_SIZE = 64
|
||||
NUM_EPOCHS = 1000
|
||||
|
||||
# Dataset
|
||||
DATA_DIR = "dataset/"
|
||||
NUM_WORKERS = 4
|
||||
|
||||
# Compute related
|
||||
ACCELERATOR = "gpu"
|
||||
DEVICES = [0]
|
||||
PRECISION = 16
|
||||
59
ML/Pytorch/pytorch_lightning/7. Callbacks/dataset.py
Normal file
59
ML/Pytorch/pytorch_lightning/7. Callbacks/dataset.py
Normal file
@@ -0,0 +1,59 @@
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
import torchvision.datasets as datasets
|
||||
import torchvision.transforms as transforms
|
||||
from torch import nn, optim
|
||||
from torch.utils.data import DataLoader
|
||||
from torch.utils.data import random_split
|
||||
import pytorch_lightning as pl
|
||||
|
||||
|
||||
class MnistDataModule(pl.LightningDataModule):
|
||||
def __init__(self, data_dir, batch_size, num_workers):
|
||||
super().__init__()
|
||||
self.data_dir = data_dir
|
||||
self.batch_size = batch_size
|
||||
self.num_workers = num_workers
|
||||
|
||||
def prepare_data(self):
|
||||
datasets.MNIST(self.data_dir, train=True, download=True)
|
||||
datasets.MNIST(self.data_dir, train=False, download=True)
|
||||
|
||||
def setup(self, stage):
|
||||
entire_dataset = datasets.MNIST(
|
||||
root=self.data_dir,
|
||||
train=True,
|
||||
transform=transforms.ToTensor(),
|
||||
download=False,
|
||||
)
|
||||
self.train_ds, self.val_ds = random_split(entire_dataset, [50000, 10000])
|
||||
self.test_ds = datasets.MNIST(
|
||||
root=self.data_dir,
|
||||
train=False,
|
||||
transform=transforms.ToTensor(),
|
||||
download=False,
|
||||
)
|
||||
|
||||
def train_dataloader(self):
|
||||
return DataLoader(
|
||||
self.train_ds,
|
||||
batch_size=self.batch_size,
|
||||
num_workers=self.num_workers,
|
||||
shuffle=True,
|
||||
)
|
||||
|
||||
def val_dataloader(self):
|
||||
return DataLoader(
|
||||
self.val_ds,
|
||||
batch_size=self.batch_size,
|
||||
num_workers=self.num_workers,
|
||||
shuffle=False,
|
||||
)
|
||||
|
||||
def test_dataloader(self):
|
||||
return DataLoader(
|
||||
self.test_ds,
|
||||
batch_size=self.batch_size,
|
||||
num_workers=self.num_workers,
|
||||
shuffle=False,
|
||||
)
|
||||
71
ML/Pytorch/pytorch_lightning/7. Callbacks/model.py
Normal file
71
ML/Pytorch/pytorch_lightning/7. Callbacks/model.py
Normal file
@@ -0,0 +1,71 @@
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
import torchvision.datasets as datasets
|
||||
import torchvision.transforms as transforms
|
||||
from torch import nn, optim
|
||||
from torch.utils.data import DataLoader
|
||||
from tqdm import tqdm
|
||||
import pytorch_lightning as pl
|
||||
import torchmetrics
|
||||
from torchmetrics import Metric
|
||||
|
||||
|
||||
class NN(pl.LightningModule):
|
||||
def __init__(self, input_size, learning_rate, num_classes):
|
||||
super().__init__()
|
||||
self.lr = learning_rate
|
||||
self.fc1 = nn.Linear(input_size, 50)
|
||||
self.fc2 = nn.Linear(50, num_classes)
|
||||
self.loss_fn = nn.CrossEntropyLoss()
|
||||
self.accuracy = torchmetrics.Accuracy(
|
||||
task="multiclass", num_classes=num_classes
|
||||
)
|
||||
self.f1_score = torchmetrics.F1Score(task="multiclass", num_classes=num_classes)
|
||||
|
||||
def forward(self, x):
|
||||
x = F.relu(self.fc1(x))
|
||||
x = self.fc2(x)
|
||||
return x
|
||||
|
||||
def training_step(self, batch, batch_idx):
|
||||
loss, scores, y = self._common_step(batch, batch_idx)
|
||||
accuracy = self.accuracy(scores, y)
|
||||
f1_score = self.f1_score(scores, y)
|
||||
self.log_dict(
|
||||
{
|
||||
"train_loss": loss,
|
||||
"train_accuracy": accuracy,
|
||||
"train_f1_score": f1_score,
|
||||
},
|
||||
on_step=False,
|
||||
on_epoch=True,
|
||||
prog_bar=True,
|
||||
)
|
||||
return {"loss": loss, "scores": scores, "y": y}
|
||||
|
||||
def validation_step(self, batch, batch_idx):
|
||||
loss, scores, y = self._common_step(batch, batch_idx)
|
||||
self.log("val_loss", loss)
|
||||
return loss
|
||||
|
||||
def test_step(self, batch, batch_idx):
|
||||
loss, scores, y = self._common_step(batch, batch_idx)
|
||||
self.log("test_loss", loss)
|
||||
return loss
|
||||
|
||||
def _common_step(self, batch, batch_idx):
|
||||
x, y = batch
|
||||
x = x.reshape(x.size(0), -1)
|
||||
scores = self.forward(x)
|
||||
loss = self.loss_fn(scores, y)
|
||||
return loss, scores, y
|
||||
|
||||
def predict_step(self, batch, batch_idx):
|
||||
x, y = batch
|
||||
x = x.reshape(x.size(0), -1)
|
||||
scores = self.forward(x)
|
||||
preds = torch.argmax(scores, dim=1)
|
||||
return preds
|
||||
|
||||
def configure_optimizers(self):
|
||||
return optim.Adam(self.parameters(), lr=self.lr)
|
||||
31
ML/Pytorch/pytorch_lightning/7. Callbacks/train.py
Normal file
31
ML/Pytorch/pytorch_lightning/7. Callbacks/train.py
Normal file
@@ -0,0 +1,31 @@
|
||||
import torch
|
||||
import pytorch_lightning as pl
|
||||
from model import NN
|
||||
from dataset import MnistDataModule
|
||||
import config
|
||||
from callbacks import MyPrintingCallback, EarlyStopping
|
||||
|
||||
torch.set_float32_matmul_precision("medium") # to make lightning happy
|
||||
|
||||
if __name__ == "__main__":
|
||||
model = NN(
|
||||
input_size=config.INPUT_SIZE,
|
||||
learning_rate=config.LEARNING_RATE,
|
||||
num_classes=config.NUM_CLASSES,
|
||||
)
|
||||
dm = MnistDataModule(
|
||||
data_dir=config.DATA_DIR,
|
||||
batch_size=config.BATCH_SIZE,
|
||||
num_workers=config.NUM_WORKERS,
|
||||
)
|
||||
trainer = pl.Trainer(
|
||||
accelerator=config.ACCELERATOR,
|
||||
devices=config.DEVICES,
|
||||
min_epochs=1,
|
||||
max_epochs=config.NUM_EPOCHS,
|
||||
precision=config.PRECISION,
|
||||
callbacks=[MyPrintingCallback(), EarlyStopping(monitor="val_loss")],
|
||||
)
|
||||
trainer.fit(model, dm)
|
||||
trainer.validate(model, dm)
|
||||
trainer.test(model, dm)
|
||||
@@ -0,0 +1,12 @@
|
||||
from pytorch_lightning.callbacks import EarlyStopping, Callback
|
||||
|
||||
class MyPrintingCallback(Callback):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
def on_train_start(self, trainer, pl_module):
|
||||
print("Starting to train!")
|
||||
|
||||
def on_train_end(self, trainer, pl_module):
|
||||
print("Training is done.")
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
# Training hyperparameters
|
||||
INPUT_SIZE = 784
|
||||
NUM_CLASSES = 10
|
||||
LEARNING_RATE = 0.001
|
||||
BATCH_SIZE = 64
|
||||
NUM_EPOCHS = 1000
|
||||
|
||||
# Dataset
|
||||
DATA_DIR = "dataset/"
|
||||
NUM_WORKERS = 4
|
||||
|
||||
# Compute related
|
||||
ACCELERATOR = "gpu"
|
||||
DEVICES = [0]
|
||||
PRECISION = 16
|
||||
@@ -0,0 +1,64 @@
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
import torchvision.datasets as datasets
|
||||
import torchvision.transforms as transforms
|
||||
from torch import nn, optim
|
||||
from torch.utils.data import DataLoader
|
||||
from torch.utils.data import random_split
|
||||
import pytorch_lightning as pl
|
||||
from torchvision.transforms import RandomHorizontalFlip, RandomVerticalFlip
|
||||
|
||||
|
||||
class MnistDataModule(pl.LightningDataModule):
|
||||
def __init__(self, data_dir, batch_size, num_workers):
|
||||
super().__init__()
|
||||
self.data_dir = data_dir
|
||||
self.batch_size = batch_size
|
||||
self.num_workers = num_workers
|
||||
|
||||
def prepare_data(self):
|
||||
datasets.MNIST(self.data_dir, train=True, download=True)
|
||||
datasets.MNIST(self.data_dir, train=False, download=True)
|
||||
|
||||
def setup(self, stage):
|
||||
entire_dataset = datasets.MNIST(
|
||||
root=self.data_dir,
|
||||
train=True,
|
||||
transform=transforms.Compose([
|
||||
transforms.RandomVerticalFlip(),
|
||||
transforms.RandomHorizontalFlip(),
|
||||
transforms.ToTensor(),
|
||||
]),
|
||||
download=False,
|
||||
)
|
||||
self.train_ds, self.val_ds = random_split(entire_dataset, [50000, 10000])
|
||||
self.test_ds = datasets.MNIST(
|
||||
root=self.data_dir,
|
||||
train=False,
|
||||
transform=transforms.ToTensor(),
|
||||
download=False,
|
||||
)
|
||||
|
||||
def train_dataloader(self):
|
||||
return DataLoader(
|
||||
self.train_ds,
|
||||
batch_size=self.batch_size,
|
||||
num_workers=self.num_workers,
|
||||
shuffle=True,
|
||||
)
|
||||
|
||||
def val_dataloader(self):
|
||||
return DataLoader(
|
||||
self.val_ds,
|
||||
batch_size=self.batch_size,
|
||||
num_workers=self.num_workers,
|
||||
shuffle=False,
|
||||
)
|
||||
|
||||
def test_dataloader(self):
|
||||
return DataLoader(
|
||||
self.test_ds,
|
||||
batch_size=self.batch_size,
|
||||
num_workers=self.num_workers,
|
||||
shuffle=False,
|
||||
)
|
||||
79
ML/Pytorch/pytorch_lightning/8. Logging Tensorboard/model.py
Normal file
79
ML/Pytorch/pytorch_lightning/8. Logging Tensorboard/model.py
Normal file
@@ -0,0 +1,79 @@
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
import torchvision.datasets as datasets
|
||||
import torchvision.transforms as transforms
|
||||
from torch import nn, optim
|
||||
from torch.utils.data import DataLoader
|
||||
from tqdm import tqdm
|
||||
import pytorch_lightning as pl
|
||||
import torchmetrics
|
||||
from torchmetrics import Metric
|
||||
import torchvision
|
||||
|
||||
|
||||
class NN(pl.LightningModule):
|
||||
def __init__(self, input_size, learning_rate, num_classes):
|
||||
super().__init__()
|
||||
self.lr = learning_rate
|
||||
self.fc1 = nn.Linear(input_size, 50)
|
||||
self.fc2 = nn.Linear(50, num_classes)
|
||||
self.loss_fn = nn.CrossEntropyLoss()
|
||||
self.accuracy = torchmetrics.Accuracy(
|
||||
task="multiclass", num_classes=num_classes
|
||||
)
|
||||
self.f1_score = torchmetrics.F1Score(task="multiclass", num_classes=num_classes)
|
||||
|
||||
def forward(self, x):
|
||||
x = F.relu(self.fc1(x))
|
||||
x = self.fc2(x)
|
||||
return x
|
||||
|
||||
def training_step(self, batch, batch_idx):
|
||||
x, y = batch
|
||||
loss, scores, y = self._common_step(batch, batch_idx)
|
||||
accuracy = self.accuracy(scores, y)
|
||||
f1_score = self.f1_score(scores, y)
|
||||
self.log_dict(
|
||||
{
|
||||
"train_loss": loss,
|
||||
"train_accuracy": accuracy,
|
||||
"train_f1_score": f1_score,
|
||||
},
|
||||
on_step=False,
|
||||
on_epoch=True,
|
||||
prog_bar=True,
|
||||
)
|
||||
|
||||
if batch_idx % 100 == 0:
|
||||
x = x[:8]
|
||||
grid = torchvision.utils.make_grid(x.view(-1, 1, 28, 28))
|
||||
self.logger.experiment.add_image("mnist_images", grid, self.global_step)
|
||||
|
||||
return {"loss": loss, "scores": scores, "y": y}
|
||||
|
||||
def validation_step(self, batch, batch_idx):
|
||||
loss, scores, y = self._common_step(batch, batch_idx)
|
||||
self.log("val_loss", loss)
|
||||
return loss
|
||||
|
||||
def test_step(self, batch, batch_idx):
|
||||
loss, scores, y = self._common_step(batch, batch_idx)
|
||||
self.log("test_loss", loss)
|
||||
return loss
|
||||
|
||||
def _common_step(self, batch, batch_idx):
|
||||
x, y = batch
|
||||
x = x.reshape(x.size(0), -1)
|
||||
scores = self.forward(x)
|
||||
loss = self.loss_fn(scores, y)
|
||||
return loss, scores, y
|
||||
|
||||
def predict_step(self, batch, batch_idx):
|
||||
x, y = batch
|
||||
x = x.reshape(x.size(0), -1)
|
||||
scores = self.forward(x)
|
||||
preds = torch.argmax(scores, dim=1)
|
||||
return preds
|
||||
|
||||
def configure_optimizers(self):
|
||||
return optim.Adam(self.parameters(), lr=self.lr)
|
||||
34
ML/Pytorch/pytorch_lightning/8. Logging Tensorboard/train.py
Normal file
34
ML/Pytorch/pytorch_lightning/8. Logging Tensorboard/train.py
Normal file
@@ -0,0 +1,34 @@
|
||||
import torch
|
||||
import pytorch_lightning as pl
|
||||
from model import NN
|
||||
from dataset import MnistDataModule
|
||||
import config
|
||||
from callbacks import MyPrintingCallback, EarlyStopping
|
||||
from pytorch_lightning.loggers import TensorBoardLogger
|
||||
|
||||
torch.set_float32_matmul_precision("medium") # to make lightning happy
|
||||
|
||||
if __name__ == "__main__":
|
||||
logger = TensorBoardLogger("tb_logs", name="mnist_model_v0")
|
||||
model = NN(
|
||||
input_size=config.INPUT_SIZE,
|
||||
learning_rate=config.LEARNING_RATE,
|
||||
num_classes=config.NUM_CLASSES,
|
||||
)
|
||||
dm = MnistDataModule(
|
||||
data_dir=config.DATA_DIR,
|
||||
batch_size=config.BATCH_SIZE,
|
||||
num_workers=config.NUM_WORKERS,
|
||||
)
|
||||
trainer = pl.Trainer(
|
||||
logger=logger,
|
||||
accelerator=config.ACCELERATOR,
|
||||
devices=config.DEVICES,
|
||||
min_epochs=1,
|
||||
max_epochs=config.NUM_EPOCHS,
|
||||
precision=config.PRECISION,
|
||||
callbacks=[MyPrintingCallback(), EarlyStopping(monitor="val_loss")],
|
||||
)
|
||||
trainer.fit(model, dm)
|
||||
trainer.validate(model, dm)
|
||||
trainer.test(model, dm)
|
||||
12
ML/Pytorch/pytorch_lightning/9. Profiler/callbacks.py
Normal file
12
ML/Pytorch/pytorch_lightning/9. Profiler/callbacks.py
Normal file
@@ -0,0 +1,12 @@
|
||||
from pytorch_lightning.callbacks import EarlyStopping, Callback
|
||||
|
||||
class MyPrintingCallback(Callback):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
def on_train_start(self, trainer, pl_module):
|
||||
print("Starting to train!")
|
||||
|
||||
def on_train_end(self, trainer, pl_module):
|
||||
print("Training is done.")
|
||||
|
||||
15
ML/Pytorch/pytorch_lightning/9. Profiler/config.py
Normal file
15
ML/Pytorch/pytorch_lightning/9. Profiler/config.py
Normal file
@@ -0,0 +1,15 @@
|
||||
# Training hyperparameters
|
||||
INPUT_SIZE = 784
|
||||
NUM_CLASSES = 10
|
||||
LEARNING_RATE = 0.001
|
||||
BATCH_SIZE = 64
|
||||
NUM_EPOCHS = 3
|
||||
|
||||
# Dataset
|
||||
DATA_DIR = "dataset/"
|
||||
NUM_WORKERS = 4
|
||||
|
||||
# Compute related
|
||||
ACCELERATOR = "gpu"
|
||||
DEVICES = [0]
|
||||
PRECISION = 16
|
||||
64
ML/Pytorch/pytorch_lightning/9. Profiler/dataset.py
Normal file
64
ML/Pytorch/pytorch_lightning/9. Profiler/dataset.py
Normal file
@@ -0,0 +1,64 @@
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
import torchvision.datasets as datasets
|
||||
import torchvision.transforms as transforms
|
||||
from torch import nn, optim
|
||||
from torch.utils.data import DataLoader
|
||||
from torch.utils.data import random_split
|
||||
import pytorch_lightning as pl
|
||||
from torchvision.transforms import RandomHorizontalFlip, RandomVerticalFlip
|
||||
|
||||
|
||||
class MnistDataModule(pl.LightningDataModule):
|
||||
def __init__(self, data_dir, batch_size, num_workers):
|
||||
super().__init__()
|
||||
self.data_dir = data_dir
|
||||
self.batch_size = batch_size
|
||||
self.num_workers = num_workers
|
||||
|
||||
def prepare_data(self):
|
||||
datasets.MNIST(self.data_dir, train=True, download=True)
|
||||
datasets.MNIST(self.data_dir, train=False, download=True)
|
||||
|
||||
def setup(self, stage):
|
||||
entire_dataset = datasets.MNIST(
|
||||
root=self.data_dir,
|
||||
train=True,
|
||||
transform=transforms.Compose([
|
||||
transforms.RandomVerticalFlip(),
|
||||
transforms.RandomHorizontalFlip(),
|
||||
transforms.ToTensor(),
|
||||
]),
|
||||
download=False,
|
||||
)
|
||||
self.train_ds, self.val_ds = random_split(entire_dataset, [50000, 10000])
|
||||
self.test_ds = datasets.MNIST(
|
||||
root=self.data_dir,
|
||||
train=False,
|
||||
transform=transforms.ToTensor(),
|
||||
download=False,
|
||||
)
|
||||
|
||||
def train_dataloader(self):
|
||||
return DataLoader(
|
||||
self.train_ds,
|
||||
batch_size=self.batch_size,
|
||||
num_workers=self.num_workers,
|
||||
shuffle=True,
|
||||
)
|
||||
|
||||
def val_dataloader(self):
|
||||
return DataLoader(
|
||||
self.val_ds,
|
||||
batch_size=self.batch_size,
|
||||
num_workers=self.num_workers,
|
||||
shuffle=False,
|
||||
)
|
||||
|
||||
def test_dataloader(self):
|
||||
return DataLoader(
|
||||
self.test_ds,
|
||||
batch_size=self.batch_size,
|
||||
num_workers=self.num_workers,
|
||||
shuffle=False,
|
||||
)
|
||||
89
ML/Pytorch/pytorch_lightning/9. Profiler/model.py
Normal file
89
ML/Pytorch/pytorch_lightning/9. Profiler/model.py
Normal file
@@ -0,0 +1,89 @@
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
import torchvision.datasets as datasets
|
||||
import torchvision.transforms as transforms
|
||||
from torch import nn, optim
|
||||
from torch.utils.data import DataLoader
|
||||
from tqdm import tqdm
|
||||
import pytorch_lightning as pl
|
||||
import torchmetrics
|
||||
from torchmetrics import Metric
|
||||
import torchvision
|
||||
|
||||
|
||||
class NN(pl.LightningModule):
|
||||
def __init__(self, input_size, learning_rate, num_classes):
|
||||
super().__init__()
|
||||
self.lr = learning_rate
|
||||
self.fc1 = nn.Linear(input_size, 50)
|
||||
self.fc2 = nn.Linear(50, num_classes)
|
||||
self.loss_fn = nn.CrossEntropyLoss()
|
||||
self.accuracy = torchmetrics.Accuracy(
|
||||
task="multiclass", num_classes=num_classes
|
||||
)
|
||||
self.f1_score = torchmetrics.F1Score(task="multiclass", num_classes=num_classes)
|
||||
|
||||
def forward(self, x):
|
||||
x = F.relu(self.fc1(x))
|
||||
x = self.fc2(x)
|
||||
return x
|
||||
|
||||
def training_step(self, batch, batch_idx):
|
||||
x, y = batch
|
||||
loss, scores, y = self._common_step(batch, batch_idx)
|
||||
|
||||
self.log_dict(
|
||||
{
|
||||
"train_loss": loss,
|
||||
},
|
||||
on_step=False,
|
||||
on_epoch=True,
|
||||
prog_bar=True,
|
||||
)
|
||||
|
||||
if batch_idx % 100 == 0:
|
||||
x = x[:8]
|
||||
grid = torchvision.utils.make_grid(x.view(-1, 1, 28, 28))
|
||||
self.logger.experiment.add_image("mnist_images", grid, self.global_step)
|
||||
|
||||
return {"loss": loss, "scores": scores, "y": y}
|
||||
|
||||
def training_epoch_end(self, outputs):
|
||||
scores = torch.cat([x["scores"] for x in outputs])
|
||||
y = torch.cat([x["y"] for x in outputs])
|
||||
self.log_dict(
|
||||
{
|
||||
"train_acc": self.accuracy(scores, y),
|
||||
"train_f1": self.f1_score(scores, y),
|
||||
},
|
||||
on_step=False,
|
||||
on_epoch=True,
|
||||
prog_bar=True,
|
||||
)
|
||||
|
||||
def validation_step(self, batch, batch_idx):
|
||||
loss, scores, y = self._common_step(batch, batch_idx)
|
||||
self.log("val_loss", loss)
|
||||
return loss
|
||||
|
||||
def test_step(self, batch, batch_idx):
|
||||
loss, scores, y = self._common_step(batch, batch_idx)
|
||||
self.log("test_loss", loss)
|
||||
return loss
|
||||
|
||||
def _common_step(self, batch, batch_idx):
|
||||
x, y = batch
|
||||
x = x.reshape(x.size(0), -1)
|
||||
scores = self.forward(x)
|
||||
loss = self.loss_fn(scores, y)
|
||||
return loss, scores, y
|
||||
|
||||
def predict_step(self, batch, batch_idx):
|
||||
x, y = batch
|
||||
x = x.reshape(x.size(0), -1)
|
||||
scores = self.forward(x)
|
||||
preds = torch.argmax(scores, dim=1)
|
||||
return preds
|
||||
|
||||
def configure_optimizers(self):
|
||||
return optim.Adam(self.parameters(), lr=self.lr)
|
||||
40
ML/Pytorch/pytorch_lightning/9. Profiler/train.py
Normal file
40
ML/Pytorch/pytorch_lightning/9. Profiler/train.py
Normal file
@@ -0,0 +1,40 @@
|
||||
import torch
|
||||
import pytorch_lightning as pl
|
||||
from model import NN
|
||||
from dataset import MnistDataModule
|
||||
import config
|
||||
from callbacks import MyPrintingCallback, EarlyStopping
|
||||
from pytorch_lightning.loggers import TensorBoardLogger
|
||||
from pytorch_lightning.profilers import PyTorchProfiler
|
||||
|
||||
torch.set_float32_matmul_precision("medium") # to make lightning happy
|
||||
|
||||
if __name__ == "__main__":
|
||||
logger = TensorBoardLogger("tb_logs", name="mnist_model_v1")
|
||||
profiler = PyTorchProfiler(
|
||||
on_trace_ready=torch.profiler.tensorboard_trace_handler("tb_logs/profiler0"),
|
||||
schedule=torch.profiler.schedule(skip_first=10, wait=1, warmup=1, active=20),
|
||||
)
|
||||
model = NN(
|
||||
input_size=config.INPUT_SIZE,
|
||||
learning_rate=config.LEARNING_RATE,
|
||||
num_classes=config.NUM_CLASSES,
|
||||
)
|
||||
dm = MnistDataModule(
|
||||
data_dir=config.DATA_DIR,
|
||||
batch_size=config.BATCH_SIZE,
|
||||
num_workers=config.NUM_WORKERS,
|
||||
)
|
||||
trainer = pl.Trainer(
|
||||
profiler=profiler,
|
||||
logger=logger,
|
||||
accelerator=config.ACCELERATOR,
|
||||
devices=config.DEVICES,
|
||||
min_epochs=1,
|
||||
max_epochs=config.NUM_EPOCHS,
|
||||
precision=config.PRECISION,
|
||||
callbacks=[MyPrintingCallback(), EarlyStopping(monitor="val_loss")],
|
||||
)
|
||||
trainer.fit(model, dm)
|
||||
trainer.validate(model, dm)
|
||||
trainer.test(model, dm)
|
||||
Reference in New Issue
Block a user