Spaces:
Runtime error
Runtime error
Commit
·
d6c2823
1
Parent(s):
34eb6c0
added comet logging
Browse files
src/scripts/train.py
CHANGED
@@ -1,11 +1,13 @@
|
|
1 |
import os
|
2 |
import argparse
|
|
|
3 |
from src.utils.config_loader import Config
|
4 |
from src.utils import config_loader
|
5 |
from src.utils.script_utils import validate_config
|
6 |
import importlib
|
7 |
from pathlib import Path
|
8 |
-
|
|
|
9 |
|
10 |
def train(args):
|
11 |
config_file_path = args.config_file
|
@@ -17,7 +19,7 @@ def train(args):
|
|
17 |
# set config globally
|
18 |
config_loader.config = config
|
19 |
|
20 |
-
# now
|
21 |
Model = importlib.import_module(f"src.{config.task}.model.models.{config.model}").Model
|
22 |
|
23 |
|
@@ -25,11 +27,30 @@ def train(args):
|
|
25 |
os.makedirs(model_dir,exist_ok=True)
|
26 |
model_save_path = os.path.join(model_dir,"model.weights.h5")
|
27 |
|
28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
29 |
model.train()
|
30 |
model.save(model_save_path)
|
|
|
|
|
|
|
|
|
|
|
31 |
metrics = model.evaluate()
|
32 |
print("Model Evaluation Metrics:",metrics)
|
|
|
|
|
33 |
|
34 |
def main():
|
35 |
parser = argparse.ArgumentParser(description="train model based on config yaml file")
|
|
|
1 |
import os
|
2 |
import argparse
|
3 |
+
from comet_ml import Experiment
|
4 |
from src.utils.config_loader import Config
|
5 |
from src.utils import config_loader
|
6 |
from src.utils.script_utils import validate_config
|
7 |
import importlib
|
8 |
from pathlib import Path
|
9 |
+
from dotenv import load_dotenv
|
10 |
+
load_dotenv()
|
11 |
|
12 |
def train(args):
|
13 |
config_file_path = args.config_file
|
|
|
19 |
# set config globally
|
20 |
config_loader.config = config
|
21 |
|
22 |
+
# now load the model
|
23 |
Model = importlib.import_module(f"src.{config.task}.model.models.{config.model}").Model
|
24 |
|
25 |
|
|
|
27 |
os.makedirs(model_dir,exist_ok=True)
|
28 |
model_save_path = os.path.join(model_dir,"model.weights.h5")
|
29 |
|
30 |
+
|
31 |
+
experiment = Experiment(
|
32 |
+
api_key=os.environ["COMET_API_KEY"],
|
33 |
+
project_name="image-colorization",
|
34 |
+
workspace="anujpanthri",
|
35 |
+
auto_histogram_activation_logging=True,
|
36 |
+
auto_histogram_epoch_rate=True,
|
37 |
+
auto_histogram_gradient_logging=True,
|
38 |
+
auto_histogram_weight_logging=True,
|
39 |
+
auto_param_logging=True,
|
40 |
+
)
|
41 |
+
|
42 |
+
model = Model(experiment=experiment)
|
43 |
model.train()
|
44 |
model.save(model_save_path)
|
45 |
+
|
46 |
+
# log model to comet
|
47 |
+
if "LOCAL_SYSTEM" not in os.environ:
|
48 |
+
experiment.log_model(f"{config.task}_{config.dataset}_{config.model}",model_save_path)
|
49 |
+
|
50 |
metrics = model.evaluate()
|
51 |
print("Model Evaluation Metrics:",metrics)
|
52 |
+
|
53 |
+
experiment.end()
|
54 |
|
55 |
def main():
|
56 |
parser = argparse.ArgumentParser(description="train model based on config yaml file")
|
src/simple_regression_colorization/model/base_model_interface.py
CHANGED
@@ -1,22 +1,88 @@
|
|
1 |
import numpy as np
|
2 |
from abc import ABC, abstractmethod
|
|
|
|
|
|
|
|
|
|
|
3 |
|
4 |
# BaseModel Abstract class
|
5 |
# all the models within this sub_task must inherit this class
|
6 |
|
7 |
class BaseModel(ABC):
|
8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
9 |
def train(self):
|
10 |
-
|
|
|
|
|
11 |
|
12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
13 |
def evaluate(self):
|
14 |
-
|
|
|
|
|
15 |
|
16 |
-
|
17 |
-
|
18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
19 |
|
20 |
-
@abstractmethod
|
21 |
def show_results(self):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
22 |
pass
|
|
|
|
|
|
1 |
import numpy as np
|
2 |
from abc import ABC, abstractmethod
|
3 |
+
from src.simple_regression_colorization.model.dataloaders import get_datasets
|
4 |
+
from src.utils.data_utils import scale_L,scale_AB,rescale_AB,rescale_L,see_batch
|
5 |
+
from src.utils.config_loader import config
|
6 |
+
from skimage.color import lab2rgb
|
7 |
+
from src.simple_regression_colorization.model.callbacks import LogPredictionsCallback
|
8 |
|
9 |
# BaseModel Abstract class
|
10 |
# all the models within this sub_task must inherit this class
|
11 |
|
12 |
class BaseModel(ABC):
|
13 |
+
def __init__(self,path=None,experiment=None):
|
14 |
+
self.init_model()
|
15 |
+
self.load_weights(path)
|
16 |
+
self.experiment = experiment
|
17 |
+
|
18 |
+
def load_weights(self,path=None):
|
19 |
+
if path:
|
20 |
+
self.model.load_weights(path)
|
21 |
+
|
22 |
+
def prepare_data(self):
|
23 |
+
self.train_ds,self.val_ds,self.test_ds = get_datasets()
|
24 |
+
|
25 |
def train(self):
|
26 |
+
|
27 |
+
self.prepare_data()
|
28 |
+
self.model.compile(optimizer="adam",loss="mse",metrics=["mae","acc"])
|
29 |
|
30 |
+
callbacks = [
|
31 |
+
LogPredictionsCallback(self.train_ds,"train_ds",self.experiment),
|
32 |
+
LogPredictionsCallback(self.val_ds,"val_ds",self.experiment),
|
33 |
+
]
|
34 |
+
|
35 |
+
self.history = self.model.fit(self.train_ds,
|
36 |
+
validation_data=self.val_ds,
|
37 |
+
callbacks=callbacks,
|
38 |
+
epochs=config.epochs)
|
39 |
+
|
40 |
+
def save(self,model_path):
|
41 |
+
self.model.save_weights(model_path)
|
42 |
+
|
43 |
+
def predict(self,L_batch):
|
44 |
+
L_batch = scale_L(L_batch)
|
45 |
+
AB_batch = self.model.predict(L_batch,verbose=0)
|
46 |
+
return rescale_AB(AB_batch)
|
47 |
+
|
48 |
def evaluate(self):
|
49 |
+
train_metrics = self.model.evaluate(self.train_ds)
|
50 |
+
val_metrics = self.model.evaluate(self.val_ds)
|
51 |
+
test_metrics = self.model.evaluate(self.test_ds)
|
52 |
|
53 |
+
return {
|
54 |
+
"train": train_metrics,
|
55 |
+
"val": val_metrics,
|
56 |
+
"test": test_metrics,
|
57 |
+
}
|
58 |
+
|
59 |
+
def predict_colors(self,L_batch):
|
60 |
+
AB_batch = self.predict(L_batch)
|
61 |
+
colored_batch = np.concatenate([L_batch,rescale_AB(AB_batch)],axis=-1)
|
62 |
+
colored_batch = lab2rgb(colored_batch) * 255
|
63 |
+
return colored_batch
|
64 |
|
|
|
65 |
def show_results(self):
|
66 |
+
self.prepare_data()
|
67 |
+
|
68 |
+
L_batch,AB_batch = next(iter(self.train_ds))
|
69 |
+
L_batch = L_batch.numpy()
|
70 |
+
AB_pred = self.model.predict(L_batch,verbose=0)
|
71 |
+
see_batch(L_batch,AB_pred,title="Train dataset Results")
|
72 |
+
|
73 |
+
L_batch,AB_batch = next(iter(self.val_ds))
|
74 |
+
L_batch = L_batch.numpy()
|
75 |
+
AB_pred = self.model.predict(L_batch,verbose=0)
|
76 |
+
see_batch(L_batch,AB_pred,title="Val dataset Results")
|
77 |
+
|
78 |
+
L_batch,AB_batch = next(iter(self.test_ds))
|
79 |
+
L_batch = L_batch.numpy()
|
80 |
+
AB_pred = self.model.predict(L_batch,verbose=0)
|
81 |
+
see_batch(L_batch,AB_pred,title="Test dataset Results")
|
82 |
+
|
83 |
+
|
84 |
+
@abstractmethod
|
85 |
+
def init_model(self):
|
86 |
pass
|
87 |
+
|
88 |
+
|
src/simple_regression_colorization/model/callbacks.py
CHANGED
@@ -1 +1,27 @@
|
|
1 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import tensorflow as tf
|
2 |
+
from src.utils.data_utils import rescale_AB,rescale_L
|
3 |
+
from skimage.color import lab2rgb
|
4 |
+
import numpy as np
|
5 |
+
|
6 |
+
class LogPredictionsCallback(tf.keras.callbacks.Callback):
|
7 |
+
def __init__(self,ds,ds_name,experiment=None):
|
8 |
+
self.ds = ds
|
9 |
+
self.ds_name = ds_name
|
10 |
+
self.experiment = experiment
|
11 |
+
|
12 |
+
def on_epoch_end(self, epoch, logs=None):
|
13 |
+
|
14 |
+
L_batch, _ = next(iter(self.ds))
|
15 |
+
AB_batch = self.model.predict(L_batch,verbose=0)
|
16 |
+
colored_batch = np.concatenate([rescale_L(L_batch),rescale_AB(AB_batch)],axis=-1)
|
17 |
+
colored_batch = lab2rgb(colored_batch) * 255
|
18 |
+
|
19 |
+
print(self.ds_name)
|
20 |
+
print("R:",colored_batch[:,:,0].min(),colored_batch[:,:,0].max())
|
21 |
+
print("G:",colored_batch[:,:,1].min(),colored_batch[:,:,1].max())
|
22 |
+
print("B:",colored_batch[:,:,2].min(),colored_batch[:,:,2].max())
|
23 |
+
|
24 |
+
if self.experiment:
|
25 |
+
# log images
|
26 |
+
for i,image in enumerate(colored_batch):
|
27 |
+
self.experiment.log_image(image,name=f"{self.ds_name}_{i}")
|
src/simple_regression_colorization/model/model_utils.py
ADDED
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import tensorflow as tf
|
2 |
+
from tensorflow.keras import layers,Model as keras_Model,Sequential
|
3 |
+
|
4 |
+
def down_block(filters,kernel_size,apply_batch_normalization=True):
|
5 |
+
down = Sequential()
|
6 |
+
down.add(layers.Conv2D(filters,kernel_size,padding="same",strides=2))
|
7 |
+
if apply_batch_normalization:
|
8 |
+
down.add(layers.BatchNormalization())
|
9 |
+
down.add(layers.LeakyReLU())
|
10 |
+
return down
|
11 |
+
|
12 |
+
def up_block(filters,kernel_size,dropout=False):
|
13 |
+
upsample = Sequential()
|
14 |
+
upsample.add(layers.Conv2DTranspose(filters,kernel_size,padding="same",strides=2))
|
15 |
+
if dropout:
|
16 |
+
upsample.add(layers.Dropout(dropout))
|
17 |
+
upsample.add(layers.LeakyReLU())
|
18 |
+
return upsample
|
src/simple_regression_colorization/model/models/model_v1.py
CHANGED
@@ -1,119 +1,34 @@
|
|
1 |
from src.simple_regression_colorization.model.base_model_interface import BaseModel
|
2 |
-
from src.simple_regression_colorization.model.dataloaders import get_datasets
|
3 |
from src.utils.config_loader import config
|
4 |
-
from src.
|
5 |
-
from skimage.color import lab2rgb
|
6 |
import tensorflow as tf
|
7 |
from tensorflow.keras import layers,Model as keras_Model,Sequential
|
8 |
-
import numpy as np
|
9 |
|
10 |
-
def down(filters,kernel_size,apply_batch_normalization=True):
|
11 |
-
down = Sequential()
|
12 |
-
down.add(layers.Conv2D(filters,kernel_size,padding="same",strides=2))
|
13 |
-
if apply_batch_normalization:
|
14 |
-
down.add(layers.BatchNormalization())
|
15 |
-
down.add(layers.LeakyReLU())
|
16 |
-
return down
|
17 |
-
|
18 |
-
def up(filters,kernel_size,dropout=False):
|
19 |
-
upsample = Sequential()
|
20 |
-
upsample.add(layers.Conv2DTranspose(filters,kernel_size,padding="same",strides=2))
|
21 |
-
if dropout:
|
22 |
-
upsample.add(layers.Dropout(dropout))
|
23 |
-
upsample.add(layers.LeakyReLU())
|
24 |
-
return upsample
|
25 |
|
26 |
class Model(BaseModel):
|
27 |
|
28 |
-
def __init__(self
|
29 |
-
|
30 |
-
# load weights (optional)
|
31 |
-
# create dataset loaders
|
32 |
-
# train
|
33 |
-
# predict
|
34 |
-
self.init_model()
|
35 |
-
self.load_weights(path)
|
36 |
-
|
37 |
|
38 |
def init_model(self):
|
39 |
x = layers.Input([config.image_size,config.image_size,1])
|
40 |
-
d1 =
|
41 |
-
d2 =
|
42 |
-
d3 =
|
43 |
-
d4 =
|
44 |
-
d5 =
|
45 |
|
46 |
-
u1 =
|
47 |
u1 = layers.concatenate([u1,d4])
|
48 |
-
u2 =
|
49 |
u2 = layers.concatenate([u2,d3])
|
50 |
-
u3 =
|
51 |
u3 = layers.concatenate([u3,d2])
|
52 |
-
u4 =
|
53 |
u4 = layers.concatenate([u4,d1])
|
54 |
-
u5 =
|
55 |
u5 = layers.concatenate([u5,x])
|
56 |
|
57 |
y = layers.Conv2D(2,(2,2),strides = 1, padding = 'same',activation="tanh")(u5)
|
58 |
|
59 |
-
self.model = keras_Model(x,y,name="UNet")
|
60 |
-
|
61 |
-
|
62 |
-
def load_weights(self,path=None):
|
63 |
-
if path:
|
64 |
-
self.model.load_weights(path)
|
65 |
-
|
66 |
-
def prepare_data(self):
|
67 |
-
self.train_ds,self.val_ds,self.test_ds = get_datasets()
|
68 |
-
|
69 |
-
def train(self):
|
70 |
-
|
71 |
-
self.prepare_data()
|
72 |
-
self.model.compile(optimizer="adam",loss="mse",metrics=["mae","acc"])
|
73 |
-
self.history = self.model.fit(self.train_ds,
|
74 |
-
validation_data=self.val_ds,
|
75 |
-
epochs=config.epochs)
|
76 |
-
|
77 |
-
def save(self,model_path):
|
78 |
-
self.model.save_weights(model_path)
|
79 |
-
|
80 |
-
def predict(self,L_batch):
|
81 |
-
L_batch = scale_L(L_batch)
|
82 |
-
AB_batch = self.model.predict(L_batch,verbose=0)
|
83 |
-
return rescale_AB(AB_batch)
|
84 |
-
|
85 |
-
def evaluate(self):
|
86 |
-
train_metrics = self.model.evaluate(self.train_ds)
|
87 |
-
val_metrics = self.model.evaluate(self.val_ds)
|
88 |
-
test_metrics = self.model.evaluate(self.test_ds)
|
89 |
-
|
90 |
-
return {
|
91 |
-
"train": train_metrics,
|
92 |
-
"val": val_metrics,
|
93 |
-
"test": test_metrics,
|
94 |
-
}
|
95 |
-
|
96 |
-
def predict_colors(self,L_batch):
|
97 |
-
AB_batch = self.predict(L_batch)
|
98 |
-
colored_batch = np.concatenate([L_batch,rescale_AB(AB_batch)],axis=-1)
|
99 |
-
colored_batch = lab2rgb(colored_batch) * 255
|
100 |
-
return colored_batch
|
101 |
-
|
102 |
-
def show_results(self):
|
103 |
-
self.prepare_data()
|
104 |
-
|
105 |
-
L_batch,AB_batch = next(iter(self.train_ds))
|
106 |
-
L_batch = L_batch.numpy()
|
107 |
-
AB_pred = self.model.predict(L_batch,verbose=0)
|
108 |
-
see_batch(L_batch,AB_pred,title="Train dataset Results")
|
109 |
-
|
110 |
-
L_batch,AB_batch = next(iter(self.val_ds))
|
111 |
-
L_batch = L_batch.numpy()
|
112 |
-
AB_pred = self.model.predict(L_batch,verbose=0)
|
113 |
-
see_batch(L_batch,AB_pred,title="Val dataset Results")
|
114 |
-
|
115 |
-
L_batch,AB_batch = next(iter(self.test_ds))
|
116 |
-
L_batch = L_batch.numpy()
|
117 |
-
AB_pred = self.model.predict(L_batch,verbose=0)
|
118 |
-
see_batch(L_batch,AB_pred,title="Test dataset Results")
|
119 |
-
|
|
|
1 |
from src.simple_regression_colorization.model.base_model_interface import BaseModel
|
|
|
2 |
from src.utils.config_loader import config
|
3 |
+
from src.simple_regression_colorization.model.model_utils import up_block,down_block
|
|
|
4 |
import tensorflow as tf
|
5 |
from tensorflow.keras import layers,Model as keras_Model,Sequential
|
|
|
6 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
7 |
|
8 |
class Model(BaseModel):
|
9 |
|
10 |
+
def __init__(self,*args,**kwargs):
|
11 |
+
super().__init__(*args,**kwargs)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
12 |
|
13 |
def init_model(self):
|
14 |
x = layers.Input([config.image_size,config.image_size,1])
|
15 |
+
d1 = down_block(128,(3,3),False)(x)
|
16 |
+
d2 = down_block(128,(3,3),False)(d1)
|
17 |
+
d3 = down_block(256,(3,3),True)(d2)
|
18 |
+
d4 = down_block(512,(3,3),True)(d3)
|
19 |
+
d5 = down_block(512,(3,3),True)(d4)
|
20 |
|
21 |
+
u1 = up_block(512,(3,3))(d5)
|
22 |
u1 = layers.concatenate([u1,d4])
|
23 |
+
u2 = up_block(256,(3,3))(u1)
|
24 |
u2 = layers.concatenate([u2,d3])
|
25 |
+
u3 = up_block(128,(3,3))(u2)
|
26 |
u3 = layers.concatenate([u3,d2])
|
27 |
+
u4 = up_block(128,(3,3))(u3)
|
28 |
u4 = layers.concatenate([u4,d1])
|
29 |
+
u5 = up_block(64,(3,3))(u4)
|
30 |
u5 = layers.concatenate([u5,x])
|
31 |
|
32 |
y = layers.Conv2D(2,(2,2),strides = 1, padding = 'same',activation="tanh")(u5)
|
33 |
|
34 |
+
self.model = keras_Model(x,y,name="UNet")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|