restructure project again

This commit is contained in:
hobogalaxy committed 2020-11-27 01:19:11 +01:00
1 parent 20c451bc3d
commit ee7006a92a
24 files changed
+207 -632

No files matched your search

+1 -1
View File
@@ -230,4 +230,4 @@ project/lightning_logs/
project/wandb/ project/wandb/
project/logs/ project/logs/
project/config.yaml project/project_config.yaml
-95
View File
@@ -1,95 +0,0 @@
num_of_gpus: -1
model_configs:
simple_mnist_classifier_v1: # everything inside will be saved to to wandb and in model checkpoint
model_folder_name: "simple_mnist_classifier"
max_epochs: 3
lr: 0.001
batch_size: 64
weight_decay: 0.000001
gradient_clip_val: 0.5
accumulate_grad_batches: 1
input_size: 784 # img size is 28*28*1
output_size: 10
lin1_size: 256
lin2_size: 256
lin3_size: 128
dataset:
class_name: "MNISTDataModule"
train_transforms: "minst_train_preprocess"
test_transforms: "minst_test_preprocess"
train_val_split_ratio: 0.8
num_workers: 1
pin_memory: False
transfer_learning_cifar10_classifier_v1:
model_folder_name: "transfer_learning_img_classifier"
max_epochs: 3
lr: 0.001
batch_size: 128
weight_decay: 0.000001
gradient_clip_val: 0.5
accumulate_grad_batches: 1
output_size: 10
lin1_size: 512
lin2_size: 256
dataset:
class_name: "CIFAR10DataModule"
train_transforms: "cifar10_train_preprocess"
test_transforms: "cifar10_test_preprocess"
train_val_split_ratio: 0.9
num_workers: 1
pin_memory: False
transfer_learning_cifar10_classifier_v2:
model_folder_name: "transfer_learning_img_classifier"
max_epochs: 3
lr: 0.001
batch_size: 128
weight_decay: 0.000001
gradient_clip_val: 0.5
accumulate_grad_batches: 1
output_size: 10
lin1_size: 512
lin2_size: 256
dataset:
class_name: "CIFAR10DataModule"
train_transforms: "cifar10_train_preprocess"
test_transforms: "cifar10_test_preprocess"
train_val_split_ratio: 0.9
num_workers: 1
pin_memory: False
resume_training:
lightning_ckpt:
resume_from_ckpt: False
ckpt_path: "logs/checkpoints/epoch=2.ckpt"
wandb:
resume_wandb_run: False
wandb_run_id: "8uuomodb"
loggers:
wandb:
project: "hackathon_template_test"
team: "kino"
group: None
job_type: "train"
tags: []
log_model: True
offline: False
callbacks:
checkpoint:
monitor: "val_acc"
save_top_k: 1
save_last: True
mode: "max"
early_stop:
monitor: "val_acc"
patience: 100
mode: "max"
printing:
progress_bar_refresh_rate: 5
weights_summary: "top" # "full"
profiler: False
@@ -1,23 +1,23 @@
from torch.utils.data import DataLoader, random_split from torch.utils.data import DataLoader, random_split
from torchvision.datasets import MNIST, CIFAR10 from torchvision.datasets import MNIST, CIFAR10
from torchvision.transforms import transforms
import pytorch_lightning as pl import pytorch_lightning as pl
# custom data_modules
class ExampleDataModule(pl.LightningDataModule): class ExampleDataModule(pl.LightningDataModule):
"""All datamodules should look like this!""" """All datamodules should look like this!"""
def __init__(self, transforms, data_dir="data/example_data", batch_size=64, data_split_ratio=0.90, num_workers=1, def __init__(self, data_dir="data/example_data", batch_size=64, data_split_ratio=0.90, num_workers=1,
pin_memory=False, **args): pin_memory=False):
super().__init__() super().__init__()
self.transforms = transforms
self.data_dir = data_dir self.data_dir = data_dir
self.batch_size = batch_size self.batch_size = batch_size
self.data_split_ratio = data_split_ratio self.data_split_ratio = data_split_ratio
self.num_workers = num_workers self.num_workers = num_workers
self.pin_memory = pin_memory self.pin_memory = pin_memory
self.transforms = None
self.data_train = None self.data_train = None
self.data_val = None self.data_val = None
self.data_test = None self.data_test = None
@@ -44,17 +44,18 @@ class ExampleDataModule(pl.LightningDataModule):
class MNISTDataModule(pl.LightningDataModule): class MNISTDataModule(pl.LightningDataModule):
def __init__(self, transforms, data_dir='data/mnist', batch_size=64, train_val_split_ratio=0.90, num_workers=1, def __init__(self, data_dir='data/mnist', batch_size=64, train_val_split_ratio=0.90, num_workers=1,
pin_memory=False, **args): pin_memory=False):
super().__init__() super().__init__()
self.transforms = transforms
self.data_dir = data_dir self.data_dir = data_dir
self.batch_size = batch_size self.batch_size = batch_size
self.train_val_split_ratio = train_val_split_ratio self.train_val_split_ratio = train_val_split_ratio
self.num_workers = num_workers self.num_workers = num_workers
self.pin_memory = pin_memory self.pin_memory = pin_memory
self.transforms = transforms.ToTensor()
self.data_train = None self.data_train = None
self.data_val = None self.data_val = None
self.data_test = None self.data_test = None
@@ -88,17 +89,18 @@ class MNISTDataModule(pl.LightningDataModule):
class CIFAR10DataModule(pl.LightningDataModule): class CIFAR10DataModule(pl.LightningDataModule):
def __init__(self, transforms, data_dir="data/cifar10", batch_size=64, train_val_split_ratio=0.90, num_workers=1, def __init__(self, data_dir="data/cifar10", batch_size=64, train_val_split_ratio=0.90, num_workers=1,
pin_memory=False, **args): pin_memory=False):
super().__init__() super().__init__()
self.transforms = transforms
self.data_dir = data_dir self.data_dir = data_dir
self.batch_size = batch_size self.batch_size = batch_size
self.train_val_split_ratio = train_val_split_ratio self.train_val_split_ratio = train_val_split_ratio
self.num_workers = num_workers self.num_workers = num_workers
self.pin_memory = pin_memory self.pin_memory = pin_memory
self.transforms = transforms.ToTensor()
self.data_train = None self.data_train = None
self.data_val = None self.data_val = None
self.data_test = None self.data_test = None
@@ -4,6 +4,7 @@ import os
class TestDatasetForImgs(Dataset): class TestDatasetForImgs(Dataset):
"""Example dataset class for loading images from folder."""
def __init__(self, img_dir, transform): def __init__(self, img_dir, transform):
self.transform = transform self.transform = transform
@@ -1,40 +1,40 @@
from torchvision import transforms from torchvision import transforms
minst_train_preprocess = transforms.Compose([ mnist_train_transforms = transforms.Compose([
transforms.ToTensor(), transforms.ToTensor(),
]) ])
mnist_test_preprocess = transforms.Compose([ mnist_test_transforms = transforms.Compose([
transforms.ToTensor() transforms.ToTensor()
]) ])
img_augmentation_transformations = [ img_augmentation_transforms = [
transforms.RandomAffine((-15, 15), translate=(0.2, 0.2)), transforms.RandomAffine((-15, 15), translate=(0.2, 0.2)),
transforms.RandomHorizontalFlip(p=0.65), transforms.RandomHorizontalFlip(p=0.65),
transforms.RandomRotation((-15, 15)), transforms.RandomRotation((-15, 15)),
transforms.ColorJitter(hue=.05, saturation=.05), transforms.ColorJitter(hue=.05, saturation=.05),
] ]
imagenet_train_preprocess = transforms.Compose([ imagenet_train_transforms = transforms.Compose([
transforms.Resize((256, 256)), # the correct size for eff net b1 is 224x224 but we random crop it later transforms.Resize((256, 256)), # the correct size for eff net b1 is 224x224 but we random crop it later
transforms.RandomCrop(224), transforms.RandomCrop(224),
transforms.ToTensor(), transforms.ToTensor(),
transforms.RandomApply(img_augmentation_transformations, 0.8), transforms.RandomApply(img_augmentation_transforms, 0.8),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
]) ])
imagenet_test_preprocess = transforms.Compose([ imagenet_test_transforms = transforms.Compose([
transforms.Resize((224, 224)), transforms.Resize((224, 224)),
transforms.ToTensor(), transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
]) ])
cifar10_train_preprocess = transforms.Compose([ cifar10_train_transforms = transforms.Compose([
transforms.ToTensor(), transforms.ToTensor(),
transforms.RandomHorizontalFlip(p=0.5), transforms.RandomHorizontalFlip(p=0.5),
]) ])
cifar10_test_preprocess = transforms.Compose([ cifar10_test_transforms = transforms.Compose([
transforms.ToTensor(), transforms.ToTensor(),
]) ])
Binary file not shown.
Binary file not shown.
Binary file not shown.
+1 -1
View File
@@ -20,4 +20,4 @@ for key, value in sweep_hparams.items():
model_conf[key] = value model_conf[key] = value
# Execute run # Execute run
train.train(config=conf, model_config=model_conf) train.train(project_config=conf, run_config=model_conf)
+5 -4
View File
@@ -134,13 +134,14 @@ class SaveCodeToWandbCallback(pl.Callback):
def __init__(self, wandb_save_dir, lit_model): def __init__(self, wandb_save_dir, lit_model):
self.wandb_save_dir = wandb_save_dir self.wandb_save_dir = wandb_save_dir
self.additional_files_to_be_saved = [ self.additional_files_to_be_saved = [
"lightning_modules/data_modules/datamodules.py", "data_modules/datamodules.py",
"lightning_modules/data_modules/datasets.py", "data_modules/datasets.py",
"lightning_modules/data_modules/transforms.py", "data_modules/transforms.py",
"lightning_modules/callbacks.py", "lightning_modules/callbacks.py",
"lightning_modules/init_utils.py", "lightning_modules/init_utils.py",
"train.py", "train.py",
"config.yaml" "project_config.yaml",
"run_configs.yaml",
] ]
self.model_path = os.path.dirname(inspect.getfile(lit_model.__class__)) self.model_path = os.path.dirname(inspect.getfile(lit_model.__class__))
+28 -20
View File
@@ -1,46 +1,49 @@
from pytorch_lightning.loggers import WandbLogger, TensorBoardLogger, CometLogger, MLFlowLogger, NeptuneLogger from pytorch_lightning.loggers import WandbLogger
from pytorch_lightning.callbacks import ModelCheckpoint, EarlyStopping from pytorch_lightning.callbacks import ModelCheckpoint, EarlyStopping
from lightning_modules.data_modules import datamodules, transforms from data_modules import datamodules
import importlib import importlib
import os import os
def init_lit_model(model_config): def init_lit_model(model_config):
module_path = "models." + model_config["model_folder_name"] + ".lightning_module" """Load LitModel from folder specified in run config."""
module_path = "models." + model_config["name"] + ".lightning_module"
model_config["model_folder_name"] = model_config.pop("name")
return importlib.import_module(module_path).LitModel(hparams=model_config) return importlib.import_module(module_path).LitModel(hparams=model_config)
def init_datamodule(model_config): def init_datamodule(dataset_config):
datamodule_class = getattr(datamodules, model_config["dataset"]["class_name"]) """Load datamodule from class specified in run config."""
train_transforms = getattr(transforms, model_config["dataset"]["train_transforms"]) datamodule_class = getattr(datamodules, dataset_config["name"])
datamodule = datamodule_class( dataset_config["datamodule_name"] = dataset_config.pop("name")
transforms=train_transforms, dataset_config = dataset_config.copy()
batch_size=model_config["batch_size"], dataset_config.pop("datamodule_name")
**model_config["dataset"] datamodule = datamodule_class(**dataset_config)
)
datamodule.prepare_data() datamodule.prepare_data()
datamodule.setup() datamodule.setup()
return datamodule return datamodule
def init_main_callbacks(config): def init_main_callbacks(project_config):
"""Initialize EarlyStopping callback and ModelCheckpoint callback."""
callbacks = [ callbacks = [
EarlyStopping( EarlyStopping(
monitor=config["callbacks"]["early_stop"]["monitor"], monitor=project_config["callbacks"]["early_stop"]["monitor"],
patience=config["callbacks"]["early_stop"]["patience"], patience=project_config["callbacks"]["early_stop"]["patience"],
mode=config["callbacks"]["early_stop"]["mode"], mode=project_config["callbacks"]["early_stop"]["mode"],
), ),
ModelCheckpoint( ModelCheckpoint(
monitor=config["callbacks"]["checkpoint"]["monitor"], monitor=project_config["callbacks"]["checkpoint"]["monitor"],
save_top_k=config["callbacks"]["checkpoint"]["save_top_k"], save_top_k=project_config["callbacks"]["checkpoint"]["save_top_k"],
mode=config["callbacks"]["checkpoint"]["mode"], mode=project_config["callbacks"]["checkpoint"]["mode"],
save_last=config["callbacks"]["checkpoint"]["save_last"], save_last=project_config["callbacks"]["checkpoint"]["save_last"],
) )
] ]
return callbacks return callbacks
def init_wandb_logger(config, lit_model, datamodule): def init_wandb_logger(config, run_config, lit_model, datamodule):
"""Initialize Weights&Biases logger."""
wandb_logger = WandbLogger( wandb_logger = WandbLogger(
project=config["loggers"]["wandb"]["project"], project=config["loggers"]["wandb"]["project"],
job_type=config["loggers"]["wandb"]["job_type"], job_type=config["loggers"]["wandb"]["job_type"],
@@ -55,7 +58,9 @@ def init_wandb_logger(config, lit_model, datamodule):
) )
if not os.path.exists("logs/"): if not os.path.exists("logs/"):
os.mkdir("logs/") os.mkdir("logs/")
if hasattr(lit_model, 'model'):
wandb_logger.watch(lit_model.model, log=None) wandb_logger.watch(lit_model.model, log=None)
wandb_logger.watch(lit_model, log=None)
wandb_logger.log_hyperparams({ wandb_logger.log_hyperparams({
"model_name": lit_model.model.__class__.__name__, "model_name": lit_model.model.__class__.__name__,
"optimizer": lit_model.configure_optimizers().__class__.__name__, "optimizer": lit_model.configure_optimizers().__class__.__name__,
@@ -63,6 +68,9 @@ def init_wandb_logger(config, lit_model, datamodule):
"val_size": len(datamodule.data_val) if datamodule.data_train is not None else 0, "val_size": len(datamodule.data_val) if datamodule.data_train is not None else 0,
"test_size": len(datamodule.data_test) if datamodule.data_train is not None else 0, "test_size": len(datamodule.data_test) if datamodule.data_train is not None else 0,
}) })
wandb_logger.log_hyperparams(run_config["model"])
wandb_logger.log_hyperparams(run_config["dataset"])
wandb_logger.log_hyperparams(run_config["trainer"])
return wandb_logger return wandb_logger
@@ -1 +0,0 @@
from .lightning_module import LitModel
@@ -67,4 +67,4 @@ class LitModel(pl.LightningModule):
return loss return loss
def configure_optimizers(self): def configure_optimizers(self):
return torch.optim.Adam(self.parameters(), lr=self.hparams.lr, weight_decay=self.hparams["weight_decay"]) return torch.optim.Adam(self.parameters(), lr=self.hparams.lr, weight_decay=self.hparams.weight_decay)
@@ -1,35 +0,0 @@
from models.simple_mnist_classifier.lightning_module import LitModel
from lightning_modules.data_modules import transforms
from PIL import Image
def predict():
"""
Loads model from checkpoint.
Model used in lightning_module.py and declaration of that model in models.py
should be the same as during training.
"""
CKPT_PATH = "epoch=0.ckpt"
# load model from checkpoint
pretrained_model = LitModel.load_from_checkpoint(checkpoint_path=CKPT_PATH)
# switch to evaluation mode
pretrained_model.eval()
pretrained_model.freeze()
# load data
img = Image.open("../../example_img.png").convert("L")
# preprocess
img = transforms.mnist_test_preprocess(img)
img = img.reshape((1, *img.size())) # reshape to form batch of size 1
# inference
output = pretrained_model(img)
print(output)
if __name__ == "__main__":
predict()
@@ -1 +0,0 @@
from .lightning_module import LitModel
@@ -67,4 +67,4 @@ class LitModel(pl.LightningModule):
return loss return loss
def configure_optimizers(self): def configure_optimizers(self):
return torch.optim.Adam(self.parameters(), lr=self.hparams.lr, weight_decay=self.hparams["weight_decay"]) return torch.optim.Adam(self.parameters(), lr=self.hparams.lr, weight_decay=self.hparams.weight_decay)
@@ -1,4 +1,3 @@
from pl_bolts.models.self_supervised import CPCV2
from efficientnet_pytorch import EfficientNet from efficientnet_pytorch import EfficientNet
from torchvision import models from torchvision import models
from torch import nn from torch import nn
@@ -9,7 +8,7 @@ class EfficientNetPretrained(nn.Module):
def __init__(self, config): def __init__(self, config):
super().__init__() super().__init__()
self.model = EfficientNet.from_pretrained('efficientnet-b1') self.model = EfficientNet.from_pretrained('efficientnet-b0')
for param in self.model.parameters(): for param in self.model.parameters():
param.requires_grad = False param.requires_grad = False
@@ -81,35 +80,3 @@ class ResnextPretrained(nn.Module):
def forward(self, x): def forward(self, x):
return self.model(x) return self.model(x)
# this model doesn't work yet, we wait for lightning-bolts patch
# class ResnetPretrainedUnsupervised(nn.Module):
# """
# Trained without labels on Imagenet.
# Perhaps the features when trained without labels are much better for classification or other tasks.
# """
# def __init__(self, config):
# super().__init__()
#
# self.model = CPCV2(encoder='resnet18', pretrained='imagenet128').encoder
# # self.model = CPCV2(encoder='resnet18', pretrained='stl10').encoder
#
# for param in self.model.parameters():
# param.requires_grad = False
#
# self.model.fc = nn.Sequential(
# nn.Linear(self.model.fc.in_features, config["lin1_size"]),
# nn.BatchNorm1d(config["lin1_size"]),
# nn.ReLU(),
# nn.Dropout(p=0.25),
# nn.Linear(config["lin1_size"], config["lin2_size"]),
# nn.BatchNorm1d(config["lin2_size"]),
# nn.ReLU(),
# nn.Dropout(p=0.2),
# nn.Linear(config["lin2_size"], config["output_size"]),
# nn.LogSoftmax(dim=1)
# )
#
# def forward(self, x):
# return self.model(x)
View File
Whitespace-only changes.
-372
View File
@@ -1,372 +0,0 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Import modules from parent directory"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"pycharm": {
"is_executing": false
}
},
"outputs": [],
"source": [
"# add directory above current directory to path\n",
"import sys\n",
"sys.path.insert(0, '..')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"pycharm": {
"is_executing": false
}
},
"outputs": [],
"source": [
"# now we can import modules from parent directory\n",
"import train\n",
"import pipeline_modules"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Define function to print object length with commas"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [],
"source": [
"showlen = lambda data: print(f\"{len(data):,}\")\n",
"showlen([0 for i in range(2395940)])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Create quick progress bars with tqdm"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"pycharm": {
"name": "#%%\n"
},
"scrolled": true
},
"outputs": [],
"source": [
"from tqdm import tqdm\n",
"import time\n",
"\n",
"for i in tqdm(range(10)):\n",
" time.sleep(1)"
]
},
{
"cell_type": "markdown",
"metadata": {
"pycharm": {
"name": "#%%\n"
}
},
"source": [
"### Prettier ipywidgets version of the progress bar specifically for the notebook environment"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [],
"source": [
"from tqdm.auto import tqdm\n",
"\n",
"for i in tqdm(range(10)):\n",
" time.sleep(1)"
]
},
{
"cell_type": "markdown",
"metadata": {
"pycharm": {
"name": "#%%\n"
}
},
"source": [
"### Beyond basic for loops, you can also use it in list comprehensions"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [],
"source": [
"some_list = [x**2 for x in tqdm(10*[0])]"
]
},
{
"cell_type": "markdown",
"metadata": {
"pycharm": {
"name": "#%%\n"
}
},
"source": [
"### You can even use it with multiprocessing\n",
"https://stackoverflow.com/questions/41920124/multiprocessing-use-tqdm-to-display-a-progress-bar"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### If you’re iterating over a generator, tqdm won’t know the length and the progress bar will be more limited but if you know or can calculate the total length you can supply that as an argument"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# generator expressions are surrounded by parenthesis ()\n",
"generator = (x**2 for x in [1, 2, 3, 4])\n",
"# print(next(generator))\n",
"\n",
"some_list = [x for x in tqdm(generator, total=4)]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Jupyter Notebook Shortcuts"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"- Esc will take you into command mode where you can navigate around your notebook with arrow keys.\n",
"- While in command mode:\n",
" - A to insert a new cell above the current cell, B to insert a new cell below.\n",
" - M to change the current cell to Markdown, Y to change it back to code\n",
" - D + D (press the key twice) to delete the current cell\n",
" - Enter will take you from command mode back into edit mode for the given cell.\n",
"- Shift + Tab will show you the Docstring (documentation) for the the object you have just typed in a code cell – you can keep pressing this short cut to cycle through a few modes of documentation.\n",
"- Ctrl + Shift + - will split the current cell into two from where your cursor is.\n",
"- Esc + O Toggle cell output.\n",
"- Select Multiple Cells:\n",
" - Shift + J or Shift + Down selects the next sell in a downwards direction. You can also select sells in an upwards direction by using Shift + K or Shift + Up.\n",
" - Once cells are selected, you can then delete / copy / cut / paste / run them as a batch. This is helpful when you need to move parts of a notebook.\n",
" - You can also use Shift + M to merge multiple cells."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"pycharm": {
"is_executing": false,
"name": "#%%\n"
}
},
"outputs": [],
"source": [
"from IPython.display import IFrame, HTML, YouTubeVideo\n",
"# YouTubeVideo(\"ZbrRrXiWBKc\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"pycharm": {
"is_executing": false,
"name": "#%%\n"
}
},
"outputs": [],
"source": [
"from ipywidgets import FloatSlider, interactive, IntSlider"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"pycharm": {
"is_executing": false,
"name": "#%%\n"
}
},
"outputs": [],
"source": [
"def simple_ex(amplitude=2.0, phase=0.0):\n",
" x = np.linspace(-2*np.pi, 2*np.pi, 1000)\n",
" y = amplitude * np.sin(x + phase)\n",
" plt.rcParams['figure.figsize'] = 8,6\n",
" plt.figure()\n",
" plt.plot(x, y)\n",
" plt.xlim(-3, 3)\n",
" plt.ylim(-2*np.pi, 2*np.pi)\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"pycharm": {
"is_executing": false,
"name": "#%%\n"
}
},
"outputs": [],
"source": [
"amplitude_slider = FloatSlider(value=2.0, min=-10, max=10.0, step=.05)\n",
"phase_slider = FloatSlider(value=0.0, min=-np.pi, max=np.pi, step=.05)\n",
"\n",
"w = interactive(simple_ex,\n",
" amplitude=amplitude_slider,\n",
" phase=phase_slider\n",
" )"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"pycharm": {
"is_executing": false,
"name": "#%%\n"
}
},
"outputs": [],
"source": [
"import pandas as pd\n",
"data = pd.read_csv('loan_train.csv')\n",
"\n",
"import pandas_profiling\n",
"report = pandas_profiling.ProfileReport(data)\n",
"\n",
"report"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"pycharm": {
"is_executing": false,
"name": "#%%\n"
}
},
"outputs": [],
"source": [
"# print many outputs in the same cell!\n",
"from IPython.core.interactiveshell import InteractiveShell\n",
"InteractiveShell.ast_node_interactivity = \"all\"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"pycharm": {
"is_executing": false,
"name": "#%%\n"
}
},
"outputs": [],
"source": [
"%history -t"
]
},
{
"cell_type": "markdown",
"metadata": {
"pycharm": {
"is_executing": false,
"name": "#%% md\n"
}
},
"source": [
"https://towardsdatascience.com/bringing-the-best-out-of-jupyter-notebooks-for-data-science-f0871519ca29"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [],
"source": [
"\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.4"
},
"pycharm": {
"stem_cell": {
"cell_type": "raw",
"metadata": {
"collapsed": false
},
"source": []
}
}
},
"nbformat": 4,
"nbformat_minor": 1
}
+35
View File
@@ -0,0 +1,35 @@
num_of_gpus: -1
resume_training:
lightning_ckpt:
resume_from_ckpt: False
ckpt_path: "logs/checkpoints/epoch=2.ckpt"
wandb:
resume_wandb_run: False
wandb_run_id: "8uuomodb"
loggers:
wandb:
project: "hackathon_template_test"
team: "kino"
group: None
job_type: "train"
tags: []
log_model: True
offline: False
callbacks:
checkpoint:
monitor: "val_acc"
save_top_k: 1
save_last: True
mode: "max"
early_stop:
monitor: "val_acc"
patience: 100
mode: "max"
printing:
progress_bar_refresh_rate: 5
weights_summary: "top" # "full"
profiler: False
+55
View File
@@ -0,0 +1,55 @@
MNIST_CLASSIFIER_V1:
trainer:
max_epochs: 5
model:
name: "simple_mnist_classifier"
lr: 0.001
weight_decay: 0.000001
input_size: 784 # img size is 28*28*1
output_size: 10
lin1_size: 256
lin2_size: 256
lin3_size: 128
dataset:
name: "MNISTDataModule"
batch_size: 64
train_val_split_ratio: 0.9
CIFAR10_CLASSIFIER_V1:
trainer:
max_epochs: 5
gradient_clip_val: 0.5
accumulate_grad_batches: 1
model:
name: "transfer_learning_img_classifier"
lr: 0.001
weight_decay: 0.000001
output_size: 10
lin1_size: 256
lin2_size: 128
dataset:
name: "CIFAR10DataModule"
batch_size: 64
train_val_split_ratio: 0.9
num_workers: 1
pin_memory: False
CIFAR10_CLASSIFIER_V2:
trainer:
max_epochs: 10
gradient_clip_val: 0.5
accumulate_grad_batches: 2
limit_train_batches: 1.0
model:
name: "transfer_learning_img_classifier"
lr: 0.002
weight_decay: 0.00001
output_size: 10
lin1_size: 512
lin2_size: 256
dataset:
name: "CIFAR10DataModule"
batch_size: 256
train_val_split_ratio: 0.9
num_workers: 4
pin_memory: True
+55 -45
View File
@@ -6,84 +6,94 @@ from lightning_modules.init_utils import *
from lightning_modules.callbacks import * from lightning_modules.callbacks import *
def train(config, model_config): def train(project_config, run_config):
# Init lightning model # Init PyTorch Lightning model ⚡
lit_model = init_lit_model(model_config) lit_model = init_lit_model(model_config=run_config["model"])
# Init lightning datamodule # Init PyTorch Lightning datamodule ⚡
datamodule = init_datamodule(model_config) datamodule = init_datamodule(dataset_config=run_config["dataset"])
# Init logger # Init Weights&Biases logger
logger = init_wandb_logger(config, lit_model, datamodule) logger = init_wandb_logger(project_config, run_config, lit_model, datamodule)
# Init callbacks # Init checkpoint and early stoping callbacks
callbacks = init_main_callbacks(config) callbacks = init_main_callbacks(project_config)
# Add your custom callbacks
callbacks.extend([ callbacks.extend([
# MetricsHeatmapLoggerCallback(), # MetricsHeatmapLoggerCallback(),
# UnfreezeModelCallback(wait_epochs=5), # UnfreezeModelCallback(wait_epochs=5),
# ImagePredictionLoggerCallback(datamodule=datamodule),
SaveCodeToWandbCallback(wandb_save_dir=logger.save_dir, lit_model=lit_model), SaveCodeToWandbCallback(wandb_save_dir=logger.save_dir, lit_model=lit_model),
# SaveOnnxModelToWandbCallback(datamodule=datamodule, save_dir=logger.save_dir)
]) ])
# Init trainer # Init PyTorch Lightning trainer ⚡
trainer = pl.Trainer( trainer = pl.Trainer(
# whether to use gpu and how many
gpus=project_config["num_of_gpus"],
# experiment logging
logger=logger, logger=logger,
# useful callbacks
callbacks=callbacks, callbacks=callbacks,
gpus=config["num_of_gpus"],
resume_from_checkpoint=config["resume_training"]["lightning_ckpt"]["ckpt_path"] # resuming training from checkpoint
if config["resume_training"]["lightning_ckpt"]["resume_from_ckpt"] else None, resume_from_checkpoint=project_config["resume_training"]["lightning_ckpt"]["ckpt_path"]
if project_config["resume_training"]["lightning_ckpt"]["resume_from_ckpt"] else None,
# model related: # print related
max_epochs=model_config["max_epochs"], progress_bar_refresh_rate=project_config["printing"]["progress_bar_refresh_rate"],
accumulate_grad_batches=model_config["accumulate_grad_batches"], profiler=SimpleProfiler() if project_config["printing"]["profiler"] else None,
gradient_clip_val=model_config["gradient_clip_val"], weights_summary=project_config["printing"]["weights_summary"],
# print related: # run related
progress_bar_refresh_rate=config["printing"]["progress_bar_refresh_rate"], max_epochs=run_config["trainer"]["max_epochs"],
profiler=SimpleProfiler() if config["printing"]["profiler"] else None, min_epochs=run_config["trainer"].get("min_epochs", 1),
weights_summary=config["printing"]["weights_summary"], accumulate_grad_batches=run_config["trainer"].get("accumulate_grad_batches", 1),
gradient_clip_val=run_config["trainer"].get("gradient_clip_val", 0.5),
# these are mostly for debugging (read TIPS.md for explanation): # these are mostly for debugging (read TIPS.md for explanation)
fast_dev_run=False, fast_dev_run=run_config["trainer"].get("fast_dev_run", False),
num_sanity_val_steps=3, limit_train_batches=run_config["trainer"].get("limit_train_batches", 1.0),
limit_train_batches=1.0, limit_val_batches=run_config["trainer"].get("limit_val_batches", 1.0),
limit_val_batches=1.0, limit_test_batches=run_config["trainer"].get("limit_test_batches", 1.0),
limit_test_batches=1.0, val_check_interval=run_config["trainer"].get("val_check_interval", 1.0),
val_check_interval=1.0, num_sanity_val_steps=run_config["trainer"].get("fast_dev_run", 3),
# default log dir if no logger is found
default_root_dir="logs/lightning_logs", default_root_dir="logs/lightning_logs",
) )
# Test before training # Evaluate model on test set before training
# trainer.test(model=lit_model, datamodule=datamodule) # trainer.test(model=lit_model, datamodule=datamodule)
# Save checkpoint # Train the model
# trainer.save_checkpoint("random.ckpt")
# Train the model ⚡
trainer.fit(model=lit_model, datamodule=datamodule) trainer.fit(model=lit_model, datamodule=datamodule)
# Evaluate model on test set # Evaluate model on test set after training
trainer.test() trainer.test()
def load_config(): def load_config(path):
with open("config.yaml", "r") as ymlfile: with open(path, "r") as ymlfile:
config = yaml.load(ymlfile, Loader=yaml.FullLoader) config = yaml.load(ymlfile, Loader=yaml.FullLoader)
return config return config
if __name__ == "__main__": if __name__ == "__main__":
conf = load_config()
# --------------------------------------- CHOOSE YOUR MODEL HEREEE ↓↓↓ --------------------------------------- # # --------------------------------------- CHOOSE YOUR RUN CONFIG HEREE --------------------------------------- #
# --------------------------------------------------- ↓↓↓ ---------------------------------------------------- #
# ------------------------------------------------------------------------------------------------------------ #
# RUN_CONFIG = "MNIST_CLASSIFIER_V1"
# RUN_CONFIG = "CIFAR10_CLASSIFIER_V1"
RUN_CONFIG = "CIFAR10_CLASSIFIER_V2"
# ------------------------------------------------------------------------------------------------------------ #
# --------------------------------------------------- ↑↑↑ ---------------------------------------------------- #
# --------------------------------------- CHOOSE YOUR RUN CONFIG HEREE --------------------------------------- #
model_conf = conf["model_configs"]["simple_mnist_classifier_v1"] project_conf = load_config("project_config.yaml")
# model_conf = conf["model_configs"]["transfer_learning_cifar10_classifier_v1"] run_conf = load_config("run_configs.yaml")[RUN_CONFIG]
# --------------------------------------- CHOOSE YOUR MODEL HEREEE ↑↑↑ --------------------------------------- # train(project_config=project_conf, run_config=run_conf)
train(config=conf, model_config=model_conf)
@@ -1,5 +1,5 @@
from models.transfer_learning_img_classifier.lightning_module import LitModel from models.transfer_learning_img_classifier.lightning_module import LitModel
from lightning_modules.data_modules import transforms from data_modules import transforms
from PIL import Image from PIL import Image
@@ -23,7 +23,7 @@ def predict():
img = Image.open("../../example_img.png").convert("RGB") img = Image.open("../../example_img.png").convert("RGB")
# preprocess # preprocess
img = transforms.imagenet_test_preprocess(img) img = transforms.imagenet_test_transforms(img)
img = img.reshape((1, *img.size())) # reshape to form batch of size 1 img = img.reshape((1, *img.size())) # reshape to form batch of size 1
# inference # inference