Spaces:
Runtime error
Runtime error
HAMIM-ML
commited on
Commit
·
9bd2271
1
Parent(s):
3b1eb75
model evaluation added
Browse files- config/config.yaml +8 -0
- lightning_logs/version_37/events.out.tfevents.1724745017.Hakim.53748.0 +0 -0
- lightning_logs/version_37/hparams.yaml +7 -0
- lightning_logs/version_38/events.out.tfevents.1724745796.Hakim.53748.1 +0 -0
- lightning_logs/version_38/hparams.yaml +7 -0
- lightning_logs/version_39/events.out.tfevents.1724754294.Hakim.58248.0 +0 -0
- lightning_logs/version_39/hparams.yaml +7 -0
- lightning_logs/version_40/events.out.tfevents.1724755669.Hakim.58248.1 +0 -0
- lightning_logs/version_40/hparams.yaml +7 -0
- main.py +20 -5
- params.yaml +5 -5
- research/model_evaluation.ipynb +507 -0
- scores.json +11 -0
- src/imagecolorization/config/configuration.py +18 -1
- src/imagecolorization/conponents/model_building.py +2 -2
- src/imagecolorization/conponents/model_evaluation.py +221 -0
- src/imagecolorization/entity/config_entity.py +9 -1
- src/imagecolorization/pipeline/stage_05_model_evaluation.py +17 -0
config/config.yaml
CHANGED
@@ -19,5 +19,13 @@ model_trainer:
|
|
19 |
root_dir : artifacts/trained_model
|
20 |
test_data_path : artifacts/data_transformation/test_dataset.pt
|
21 |
train_data_path : artifacts/data_transformation/train_dataset.pt
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
22 |
|
23 |
|
|
|
19 |
root_dir : artifacts/trained_model
|
20 |
test_data_path : artifacts/data_transformation/test_dataset.pt
|
21 |
train_data_path : artifacts/data_transformation/train_dataset.pt
|
22 |
+
|
23 |
+
model_evaluation:
|
24 |
+
test_data: 'artifacts/data_transformation/test_dataset.pt'
|
25 |
+
generator_model: 'artifacts/trained_model/cwgan_generator_final.pt'
|
26 |
+
critic_model: 'artifacts/trained_model/cwgan_critic_final.pt'
|
27 |
+
|
28 |
+
|
29 |
+
|
30 |
|
31 |
|
lightning_logs/version_37/events.out.tfevents.1724745017.Hakim.53748.0
ADDED
Binary file (683 Bytes). View file
|
|
lightning_logs/version_37/hparams.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
display_step: 10
|
2 |
+
in_channels: 1
|
3 |
+
lambda_gp: 10
|
4 |
+
lambda_r1: 10
|
5 |
+
lambda_recon: 100
|
6 |
+
learning_rate: 0.0002
|
7 |
+
out_channels: 2
|
lightning_logs/version_38/events.out.tfevents.1724745796.Hakim.53748.1
ADDED
Binary file (683 Bytes). View file
|
|
lightning_logs/version_38/hparams.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
display_step: 10
|
2 |
+
in_channels: 1
|
3 |
+
lambda_gp: 10
|
4 |
+
lambda_r1: 10
|
5 |
+
lambda_recon: 100
|
6 |
+
learning_rate: 0.0002
|
7 |
+
out_channels: 2
|
lightning_logs/version_39/events.out.tfevents.1724754294.Hakim.58248.0
ADDED
Binary file (683 Bytes). View file
|
|
lightning_logs/version_39/hparams.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
display_step: 10
|
2 |
+
in_channels: 1
|
3 |
+
lambda_gp: 10
|
4 |
+
lambda_r1: 10
|
5 |
+
lambda_recon: 100
|
6 |
+
learning_rate: 0.0002
|
7 |
+
out_channels: 2
|
lightning_logs/version_40/events.out.tfevents.1724755669.Hakim.58248.1
ADDED
Binary file (683 Bytes). View file
|
|
lightning_logs/version_40/hparams.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
display_step: 10
|
2 |
+
in_channels: 1
|
3 |
+
lambda_gp: 10
|
4 |
+
lambda_r1: 10
|
5 |
+
lambda_recon: 100
|
6 |
+
learning_rate: 0.0002
|
7 |
+
out_channels: 2
|
main.py
CHANGED
@@ -2,9 +2,10 @@ from src.imagecolorization.pipeline.stage01_data_ingestion import DataIngestionP
|
|
2 |
from src.imagecolorization.pipeline.stage02_data_transformation import DataTransformationPipeline
|
3 |
from src.imagecolorization.pipeline.stage_03_model_building import ModelBuildingPipeline
|
4 |
from src.imagecolorization.pipeline.stage_04_model_trainer import ModelTrainerPipeline
|
|
|
5 |
from src.imagecolorization.logging import logger
|
6 |
|
7 |
-
STAGE_NAME = 'Data Ingestion
|
8 |
|
9 |
try:
|
10 |
logger.info(f">>>>>> stage {STAGE_NAME} started <<<<<<")
|
@@ -15,7 +16,7 @@ except Exception as e:
|
|
15 |
logger.exception(e)
|
16 |
raise e
|
17 |
|
18 |
-
STAGE_NAME = 'Data Tranasformation
|
19 |
|
20 |
try:
|
21 |
logger.info(f">>>>>> stage {STAGE_NAME} started <<<<<<")
|
@@ -27,7 +28,7 @@ except Exception as e:
|
|
27 |
raise e
|
28 |
|
29 |
|
30 |
-
STAGE_NAME = 'Model Building
|
31 |
|
32 |
try:
|
33 |
logger.info(f">>>>>> stage {STAGE_NAME} started <<<<<<")
|
@@ -39,7 +40,7 @@ except Exception as e:
|
|
39 |
raise e
|
40 |
|
41 |
|
42 |
-
STAGE_NAME = 'Model Training
|
43 |
|
44 |
try:
|
45 |
logger.info(f">>>>>> stage {STAGE_NAME} started <<<<<<")
|
@@ -48,4 +49,18 @@ try:
|
|
48 |
logger.info(f">>>>>> stage {STAGE_NAME} completed <<<<<<\n\nx==========x")
|
49 |
except Exception as e:
|
50 |
logger.exception(e)
|
51 |
-
raise e
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
from src.imagecolorization.pipeline.stage02_data_transformation import DataTransformationPipeline
|
3 |
from src.imagecolorization.pipeline.stage_03_model_building import ModelBuildingPipeline
|
4 |
from src.imagecolorization.pipeline.stage_04_model_trainer import ModelTrainerPipeline
|
5 |
+
from src.imagecolorization.pipeline.stage_05_model_evaluation import ModelEvaluationPipeLine
|
6 |
from src.imagecolorization.logging import logger
|
7 |
|
8 |
+
STAGE_NAME = 'Data Ingestion Stage'
|
9 |
|
10 |
try:
|
11 |
logger.info(f">>>>>> stage {STAGE_NAME} started <<<<<<")
|
|
|
16 |
logger.exception(e)
|
17 |
raise e
|
18 |
|
19 |
+
STAGE_NAME = 'Data Tranasformation Stage'
|
20 |
|
21 |
try:
|
22 |
logger.info(f">>>>>> stage {STAGE_NAME} started <<<<<<")
|
|
|
28 |
raise e
|
29 |
|
30 |
|
31 |
+
STAGE_NAME = 'Model Building Stage'
|
32 |
|
33 |
try:
|
34 |
logger.info(f">>>>>> stage {STAGE_NAME} started <<<<<<")
|
|
|
40 |
raise e
|
41 |
|
42 |
|
43 |
+
STAGE_NAME = 'Model Training Stage'
|
44 |
|
45 |
try:
|
46 |
logger.info(f">>>>>> stage {STAGE_NAME} started <<<<<<")
|
|
|
49 |
logger.info(f">>>>>> stage {STAGE_NAME} completed <<<<<<\n\nx==========x")
|
50 |
except Exception as e:
|
51 |
logger.exception(e)
|
52 |
+
raise e
|
53 |
+
|
54 |
+
|
55 |
+
|
56 |
+
STAGE_NAME = 'Model Evaluation Stage'
|
57 |
+
|
58 |
+
try:
|
59 |
+
logger.info(f">>>>>> stage {STAGE_NAME} started <<<<<<")
|
60 |
+
model_trianer = ModelEvaluationPipeLine()
|
61 |
+
model_trianer.main()
|
62 |
+
logger.info(f">>>>>> stage {STAGE_NAME} completed <<<<<<\n\nx==========x")
|
63 |
+
except Exception as e:
|
64 |
+
logger.exception(e)
|
65 |
+
raise e
|
66 |
+
|
params.yaml
CHANGED
@@ -1,7 +1,7 @@
|
|
1 |
# Data Parameters
|
2 |
BATCH_SIZE: 1
|
3 |
IMAGE_SIZE: [224, 224, 1]
|
4 |
-
DATA_RANGE:
|
5 |
|
6 |
# Convolutional Layer Parameters
|
7 |
KERNEL_SIZE_RES: 3
|
@@ -14,7 +14,7 @@ SCALE_FACTOR: 2
|
|
14 |
DIM: 1
|
15 |
|
16 |
# Dropout Parameters
|
17 |
-
DROPOUT_RATE: 0.
|
18 |
|
19 |
# Generator Parameters
|
20 |
KERNEL_SIZE_GENERATOR: 1
|
@@ -25,7 +25,7 @@ OUTPUT_CHANNELS: 2
|
|
25 |
IN_CHANNELS: 3
|
26 |
|
27 |
# model train
|
28 |
-
LEARNING_RATE : 2e-
|
29 |
LAMBDA_RECON : 100
|
30 |
-
DISPLAY_STEP :
|
31 |
-
EPOCH :
|
|
|
1 |
# Data Parameters
|
2 |
BATCH_SIZE: 1
|
3 |
IMAGE_SIZE: [224, 224, 1]
|
4 |
+
DATA_RANGE: 3000
|
5 |
|
6 |
# Convolutional Layer Parameters
|
7 |
KERNEL_SIZE_RES: 3
|
|
|
14 |
DIM: 1
|
15 |
|
16 |
# Dropout Parameters
|
17 |
+
DROPOUT_RATE: 0.3
|
18 |
|
19 |
# Generator Parameters
|
20 |
KERNEL_SIZE_GENERATOR: 1
|
|
|
25 |
IN_CHANNELS: 3
|
26 |
|
27 |
# model train
|
28 |
+
LEARNING_RATE : 2e-5
|
29 |
LAMBDA_RECON : 100
|
30 |
+
DISPLAY_STEP : 11
|
31 |
+
EPOCH : 2
|
research/model_evaluation.ipynb
ADDED
@@ -0,0 +1,507 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": 1,
|
6 |
+
"metadata": {},
|
7 |
+
"outputs": [],
|
8 |
+
"source": [
|
9 |
+
"import os\n",
|
10 |
+
"os.chdir('../')"
|
11 |
+
]
|
12 |
+
},
|
13 |
+
{
|
14 |
+
"cell_type": "code",
|
15 |
+
"execution_count": 2,
|
16 |
+
"metadata": {},
|
17 |
+
"outputs": [
|
18 |
+
{
|
19 |
+
"data": {
|
20 |
+
"text/plain": [
|
21 |
+
"'c:\\\\mlops project\\\\image-colorization-mlops'"
|
22 |
+
]
|
23 |
+
},
|
24 |
+
"execution_count": 2,
|
25 |
+
"metadata": {},
|
26 |
+
"output_type": "execute_result"
|
27 |
+
}
|
28 |
+
],
|
29 |
+
"source": [
|
30 |
+
"%pwd"
|
31 |
+
]
|
32 |
+
},
|
33 |
+
{
|
34 |
+
"cell_type": "code",
|
35 |
+
"execution_count": 3,
|
36 |
+
"metadata": {},
|
37 |
+
"outputs": [],
|
38 |
+
"source": [
|
39 |
+
"from dataclasses import dataclass\n",
|
40 |
+
"from pathlib import Path\n",
|
41 |
+
"\n",
|
42 |
+
"@dataclass(frozen=True)\n",
|
43 |
+
"class ModelEvalutaionConfig:\n",
|
44 |
+
" test_data : Path\n",
|
45 |
+
" generator_model : Path\n",
|
46 |
+
" critic_model : Path\n",
|
47 |
+
" all_params: dict"
|
48 |
+
]
|
49 |
+
},
|
50 |
+
{
|
51 |
+
"cell_type": "code",
|
52 |
+
"execution_count": 7,
|
53 |
+
"metadata": {},
|
54 |
+
"outputs": [],
|
55 |
+
"source": [
|
56 |
+
"from src.imagecolorization.constants import *\n",
|
57 |
+
"from src.imagecolorization.utils.common import read_yaml, create_directories, save_json\n",
|
58 |
+
"\n",
|
59 |
+
"class ConfigurationManager:\n",
|
60 |
+
" def __init__(self, config_filepath=CONFIG_FILE_PATH, params_filepath=PARAMS_FILE_PATH):\n",
|
61 |
+
" self.config = read_yaml(config_filepath)\n",
|
62 |
+
" self.params = read_yaml(params_filepath)\n",
|
63 |
+
" create_directories([self.config.artifacts_root])\n",
|
64 |
+
" \n",
|
65 |
+
" \n",
|
66 |
+
" def get_model_evaluation_config(self) -> ModelEvalutaionConfig:\n",
|
67 |
+
" config = self.config.model_evaluation \n",
|
68 |
+
" params = self.params\n",
|
69 |
+
"\n",
|
70 |
+
" model_evaluation_config = ModelEvalutaionConfig(\n",
|
71 |
+
" \n",
|
72 |
+
" test_data=config.test_data,\n",
|
73 |
+
" generator_model=config.generator_model,\n",
|
74 |
+
" critic_model=config.critic_model,\n",
|
75 |
+
" all_params = params\n",
|
76 |
+
" \n",
|
77 |
+
" )\n",
|
78 |
+
"\n",
|
79 |
+
" return model_evaluation_config\n"
|
80 |
+
]
|
81 |
+
},
|
82 |
+
{
|
83 |
+
"cell_type": "code",
|
84 |
+
"execution_count": 5,
|
85 |
+
"metadata": {},
|
86 |
+
"outputs": [],
|
87 |
+
"source": [
|
88 |
+
"import torch\n",
|
89 |
+
"from torch.utils.data import DataLoader\n",
|
90 |
+
"import mlflow\n",
|
91 |
+
"import dagshub\n",
|
92 |
+
"from tqdm.notebook import tqdm\n",
|
93 |
+
"import json\n",
|
94 |
+
"import os\n",
|
95 |
+
"import logging\n",
|
96 |
+
"from src.imagecolorization.conponents.model_building import Generator, Critic\n",
|
97 |
+
"from src.imagecolorization.conponents.model_trainer import CWGAN\n",
|
98 |
+
"import torch\n",
|
99 |
+
"from torch import nn, optim\n",
|
100 |
+
"from torchvision import transforms\n",
|
101 |
+
"from torch.utils.data import Dataset, DataLoader\n",
|
102 |
+
"from torch.autograd import Variable\n",
|
103 |
+
"from torchvision import models\n",
|
104 |
+
"from torch.nn import functional as F\n",
|
105 |
+
"import torch.utils.data\n",
|
106 |
+
"from torchvision.models.inception import inception_v3\n",
|
107 |
+
"from scipy.stats import entropy\n",
|
108 |
+
"import pytorch_lightning as pl\n",
|
109 |
+
"from torchsummary import summary\n",
|
110 |
+
"from src.imagecolorization.conponents.model_building import Generator, Critic\n",
|
111 |
+
"from src.imagecolorization.conponents.data_tranformation import ImageColorizationDataset\n",
|
112 |
+
"from src.imagecolorization.logging import logger\n",
|
113 |
+
"import gc\n",
|
114 |
+
"import numpy as np\n",
|
115 |
+
"\n",
|
116 |
+
"logger = logging.getLogger(__name__)\n",
|
117 |
+
"\n",
|
118 |
+
"import torch\n",
|
119 |
+
"from torch.utils.data import DataLoader\n",
|
120 |
+
"import mlflow\n",
|
121 |
+
"import dagshub\n",
|
122 |
+
"from tqdm.notebook import tqdm\n",
|
123 |
+
"import json\n",
|
124 |
+
"import os\n",
|
125 |
+
"import logging\n",
|
126 |
+
"from torchvision.models.inception import inception_v3\n",
|
127 |
+
"from torch.nn import functional as F\n",
|
128 |
+
"import numpy as np\n",
|
129 |
+
"from torchvision import transforms\n",
|
130 |
+
"\n",
|
131 |
+
"logger = logging.getLogger(__name__)\n",
|
132 |
+
"\n",
|
133 |
+
"class FID:\n",
|
134 |
+
" def __init__(self, device):\n",
|
135 |
+
" self.device = device\n",
|
136 |
+
" self.inception = inception_v3(pretrained=True, transform_input=False).to(self.device)\n",
|
137 |
+
" self.inception.eval()\n",
|
138 |
+
" self.resize = transforms.Resize((299, 299))\n",
|
139 |
+
"\n",
|
140 |
+
" def convert_to_three_channels(self, images):\n",
|
141 |
+
" if images.shape[1] == 2:\n",
|
142 |
+
" images = torch.cat((images, images[:, :1, :, :]), dim=1) # Duplicate one channel\n",
|
143 |
+
" return images\n",
|
144 |
+
"\n",
|
145 |
+
" def preprocess_images(self, images):\n",
|
146 |
+
" images = self.convert_to_three_channels(images)\n",
|
147 |
+
" images = images.to(self.device)\n",
|
148 |
+
" images = self.resize(images)\n",
|
149 |
+
" return images\n",
|
150 |
+
"\n",
|
151 |
+
" def calculate_fid(self, real_images, generated_images):\n",
|
152 |
+
" batch_size = 32\n",
|
153 |
+
" real_features_list = []\n",
|
154 |
+
" generated_features_list = []\n",
|
155 |
+
"\n",
|
156 |
+
" for i in range(0, len(real_images), batch_size):\n",
|
157 |
+
" real_batch = self.preprocess_images(real_images[i:i+batch_size])\n",
|
158 |
+
" generated_batch = self.preprocess_images(generated_images[i:i+batch_size])\n",
|
159 |
+
"\n",
|
160 |
+
" with torch.no_grad():\n",
|
161 |
+
" real_features = self.inception(real_batch).view(real_batch.size(0), -1)\n",
|
162 |
+
" generated_features = self.inception(generated_batch).view(generated_batch.size(0), -1)\n",
|
163 |
+
"\n",
|
164 |
+
" real_features_list.append(real_features.cpu())\n",
|
165 |
+
" generated_features_list.append(generated_features.cpu())\n",
|
166 |
+
"\n",
|
167 |
+
" real_features = torch.cat(real_features_list, dim=0)\n",
|
168 |
+
" generated_features = torch.cat(generated_features_list, dim=0)\n",
|
169 |
+
"\n",
|
170 |
+
" mu_diff = real_features.mean(dim=0) - generated_features.mean(dim=0)\n",
|
171 |
+
" sigma_diff = real_features.std(dim=0) - generated_features.std(dim=0)\n",
|
172 |
+
"\n",
|
173 |
+
" fid = mu_diff.pow(2).sum() + sigma_diff.pow(2).sum()\n",
|
174 |
+
" return fid.item()\n",
|
175 |
+
"\n",
|
176 |
+
"class InceptionScore:\n",
|
177 |
+
" def __init__(self, device):\n",
|
178 |
+
" self.device = device\n",
|
179 |
+
" self.inception = inception_v3(pretrained=True, transform_input=False).to(self.device)\n",
|
180 |
+
" self.inception.eval()\n",
|
181 |
+
" self.resize = transforms.Resize((299, 299))\n",
|
182 |
+
"\n",
|
183 |
+
" def convert_to_three_channels(self, images):\n",
|
184 |
+
" if images.shape[1] == 2: # If the input has 2 channels\n",
|
185 |
+
" images = torch.cat((images, images[:, :1, :, :]), dim=1) # Duplicate one channel\n",
|
186 |
+
" return images\n",
|
187 |
+
"\n",
|
188 |
+
" def preprocess_images(self, images):\n",
|
189 |
+
" images = self.convert_to_three_channels(images)\n",
|
190 |
+
" images = images.to(self.device)\n",
|
191 |
+
" images = self.resize(images)\n",
|
192 |
+
" return images\n",
|
193 |
+
"\n",
|
194 |
+
" def calculate_is(self, images):\n",
|
195 |
+
" batch_size = 1\n",
|
196 |
+
" splits = 10\n",
|
197 |
+
" preds = []\n",
|
198 |
+
"\n",
|
199 |
+
" for i in range(0, len(images), batch_size):\n",
|
200 |
+
" batch = self.preprocess_images(images[i:i+batch_size])\n",
|
201 |
+
" with torch.no_grad():\n",
|
202 |
+
" pred = F.softmax(self.inception(batch), dim=1)\n",
|
203 |
+
" preds.append(pred.cpu().numpy())\n",
|
204 |
+
"\n",
|
205 |
+
" preds = np.concatenate(preds, axis=0)\n",
|
206 |
+
" n_images = preds.shape[0]\n",
|
207 |
+
"\n",
|
208 |
+
" split_scores = []\n",
|
209 |
+
" for k in range(splits):\n",
|
210 |
+
" part = preds[k * (n_images // splits): (k + 1) * (n_images // splits), :]\n",
|
211 |
+
" py = np.mean(part, axis=0)\n",
|
212 |
+
" scores = []\n",
|
213 |
+
" for i in range(part.shape[0]):\n",
|
214 |
+
" pyx = part[i, :]\n",
|
215 |
+
" scores.append(entropy(pyx, py))\n",
|
216 |
+
" split_scores.append(np.exp(np.mean(scores)))\n",
|
217 |
+
"\n",
|
218 |
+
" return np.mean(split_scores), np.std(split_scores)\n",
|
219 |
+
"\n",
|
220 |
+
"class ModelEvaluation:\n",
|
221 |
+
" def __init__(self, config):\n",
|
222 |
+
" self.config = config\n",
|
223 |
+
" self.device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
224 |
+
" self.generator = None\n",
|
225 |
+
" self.critic = None\n",
|
226 |
+
"\n",
|
227 |
+
" def load_model(self):\n",
|
228 |
+
" self.generator = Generator(input_channel=1, output_channel=2).to(self.device)\n",
|
229 |
+
" self.critic = Critic(in_channels=3).to(self.device)\n",
|
230 |
+
"\n",
|
231 |
+
" self.generator.load_state_dict(torch.load(self.config.generator_model))\n",
|
232 |
+
" self.critic.load_state_dict(torch.load(self.config.critic_model))\n",
|
233 |
+
"\n",
|
234 |
+
" self.generator.eval()\n",
|
235 |
+
" self.critic.eval()\n",
|
236 |
+
"\n",
|
237 |
+
" logger.info(\"Model loaded successfully.\")\n",
|
238 |
+
"\n",
|
239 |
+
" def load_data(self):\n",
|
240 |
+
" self.test_dataset = torch.load(self.config.test_data)\n",
|
241 |
+
" self.test_dataloader = DataLoader(\n",
|
242 |
+
" self.test_dataset, \n",
|
243 |
+
" batch_size=self.config.all_params.BATCH_SIZE, \n",
|
244 |
+
" shuffle=True,\n",
|
245 |
+
" )\n",
|
246 |
+
"\n",
|
247 |
+
" def evaluate_model(self):\n",
|
248 |
+
" is_calculator = InceptionScore(self.device)\n",
|
249 |
+
" fid_calculator = FID(self.device)\n",
|
250 |
+
"\n",
|
251 |
+
" all_preds = []\n",
|
252 |
+
" all_real = []\n",
|
253 |
+
"\n",
|
254 |
+
" with torch.no_grad():\n",
|
255 |
+
" for batch in tqdm(self.test_dataloader, desc=\"Evaluating\", unit=\"batch\"):\n",
|
256 |
+
" real, condition = batch\n",
|
257 |
+
" real, condition = real.to(self.device), condition.to(self.device)\n",
|
258 |
+
" fake = self.generator(condition)\n",
|
259 |
+
" all_preds.append(fake.cpu())\n",
|
260 |
+
" all_real.append(real.cpu())\n",
|
261 |
+
"\n",
|
262 |
+
" all_preds = torch.cat(all_preds, dim=0)\n",
|
263 |
+
" all_real = torch.cat(all_real, dim=0)\n",
|
264 |
+
"\n",
|
265 |
+
" print(\"Calculating Inception Score for real images...\")\n",
|
266 |
+
" mean_real_is, std_real_is = is_calculator.calculate_is(all_real)\n",
|
267 |
+
" print(\"Calculating Inception Score for generated images...\")\n",
|
268 |
+
" mean_fake_is, std_fake_is = is_calculator.calculate_is(all_preds)\n",
|
269 |
+
"\n",
|
270 |
+
" print(\"Calculating Fréchet Inception Distance...\")\n",
|
271 |
+
" fid_value = fid_calculator.calculate_fid(all_real, all_preds)\n",
|
272 |
+
"\n",
|
273 |
+
" results = {\n",
|
274 |
+
" \"inception_score_real\": {\"mean\": float(mean_real_is), \"std\": float(std_real_is)},\n",
|
275 |
+
" \"inception_score_fake\": {\"mean\": float(mean_fake_is), \"std\": float(std_fake_is)},\n",
|
276 |
+
" \"fid\": float(fid_value)\n",
|
277 |
+
" }\n",
|
278 |
+
" return results\n",
|
279 |
+
"\n",
|
280 |
+
" def save_scores(self, results):\n",
|
281 |
+
" save_json(path=Path('scores.json'), data=results)\n",
|
282 |
+
"\n",
|
283 |
+
" def log_to_mlflow(self, results):\n",
|
284 |
+
" dagshub.init(repo_owner='HAKIM-ML', repo_name='image-colorization-mlops', mlflow=True)\n",
|
285 |
+
"\n",
|
286 |
+
" with mlflow.start_run():\n",
|
287 |
+
" # Log all parameters\n",
|
288 |
+
" for key, value in self.config.all_params.items():\n",
|
289 |
+
" mlflow.log_param(key, value)\n",
|
290 |
+
"\n",
|
291 |
+
" # Log metrics\n",
|
292 |
+
" mlflow.log_metric('inception_score_real_mean', results['inception_score_real']['mean'])\n",
|
293 |
+
" mlflow.log_metric('inception_score_fake_mean', results['inception_score_fake']['mean'])\n",
|
294 |
+
" mlflow.log_metric('fid', results['fid'])\n",
|
295 |
+
"\n",
|
296 |
+
" # Log the JSON file as an artifact\n",
|
297 |
+
" mlflow.log_artifact('scores.json')\n",
|
298 |
+
"\n",
|
299 |
+
" def run(self):\n",
|
300 |
+
" self.load_model()\n",
|
301 |
+
" self.load_data()\n",
|
302 |
+
" results = self.evaluate_model()\n",
|
303 |
+
" self.save_scores(results)\n",
|
304 |
+
" self.log_to_mlflow(results)\n"
|
305 |
+
]
|
306 |
+
},
|
307 |
+
{
|
308 |
+
"cell_type": "code",
|
309 |
+
"execution_count": 8,
|
310 |
+
"metadata": {},
|
311 |
+
"outputs": [
|
312 |
+
{
|
313 |
+
"name": "stdout",
|
314 |
+
"output_type": "stream",
|
315 |
+
"text": [
|
316 |
+
"[2024-08-27 19:55:58,492: INFO: common: yaml file: config\\config.yaml loaded successfully]\n",
|
317 |
+
"[2024-08-27 19:55:58,497: INFO: common: yaml file: params.yaml loaded successfully]\n",
|
318 |
+
"[2024-08-27 19:55:58,498: INFO: common: created directory at: artifacts]\n",
|
319 |
+
"[2024-08-27 19:55:59,527: INFO: 1629019639: Model loaded successfully.]\n"
|
320 |
+
]
|
321 |
+
},
|
322 |
+
{
|
323 |
+
"name": "stderr",
|
324 |
+
"output_type": "stream",
|
325 |
+
"text": [
|
326 |
+
"C:\\Users\\azizu\\AppData\\Local\\Temp\\ipykernel_54388\\1629019639.py:144: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature.\n",
|
327 |
+
" self.generator.load_state_dict(torch.load(self.config.generator_model))\n",
|
328 |
+
"C:\\Users\\azizu\\AppData\\Local\\Temp\\ipykernel_54388\\1629019639.py:145: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature.\n",
|
329 |
+
" self.critic.load_state_dict(torch.load(self.config.critic_model))\n",
|
330 |
+
"C:\\Users\\azizu\\AppData\\Local\\Temp\\ipykernel_54388\\1629019639.py:153: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature.\n",
|
331 |
+
" self.test_dataset = torch.load(self.config.test_data)\n",
|
332 |
+
"c:\\Users\\azizu\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages\\torchvision\\models\\_utils.py:208: UserWarning: The parameter 'pretrained' is deprecated since 0.13 and may be removed in the future, please use 'weights' instead.\n",
|
333 |
+
" warnings.warn(\n",
|
334 |
+
"c:\\Users\\azizu\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages\\torchvision\\models\\_utils.py:223: UserWarning: Arguments other than a weight enum or `None` for 'weights' are deprecated since 0.13 and may be removed in the future. The current behavior is equivalent to passing `weights=Inception_V3_Weights.IMAGENET1K_V1`. You can also use `weights=Inception_V3_Weights.DEFAULT` to get the most up-to-date weights.\n",
|
335 |
+
" warnings.warn(msg)\n"
|
336 |
+
]
|
337 |
+
},
|
338 |
+
{
|
339 |
+
"data": {
|
340 |
+
"application/vnd.jupyter.widget-view+json": {
|
341 |
+
"model_id": "e0c3c8dcf08846e2ad26bd6966770dfa",
|
342 |
+
"version_major": 2,
|
343 |
+
"version_minor": 0
|
344 |
+
},
|
345 |
+
"text/plain": [
|
346 |
+
"Evaluating: 0%| | 0/5000 [00:00<?, ?batch/s]"
|
347 |
+
]
|
348 |
+
},
|
349 |
+
"metadata": {},
|
350 |
+
"output_type": "display_data"
|
351 |
+
},
|
352 |
+
{
|
353 |
+
"name": "stdout",
|
354 |
+
"output_type": "stream",
|
355 |
+
"text": [
|
356 |
+
"Calculating Inception Score for real images...\n",
|
357 |
+
"Calculating Inception Score for generated images...\n",
|
358 |
+
"Calculating Fréchet Inception Distance...\n",
|
359 |
+
"[2024-08-27 20:03:48,138: INFO: common: Json file saved at: scores.json]\n"
|
360 |
+
]
|
361 |
+
},
|
362 |
+
{
|
363 |
+
"data": {
|
364 |
+
"text/html": [
|
365 |
+
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">Accessing as HAKIM-ML\n",
|
366 |
+
"</pre>\n"
|
367 |
+
],
|
368 |
+
"text/plain": [
|
369 |
+
"Accessing as HAKIM-ML\n"
|
370 |
+
]
|
371 |
+
},
|
372 |
+
"metadata": {},
|
373 |
+
"output_type": "display_data"
|
374 |
+
},
|
375 |
+
{
|
376 |
+
"name": "stdout",
|
377 |
+
"output_type": "stream",
|
378 |
+
"text": [
|
379 |
+
"[2024-08-27 20:03:55,975: INFO: helpers: Accessing as HAKIM-ML]\n"
|
380 |
+
]
|
381 |
+
},
|
382 |
+
{
|
383 |
+
"data": {
|
384 |
+
"text/html": [
|
385 |
+
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">Initialized MLflow to track repo <span style=\"color: #008000; text-decoration-color: #008000\">\"HAKIM-ML/image-colorization-mlops\"</span>\n",
|
386 |
+
"</pre>\n"
|
387 |
+
],
|
388 |
+
"text/plain": [
|
389 |
+
"Initialized MLflow to track repo \u001b[32m\"HAKIM-ML/image-colorization-mlops\"\u001b[0m\n"
|
390 |
+
]
|
391 |
+
},
|
392 |
+
"metadata": {},
|
393 |
+
"output_type": "display_data"
|
394 |
+
},
|
395 |
+
{
|
396 |
+
"name": "stdout",
|
397 |
+
"output_type": "stream",
|
398 |
+
"text": [
|
399 |
+
"[2024-08-27 20:04:04,162: INFO: helpers: Initialized MLflow to track repo \"HAKIM-ML/image-colorization-mlops\"]\n"
|
400 |
+
]
|
401 |
+
},
|
402 |
+
{
|
403 |
+
"data": {
|
404 |
+
"text/html": [
|
405 |
+
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">Repository HAKIM-ML/image-colorization-mlops initialized!\n",
|
406 |
+
"</pre>\n"
|
407 |
+
],
|
408 |
+
"text/plain": [
|
409 |
+
"Repository HAKIM-ML/image-colorization-mlops initialized!\n"
|
410 |
+
]
|
411 |
+
},
|
412 |
+
"metadata": {},
|
413 |
+
"output_type": "display_data"
|
414 |
+
},
|
415 |
+
{
|
416 |
+
"name": "stdout",
|
417 |
+
"output_type": "stream",
|
418 |
+
"text": [
|
419 |
+
"[2024-08-27 20:04:04,166: INFO: helpers: Repository HAKIM-ML/image-colorization-mlops initialized!]\n"
|
420 |
+
]
|
421 |
+
},
|
422 |
+
{
|
423 |
+
"name": "stderr",
|
424 |
+
"output_type": "stream",
|
425 |
+
"text": [
|
426 |
+
"2024/08/27 20:04:24 INFO mlflow.tracking._tracking_service.client: 🏃 View run grandiose-rat-650 at: https://dagshub.com/HAKIM-ML/image-colorization-mlops.mlflow/#/experiments/0/runs/593e3211953d43359f8810e4d3b21738.\n",
|
427 |
+
"2024/08/27 20:04:24 INFO mlflow.tracking._tracking_service.client: 🧪 View experiment at: https://dagshub.com/HAKIM-ML/image-colorization-mlops.mlflow/#/experiments/0.\n"
|
428 |
+
]
|
429 |
+
}
|
430 |
+
],
|
431 |
+
"source": [
|
432 |
+
"\n",
|
433 |
+
"try:\n",
|
434 |
+
" config_manager = ConfigurationManager()\n",
|
435 |
+
" model_evaluation_config = config_manager.get_model_evaluation_config()\n",
|
436 |
+
" model_evaluation = ModelEvaluation(config=model_evaluation_config)\n",
|
437 |
+
" model_evaluation.run()\n",
|
438 |
+
"except Exception as e:\n",
|
439 |
+
" logger.exception(\"An error occurred during model evaluation\")\n",
|
440 |
+
" raise e"
|
441 |
+
]
|
442 |
+
},
|
443 |
+
{
|
444 |
+
"cell_type": "code",
|
445 |
+
"execution_count": null,
|
446 |
+
"metadata": {},
|
447 |
+
"outputs": [],
|
448 |
+
"source": []
|
449 |
+
},
|
450 |
+
{
|
451 |
+
"cell_type": "code",
|
452 |
+
"execution_count": null,
|
453 |
+
"metadata": {},
|
454 |
+
"outputs": [],
|
455 |
+
"source": []
|
456 |
+
},
|
457 |
+
{
|
458 |
+
"cell_type": "code",
|
459 |
+
"execution_count": null,
|
460 |
+
"metadata": {},
|
461 |
+
"outputs": [],
|
462 |
+
"source": []
|
463 |
+
},
|
464 |
+
{
|
465 |
+
"cell_type": "code",
|
466 |
+
"execution_count": null,
|
467 |
+
"metadata": {},
|
468 |
+
"outputs": [],
|
469 |
+
"source": []
|
470 |
+
},
|
471 |
+
{
|
472 |
+
"cell_type": "code",
|
473 |
+
"execution_count": null,
|
474 |
+
"metadata": {},
|
475 |
+
"outputs": [],
|
476 |
+
"source": []
|
477 |
+
},
|
478 |
+
{
|
479 |
+
"cell_type": "code",
|
480 |
+
"execution_count": null,
|
481 |
+
"metadata": {},
|
482 |
+
"outputs": [],
|
483 |
+
"source": []
|
484 |
+
}
|
485 |
+
],
|
486 |
+
"metadata": {
|
487 |
+
"kernelspec": {
|
488 |
+
"display_name": "Python 3",
|
489 |
+
"language": "python",
|
490 |
+
"name": "python3"
|
491 |
+
},
|
492 |
+
"language_info": {
|
493 |
+
"codemirror_mode": {
|
494 |
+
"name": "ipython",
|
495 |
+
"version": 3
|
496 |
+
},
|
497 |
+
"file_extension": ".py",
|
498 |
+
"mimetype": "text/x-python",
|
499 |
+
"name": "python",
|
500 |
+
"nbconvert_exporter": "python",
|
501 |
+
"pygments_lexer": "ipython3",
|
502 |
+
"version": "3.11.0"
|
503 |
+
}
|
504 |
+
},
|
505 |
+
"nbformat": 4,
|
506 |
+
"nbformat_minor": 2
|
507 |
+
}
|
scores.json
ADDED
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"inception_score_real": {
|
3 |
+
"mean": 3.2541100236429847,
|
4 |
+
"std": 0.2093519219339589
|
5 |
+
},
|
6 |
+
"inception_score_fake": {
|
7 |
+
"mean": 1.2316137280208515,
|
8 |
+
"std": 0.011668683233882338
|
9 |
+
},
|
10 |
+
"fid": 340.08624267578125
|
11 |
+
}
|
src/imagecolorization/config/configuration.py
CHANGED
@@ -3,7 +3,8 @@ from src.imagecolorization.utils.common import read_yaml, create_directories
|
|
3 |
from src.imagecolorization.entity.config_entity import (DataIngestionConfig,
|
4 |
DataTransformationConfig,
|
5 |
ModelBuildingConfig,
|
6 |
-
ModelTrainerConfig
|
|
|
7 |
class ConfigurationManager:
|
8 |
def __init__(
|
9 |
self,
|
@@ -91,6 +92,22 @@ class ConfigurationManager:
|
|
91 |
BATCH_SIZE= params.BATCH_SIZE
|
92 |
)
|
93 |
return model_trainer_config
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
94 |
|
95 |
|
96 |
|
|
|
3 |
from src.imagecolorization.entity.config_entity import (DataIngestionConfig,
|
4 |
DataTransformationConfig,
|
5 |
ModelBuildingConfig,
|
6 |
+
ModelTrainerConfig,
|
7 |
+
ModelEvalutaionConfig)
|
8 |
class ConfigurationManager:
|
9 |
def __init__(
|
10 |
self,
|
|
|
92 |
BATCH_SIZE= params.BATCH_SIZE
|
93 |
)
|
94 |
return model_trainer_config
|
95 |
+
|
96 |
+
|
97 |
+
def get_model_evaluation_config(self) -> ModelEvalutaionConfig:
|
98 |
+
config = self.config.model_evaluation
|
99 |
+
params = self.params
|
100 |
+
|
101 |
+
model_evaluation_config = ModelEvalutaionConfig(
|
102 |
+
|
103 |
+
test_data=config.test_data,
|
104 |
+
generator_model=config.generator_model,
|
105 |
+
critic_model=config.critic_model,
|
106 |
+
all_params = params
|
107 |
+
|
108 |
+
)
|
109 |
+
|
110 |
+
return model_evaluation_config
|
111 |
|
112 |
|
113 |
|
src/imagecolorization/conponents/model_building.py
CHANGED
@@ -131,8 +131,8 @@ class ModelBuilding:
|
|
131 |
|
132 |
def get_generator(self):
|
133 |
return Generator(
|
134 |
-
input_channel=self.config.INPUT_CHANNELS,
|
135 |
-
output_channel=self.config.OUTPUT_CHANNELS,
|
136 |
dropout_rate=self.config.DROPOUT_RATE
|
137 |
).to(self.device)
|
138 |
|
|
|
131 |
|
132 |
def get_generator(self):
|
133 |
return Generator(
|
134 |
+
input_channel=self.config.INPUT_CHANNELS,
|
135 |
+
output_channel=self.config.OUTPUT_CHANNELS,
|
136 |
dropout_rate=self.config.DROPOUT_RATE
|
137 |
).to(self.device)
|
138 |
|
src/imagecolorization/conponents/model_evaluation.py
ADDED
@@ -0,0 +1,221 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from torch.utils.data import DataLoader
|
3 |
+
import mlflow
|
4 |
+
import dagshub
|
5 |
+
from tqdm.notebook import tqdm
|
6 |
+
import json
|
7 |
+
import os
|
8 |
+
import logging
|
9 |
+
from src.imagecolorization.conponents.model_building import Generator, Critic
|
10 |
+
from src.imagecolorization.conponents.model_trainer import CWGAN
|
11 |
+
import torch
|
12 |
+
from torch import nn, optim
|
13 |
+
from torchvision import transforms
|
14 |
+
from torch.utils.data import Dataset, DataLoader
|
15 |
+
from torch.autograd import Variable
|
16 |
+
from torchvision import models
|
17 |
+
from torch.nn import functional as F
|
18 |
+
import torch.utils.data
|
19 |
+
from torchvision.models.inception import inception_v3
|
20 |
+
from scipy.stats import entropy
|
21 |
+
import pytorch_lightning as pl
|
22 |
+
from torchsummary import summary
|
23 |
+
from src.imagecolorization.conponents.model_building import Generator, Critic
|
24 |
+
from src.imagecolorization.conponents.data_tranformation import ImageColorizationDataset
|
25 |
+
from src.imagecolorization.logging import logger
|
26 |
+
import gc
|
27 |
+
import numpy as np
|
28 |
+
from src.imagecolorization.config.configuration import ConfigurationManager
|
29 |
+
from pathlib import Path
|
30 |
+
|
31 |
+
|
32 |
+
logger = logging.getLogger(__name__)
|
33 |
+
|
34 |
+
import torch
|
35 |
+
from torch.utils.data import DataLoader
|
36 |
+
import mlflow
|
37 |
+
import dagshub
|
38 |
+
from tqdm.notebook import tqdm
|
39 |
+
import json
|
40 |
+
import os
|
41 |
+
import logging
|
42 |
+
from torchvision.models.inception import inception_v3
|
43 |
+
from torch.nn import functional as F
|
44 |
+
import numpy as np
|
45 |
+
from torchvision import transforms
|
46 |
+
from src.imagecolorization.utils.common import save_json
|
47 |
+
|
48 |
+
logger = logging.getLogger(__name__)
|
49 |
+
|
50 |
+
class FID:
|
51 |
+
def __init__(self, device):
|
52 |
+
self.device = device
|
53 |
+
self.inception = inception_v3(pretrained=True, transform_input=False).to(self.device)
|
54 |
+
self.inception.eval()
|
55 |
+
self.resize = transforms.Resize((299, 299))
|
56 |
+
|
57 |
+
def convert_to_three_channels(self, images):
|
58 |
+
if images.shape[1] == 2:
|
59 |
+
images = torch.cat((images, images[:, :1, :, :]), dim=1) # Duplicate one channel
|
60 |
+
return images
|
61 |
+
|
62 |
+
def preprocess_images(self, images):
|
63 |
+
images = self.convert_to_three_channels(images)
|
64 |
+
images = images.to(self.device)
|
65 |
+
images = self.resize(images)
|
66 |
+
return images
|
67 |
+
|
68 |
+
def calculate_fid(self, real_images, generated_images):
|
69 |
+
batch_size = 32
|
70 |
+
real_features_list = []
|
71 |
+
generated_features_list = []
|
72 |
+
|
73 |
+
for i in range(0, len(real_images), batch_size):
|
74 |
+
real_batch = self.preprocess_images(real_images[i:i+batch_size])
|
75 |
+
generated_batch = self.preprocess_images(generated_images[i:i+batch_size])
|
76 |
+
|
77 |
+
with torch.no_grad():
|
78 |
+
real_features = self.inception(real_batch).view(real_batch.size(0), -1)
|
79 |
+
generated_features = self.inception(generated_batch).view(generated_batch.size(0), -1)
|
80 |
+
|
81 |
+
real_features_list.append(real_features.cpu())
|
82 |
+
generated_features_list.append(generated_features.cpu())
|
83 |
+
|
84 |
+
real_features = torch.cat(real_features_list, dim=0)
|
85 |
+
generated_features = torch.cat(generated_features_list, dim=0)
|
86 |
+
|
87 |
+
mu_diff = real_features.mean(dim=0) - generated_features.mean(dim=0)
|
88 |
+
sigma_diff = real_features.std(dim=0) - generated_features.std(dim=0)
|
89 |
+
|
90 |
+
fid = mu_diff.pow(2).sum() + sigma_diff.pow(2).sum()
|
91 |
+
return fid.item()
|
92 |
+
|
93 |
+
class InceptionScore:
|
94 |
+
def __init__(self, device):
|
95 |
+
self.device = device
|
96 |
+
self.inception = inception_v3(pretrained=True, transform_input=False).to(self.device)
|
97 |
+
self.inception.eval()
|
98 |
+
self.resize = transforms.Resize((299, 299))
|
99 |
+
|
100 |
+
def convert_to_three_channels(self, images):
|
101 |
+
if images.shape[1] == 2: # If the input has 2 channels
|
102 |
+
images = torch.cat((images, images[:, :1, :, :]), dim=1) # Duplicate one channel
|
103 |
+
return images
|
104 |
+
|
105 |
+
def preprocess_images(self, images):
|
106 |
+
images = self.convert_to_three_channels(images)
|
107 |
+
images = images.to(self.device)
|
108 |
+
images = self.resize(images)
|
109 |
+
return images
|
110 |
+
|
111 |
+
def calculate_is(self, images):
|
112 |
+
batch_size = 1
|
113 |
+
splits = 10
|
114 |
+
preds = []
|
115 |
+
|
116 |
+
for i in range(0, len(images), batch_size):
|
117 |
+
batch = self.preprocess_images(images[i:i+batch_size])
|
118 |
+
with torch.no_grad():
|
119 |
+
pred = F.softmax(self.inception(batch), dim=1)
|
120 |
+
preds.append(pred.cpu().numpy())
|
121 |
+
|
122 |
+
preds = np.concatenate(preds, axis=0)
|
123 |
+
n_images = preds.shape[0]
|
124 |
+
|
125 |
+
split_scores = []
|
126 |
+
for k in range(splits):
|
127 |
+
part = preds[k * (n_images // splits): (k + 1) * (n_images // splits), :]
|
128 |
+
py = np.mean(part, axis=0)
|
129 |
+
scores = []
|
130 |
+
for i in range(part.shape[0]):
|
131 |
+
pyx = part[i, :]
|
132 |
+
scores.append(entropy(pyx, py))
|
133 |
+
split_scores.append(np.exp(np.mean(scores)))
|
134 |
+
|
135 |
+
return np.mean(split_scores), np.std(split_scores)
|
136 |
+
|
137 |
+
class ModelEvaluation:
|
138 |
+
def __init__(self, config):
|
139 |
+
self.config = config
|
140 |
+
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
141 |
+
self.generator = None
|
142 |
+
self.critic = None
|
143 |
+
|
144 |
+
def load_model(self):
|
145 |
+
self.generator = Generator(input_channel=1, output_channel=2).to(self.device)
|
146 |
+
self.critic = Critic(in_channels=3).to(self.device)
|
147 |
+
|
148 |
+
self.generator.load_state_dict(torch.load(self.config.generator_model))
|
149 |
+
self.critic.load_state_dict(torch.load(self.config.critic_model))
|
150 |
+
|
151 |
+
self.generator.eval()
|
152 |
+
self.critic.eval()
|
153 |
+
|
154 |
+
logger.info("Model loaded successfully.")
|
155 |
+
|
156 |
+
def load_data(self):
|
157 |
+
self.test_dataset = torch.load(self.config.test_data)
|
158 |
+
self.test_dataloader = DataLoader(
|
159 |
+
self.test_dataset,
|
160 |
+
batch_size=self.config.all_params.BATCH_SIZE,
|
161 |
+
shuffle=True,
|
162 |
+
)
|
163 |
+
|
164 |
+
def evaluate_model(self):
|
165 |
+
is_calculator = InceptionScore(self.device)
|
166 |
+
fid_calculator = FID(self.device)
|
167 |
+
|
168 |
+
all_preds = []
|
169 |
+
all_real = []
|
170 |
+
|
171 |
+
with torch.no_grad():
|
172 |
+
for batch in tqdm(self.test_dataloader, desc="Evaluating", unit="batch"):
|
173 |
+
real, condition = batch
|
174 |
+
real, condition = real.to(self.device), condition.to(self.device)
|
175 |
+
fake = self.generator(condition)
|
176 |
+
all_preds.append(fake.cpu())
|
177 |
+
all_real.append(real.cpu())
|
178 |
+
|
179 |
+
all_preds = torch.cat(all_preds, dim=0)
|
180 |
+
all_real = torch.cat(all_real, dim=0)
|
181 |
+
|
182 |
+
print("Calculating Inception Score for real images...")
|
183 |
+
mean_real_is, std_real_is = is_calculator.calculate_is(all_real)
|
184 |
+
print("Calculating Inception Score for generated images...")
|
185 |
+
mean_fake_is, std_fake_is = is_calculator.calculate_is(all_preds)
|
186 |
+
|
187 |
+
print("Calculating Fréchet Inception Distance...")
|
188 |
+
fid_value = fid_calculator.calculate_fid(all_real, all_preds)
|
189 |
+
|
190 |
+
results = {
|
191 |
+
"inception_score_real": {"mean": float(mean_real_is), "std": float(std_real_is)},
|
192 |
+
"inception_score_fake": {"mean": float(mean_fake_is), "std": float(std_fake_is)},
|
193 |
+
"fid": float(fid_value)
|
194 |
+
}
|
195 |
+
return results
|
196 |
+
|
197 |
+
def save_scores(self, results):
|
198 |
+
save_json(path=Path('scores.json'), data=results)
|
199 |
+
|
200 |
+
def log_to_mlflow(self, results):
|
201 |
+
dagshub.init(repo_owner='HAKIM-ML', repo_name='image-colorization-mlops', mlflow=True)
|
202 |
+
|
203 |
+
with mlflow.start_run():
|
204 |
+
# Log all parameters
|
205 |
+
for key, value in self.config.all_params.items():
|
206 |
+
mlflow.log_param(key, value)
|
207 |
+
|
208 |
+
# Log metrics
|
209 |
+
mlflow.log_metric('inception_score_real_mean', results['inception_score_real']['mean'])
|
210 |
+
mlflow.log_metric('inception_score_fake_mean', results['inception_score_fake']['mean'])
|
211 |
+
mlflow.log_metric('fid', results['fid'])
|
212 |
+
|
213 |
+
# Log the JSON file as an artifact
|
214 |
+
mlflow.log_artifact('scores.json')
|
215 |
+
|
216 |
+
def run(self):
|
217 |
+
self.load_model()
|
218 |
+
self.load_data()
|
219 |
+
results = self.evaluate_model()
|
220 |
+
self.save_scores(results)
|
221 |
+
self.log_to_mlflow(results)
|
src/imagecolorization/entity/config_entity.py
CHANGED
@@ -47,4 +47,12 @@ class ModelTrainerConfig:
|
|
47 |
INPUT_CHANNELS: int
|
48 |
OUTPUT_CHANNELS: int
|
49 |
EPOCH: int
|
50 |
-
BATCH_SIZE : int
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
47 |
INPUT_CHANNELS: int
|
48 |
OUTPUT_CHANNELS: int
|
49 |
EPOCH: int
|
50 |
+
BATCH_SIZE : int
|
51 |
+
|
52 |
+
|
53 |
+
@dataclass(frozen=True)
|
54 |
+
class ModelEvalutaionConfig:
|
55 |
+
test_data : Path
|
56 |
+
generator_model : Path
|
57 |
+
critic_model : Path
|
58 |
+
all_params: dict
|
src/imagecolorization/pipeline/stage_05_model_evaluation.py
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from src.imagecolorization.conponents.model_evaluation import ModelEvaluation
|
2 |
+
from src.imagecolorization.config.configuration import ConfigurationManager
|
3 |
+
|
4 |
+
|
5 |
+
class ModelEvaluationPipeLine:
|
6 |
+
def __init__(self):
|
7 |
+
pass
|
8 |
+
|
9 |
+
def main(self):
|
10 |
+
config_manager = ConfigurationManager()
|
11 |
+
model_evaluation_config = config_manager.get_model_evaluation_config()
|
12 |
+
model_evaluation = ModelEvaluation(config=model_evaluation_config)
|
13 |
+
model_evaluation.run()
|
14 |
+
|
15 |
+
|
16 |
+
|
17 |
+
|