Optimized U-net model for precise retinal blood vessel segmentation from colour fundus images.
The 4 matches
- [1] § Experimental analysis › ROC and precision – recall analysis ↔ 41598_2026_48475_MOESM2_ESM.ipynb, lines 1951–2003 · score 0.55 · PR AUC, precision recall, ROC
- [2] § Experimental analysis › ROC and precision – recall analysis ↔ 41598_2026_48475_MOESM3_ESM.ipynb, lines 1859–1911 · score 0.55 · PR AUC, precision recall, ROC
- [3] § Proposed method › Preprocessing › Data augmentation ↔ 41598_2026_48475_MOESM1_ESM.ipynb, lines 55–160 · score 0.50 · horizontal flipping, rotated, transformations, augmentation, mask, training
- [4] § Proposed method › Preprocessing › Data augmentation ↔ 41598_2026_48475_MOESM2_ESM.ipynb, lines 58–163 · score 0.50 · horizontal flipping, rotated, transformations, augmentation, mask, training
Paper
Loaded from Europe PMC by your browser, not stored by OSCR: doi.org · Europe PMC
The paper is loaded when this pane is shown.
The authors' code
Jupyter notebook · 2,034 lines · 56 KB · no license · 2 matches
- # %%
- # %%
- from google.colab import drive
- drive.mount('/content/drive')
- # %%
- import os
- train_images_path = '/content/drive/My Drive/Data/dataset/VesselNet/VesselNet/dataset/train/origin'
- train_mask_path = '/content/drive/My Drive/Data/dataset/VesselNet/VesselNet/dataset/train/groundtruth'
- test_images_path = '/content/drive/My Drive/Data/dataset/VesselNet/VesselNet/test/origin'
- test_mask_path = '/content/drive/My Drive/Data/dataset/VesselNet/VesselNet/test/groundtruth'
- train_images_files = sorted([os.path.join(train_images_path, i) for i in os.listdir(train_images_path)])
- train_mask_files = sorted([os.path.join(train_mask_path, i) for i in os.listdir(train_mask_path)])
- test_images_files = sorted([os.path.join(test_images_path, i) for i in os.listdir(test_images_path)])
- test_mask_files = sorted([os.path.join(test_mask_path, i) for i in os.listdir(test_mask_path)])
- # %%
- print(len(train_images_files))
- print(len(train_mask_files))
- print(len(test_images_files))
- print(len(test_mask_files))
- # %%
- import cv2
- import math
- import numpy as np
- import matplotlib.pyplot as plt
- import seaborn as sns
- sns.set()
- import tensorflow as tf
- import tensorflow.keras.backend as K
- from tensorflow.keras.utils import Sequence
- from tensorflow.keras.models import Model
- from tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, Conv2DTranspose, concatenate, BatchNormalization, Dropout, average
- from tensorflow.keras.losses import binary_crossentropy
- from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau
- # ✅ FINAL FIXED albumentations (latest compatible)
- from albumentations import (
- Compose, OneOf,
- CLAHE, HorizontalFlip, VerticalFlip, Rotate,
- RGBShift, RandomBrightnessContrast,
- Transpose, ShiftScaleRotate, RandomRotate90,
- OpticalDistortion, GridDistortion, ElasticTransform,
- ChannelShuffle, RandomCrop
- )
- from sklearn.metrics import classification_report
- from PIL import Image
- # %%
- def read_image(file_loc, dim=(256,256)):
- img = Image.open(file_loc)
- img = img.resize(dim)
- img = np.array(img)
- return img
- def read_mask(file_loc, dim=(256,256)):
- img = Image.open(file_loc)
- img = img.resize(dim)
- img = np.array(img)
- img = (img>0).astype(np.uint8)
- return img
- #...............................................................................................................
- class Train_Generator(Sequence):
- def __init__(self, x_set, y_set, batch_size=5, img_dim=(512,512), augmentation=False):
- self.x = x_set
- self.y = y_set
- self.batch_size = batch_size
- self.img_dim = img_dim
- self.augmentation = augmentation
- def __len__(self):
- return math.ceil(len(self.x) / self.batch_size)
- aug = Compose(
- [
- CLAHE(always_apply=True, p=1.0),
- OneOf([
- HorizontalFlip(p=0.5),
- VerticalFlip(p=0.5),
- Transpose()
- ], p=1.0),
- OneOf([
- ShiftScaleRotate(),
- RandomRotate90()
- ], p=0.9),
- OneOf([
- OpticalDistortion(),
- GridDistortion(),
- ElasticTransform(),
- ], p=0.4),
- OneOf([
- RGBShift(),
- RandomBrightnessContrast()
- ], p=0.2)
- ])
- def __getitem__(self, idx):
- batch_x = self.x[idx * self.batch_size:(idx + 1) * self.batch_size]
- batch_y = self.y[idx * self.batch_size:(idx + 1) * self.batch_size]
- batch_x = np.array([read_image(file_name, self.img_dim) for file_name in batch_x])
- batch_y = np.array([read_mask(file_name, self.img_dim) for file_name in batch_y])
- if self.augmentation is True:
- aug = [self.aug(image=i, mask=j) for i, j in zip(batch_x, batch_y)]
- batch_x = np.array([i['image'] for i in aug])
- batch_y = np.array([j['mask'] for j in aug])
- batch_y = np.expand_dims(batch_y, -1)
- #return batch_x/255.0, [batch_y, batch_y, batch_y, batch_y]
- return batch_x/255.0, batch_y/1.0
- #...............................................................................................................
- class Val_Generator(Sequence):
- def __init__(self, x_set, y_set, batch_size=5, img_dim=(512,512), augmentation=False):
- self.x = x_set
- self.y = y_set
- self.batch_size = batch_size
- self.img_dim = img_dim
- self.augmentation = augmentation
- def __len__(self):
- return math.ceil(len(self.x) / self.batch_size)
- aug = Compose(
- [
- CLAHE(always_apply=True, p=1.0)
- ])
- def __getitem__(self, idx):
- batch_x = self.x[idx * self.batch_size:(idx + 1) * self.batch_size]
- batch_y = self.y[idx * self.batch_size:(idx + 1) * self.batch_size]
- batch_x = np.array([read_image(file_name, self.img_dim) for file_name in batch_x])
- batch_y = np.array([read_mask(file_name, self.img_dim) for file_name in batch_y])
- if self.augmentation is True:
- aug = [self.aug(image=i, mask=j) for i, j in zip(batch_x, batch_y)]
- batch_x = np.array([i['image'] for i in aug])
- batch_y = np.array([j['mask'] for j in aug])
- batch_y = np.expand_dims(batch_y, -1)
- return batch_x/255.0, batch_y/1.0
- # return batch_x/255.0, [batch_y, batch_y, batch_y, batch_y]
- # %% [markdown]
- # Input pipeline
- # %%
- batch_img_dim = (10, 256, 256, 3)
- batch_msk_dim = (10, 256, 256, 1)
- def train_generator():
- return Train_Generator(train_images_files, train_mask_files, batch_size = batch_img_dim[0], img_dim=(batch_img_dim[1], batch_img_dim[2]), augmentation=True).__iter__()
- def valid_generator():
- return Val_Generator(test_images_files, test_mask_files, batch_size = batch_img_dim[0], img_dim=(batch_img_dim[1], batch_img_dim[2]), augmentation=True).__iter__()
- ds_train = tf.data.Dataset.from_generator(
- train_generator,
- output_types=(tf.float32, tf.float32),
- output_shapes=([batch_img_dim[0], batch_img_dim[1], batch_img_dim[2], batch_img_dim[3]], [batch_msk_dim[0], batch_msk_dim[1], batch_msk_dim[2], batch_msk_dim[3]])
- ).repeat()
- ds_valid = tf.data.Dataset.from_generator(
- valid_generator,
- output_types=(tf.float32, tf.float32),
- output_shapes=([batch_img_dim[0], batch_img_dim[1], batch_img_dim[2], batch_img_dim[3]], [batch_msk_dim[0], batch_msk_dim[1], batch_msk_dim[2], batch_msk_dim[3]])
- ).repeat()
- # %%
- for i, j in ds_train:
- break
- fig, axes = plt.subplots(1, 10, figsize=(30,5))
- axes = axes.flatten()
- for img, ax in zip(i[:10], axes[:10]):
- ax.imshow(img)
- ax.axis('off')
- plt.show()
- fig, axes = plt.subplots(1, 10, figsize=(30,5))
- axes = axes.flatten()
- for img, ax in zip(j[:10], axes[:10]):
- ax.imshow(np.squeeze(img, -1), cmap='gray')
- ax.axis('off')
- plt.show()
- # %%
- for i, j in ds_valid:
- break
- fig, axes = plt.subplots(1, 5, figsize=(10,3))
- fig.suptitle('CLAHE-d Val Images', fontsize=15)
- axes = axes.flatten()
- for img, ax in zip(i[:5], axes[:5]):
- ax.imshow(img)
- ax.axis('off')
- plt.tight_layout()
- plt.show()
- fig, axes = plt.subplots(1, 5, figsize=(10,3))
- fig.suptitle('CLAHE-d Val Masks', fontsize=15)
- axes = axes.flatten()
- for img, ax in zip(j[:5], axes[:5]):
- ax.imshow(np.squeeze(img, -1), cmap='gray')
- ax.axis('off')
- plt.tight_layout()
- plt.show()
- # %% [markdown]
- # **model**
- # %% [markdown]
- # %%
- from tensorflow.keras.layers import Lambda
- class conv_bnorm(tf.keras.layers.Layer):
- def __init__(self, f, **kwargs):
- super(conv_bnorm, self).__init__(**kwargs)
- self.conv_1 = Conv2D(f, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')
- self.norm_1 = BatchNormalization()
- self.conv_2 = Conv2D(f, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')
- self.norm_2 = BatchNormalization()
- def call(self, inputs):
- x = self.conv_1(inputs)
- x = self.norm_1(x)
- x = self.conv_2(x)
- x = self.norm_2(x)
- return x
- def SubpixelUpsampling(x, y):
- depth = tf.keras.backend.int_shape(x)[-1]
- def depth_to_space(x):
- return tf.nn.depth_to_space(x, 2)
- x = Conv2D(filters=depth*2, kernel_size=(1,1), strides=1, padding='same', )(x)
- x = Lambda(depth_to_space)(x)
- x = concatenate([x, y])
- return x
- inputs = Input((256,256,3), name='Input')
- m1c1 = conv_bnorm(32, name='M1_conv_bnorm_d1') (inputs)
- m1p1 = MaxPooling2D(name='M1_pool1') (m1c1)
- m1c2 = conv_bnorm(64, name='M1_conv_bnorm_d2') (m1p1)
- m1p2 = MaxPooling2D(name='M1_pool2') (m1c2)
- m1c3 = conv_bnorm(128, name='M1_conv_bnorm_d3') (m1p2)
- m1p3 = MaxPooling2D(name='M1_pool3') (m1c3)
- m1c4 = conv_bnorm(256, name='M1_conv_bnorm_d4') (m1p3)
- m1p4 = MaxPooling2D(name='M1_pool4') (m1c4)
- m1c5 = conv_bnorm(512, name='M1_conv_bnorm_d5') (m1p4)
- m1p5 = MaxPooling2D(name='M1_pool5') (m1c5)
- m1c6 = conv_bnorm(1024, name='M1_conv_bnorm_d6') (m1p5) # Bottleneck
- m1u5 = SubpixelUpsampling(m1c6, m1c5)
- m1u5 = conv_bnorm(512, name='M1_conv_bnorm5_u5') (m1u5)
- m1u4 = SubpixelUpsampling(m1u5, m1c4)
- m1u4 = conv_bnorm(256, name='M1_conv_bnorm_u4') (m1u4)
- m1u3 = SubpixelUpsampling(m1u4, m1c3)
- m1u3 = conv_bnorm(128, name='M1_conv_bnorm_u3') (m1u3)
- m1u2 = SubpixelUpsampling(m1u3, m1c2)
- m1u2 = conv_bnorm(64, name='M1_conv_bnorm_u2') (m1u2)
- m1u1 = SubpixelUpsampling(m1u2, m1c1)
- m1u1 = conv_bnorm(32, name='M1_conv_bnorm_u1') (m1u1)
- m1out = Conv2D(1, (1, 1), name='M1_output', activation='sigmoid') (m1u1) # Output
- #-----------------------------------------------------------------------------
- m2inp = concatenate([m1u1, inputs])
- m2c1 = conv_bnorm(32, name='M2_conv_bnorm_d1') (m2inp)
- m2p1 = MaxPooling2D(name='M2_pool1') (m2c1)
- m2c2 = conv_bnorm(64, name='M2_conv_bnorm_d2') (m2p1)
- m2p2 = MaxPooling2D(name='M2_pool2') (m2c2)
- m2c3 = conv_bnorm(128, name='M2_conv_bnorm_d3') (m2p2)
- m2p3 = MaxPooling2D(name='M2_pool3') (m2c3)
- m2c4 = conv_bnorm(256, name='M2_conv_bnorm_d4') (m2p3)
- m2p4 = MaxPooling2D(name='M2_pool4') (m2c4)
- m2c5 = conv_bnorm(512, name='M2_conv_bnorm_d5') (m2p4)
- m2p5 = MaxPooling2D(name='M2_pool5') (m2c5)
- m2c6 = conv_bnorm(1024, name='M2_conv_bnorm_d6') (m2p5)
- m2u5 = SubpixelUpsampling(m2c6, m2c5)
- m2u5 = concatenate([m2u5, m1u5])
- m2u5 = conv_bnorm(512, name='M2_conv_bnorm_u5') (m2u5)
- m2u4 = SubpixelUpsampling(m2c5, m2c4)
- m2u4 = concatenate([m2u4, m1u4])
- m2u4 = conv_bnorm(256, name='M2_conv_bnorm_u4') (m2u4)
- m2u3 = SubpixelUpsampling(m2u4, m2c3)
- m2u3 = concatenate([m2u3, m1u3])
- m2u3 = conv_bnorm(128, name='M2_conv_bnorm_u3') (m2u3)
- m2u2 = SubpixelUpsampling(m2u3, m2c2)
- m2u2 = concatenate([m2u2, m1u2])
- m2u2 = conv_bnorm(64, name='M2_conv_bnorm_u2') (m2u2)
- m2u1 = SubpixelUpsampling(m2u2, m2c1)
- m2u1 = concatenate([m2u1, m1u1])
- m2u1 = conv_bnorm(32, name='M2_conv_bnorm_u1') (m2u1)
- m2out = Conv2D(1, (1, 1), name='M2_output', activation='sigmoid') (m2u1)
- #-----------------------------------------------------------------------------
- m3inp = concatenate([m2u1, inputs])
- m3c1 = conv_bnorm(32, name='M3_conv_bnorm_d1') (m3inp)
- m3p1 = MaxPooling2D(name='M3_pool1') (m3c1)
- m3c2 = conv_bnorm(64, name='M3_conv_bnorm_d2') (m3p1)
- m3p2 = MaxPooling2D(name='M3_pool2') (m3c2)
- m3c3 = conv_bnorm(128, name='M3_conv_bnorm_d3') (m3p2)
- m3p3 = MaxPooling2D(name='M3_pool3') (m3c3)
- m3c4 = conv_bnorm(256, name='M3_conv_bnorm_d4') (m3p3)
- m3p4 = MaxPooling2D(name='M3_pool4') (m3c4)
- m3c5 = conv_bnorm(512, name='M3_conv_bnorm_d5') (m3p4)
- m3p5 = MaxPooling2D(name='M3_pool5') (m3c5)
- m3c6 = conv_bnorm(1024, name='M3_conv_bnorm_d6') (m3p5)
- m3u5 = SubpixelUpsampling(m3c6, m3c5)
- m3u5 = concatenate([m3u5, m1u5])
- m3u5 = concatenate([m3u5, m2u5])
- m3u5 = conv_bnorm(512, name='M3_conv_bnorm_u5') (m3u5)
- m3u4 = SubpixelUpsampling(m3c5, m3c4)
- m3u4 = concatenate([m3u4, m1u4])
- m3u4 = concatenate([m3u4, m2u4])
- m3u4 = conv_bnorm(256, name='M3_conv_bnorm_u4') (m3u4)
- m3u3 = SubpixelUpsampling(m3u4, m3c3)
- m3u3 = concatenate([m3u3, m1u3])
- m3u3 = concatenate([m3u3, m2u3])
- m3u3 = conv_bnorm(128, name='M3_conv_bnorm_u3') (m3u3)
- m3u2 = SubpixelUpsampling(m3u3, m3c2)
- m3u2 = concatenate([m3u2, m1u2])
- m3u2 = concatenate([m3u2, m2u2])
- m3u2 = conv_bnorm(64, name='M3_conv_bnorm_u2') (m3u2)
- m3u1 = SubpixelUpsampling(m3u2, m3c1)
- m3u1 = concatenate([m3u1, m1u1])
- m3u1 = concatenate([m3u1, m2u1])
- m3u1 = conv_bnorm(32, name='M3_conv_bnorm_u1') (m3u1)
- m3out = Conv2D(1, (1, 1), name='M3_output', activation='sigmoid') (m3u1)
- #-----------------------------------------------------------------------------
- m4inp = concatenate([m3u1, inputs])
- m4c1 = conv_bnorm(32, name='M4_conv_bnorm_d1') (m4inp)
- m4p1 = MaxPooling2D(name='M4_pool1') (m4c1)
- m4c2 = conv_bnorm(64, name='M4_conv_bnorm_d2') (m4p1)
- m4p2 = MaxPooling2D(name='M4_pool2') (m4c2)
- m4c3 = conv_bnorm(128, name='M4_conv_bnorm_d3') (m4p2)
- m4p3 = MaxPooling2D(name='M4_pool3') (m4c3)
- m4c4 = conv_bnorm(256, name='M4_conv_bnorm_d4') (m4p3)
- m4p4 = MaxPooling2D(name='M4_pool4') (m4c4)
- m4c5 = conv_bnorm(512, name='M4_conv_bnorm_d5') (m4p4)
- m4p5 = MaxPooling2D(name='M4_pool5') (m4c5)
- m4c6 = conv_bnorm(1024, name='M4_conv_bnorm_d6') (m4p5)
- m4u5 = SubpixelUpsampling(m4c6, m4c5)
- m4u5 = concatenate([m4u5, m1u5])
- m4u5 = concatenate([m4u5, m2u5])
- m4u5 = concatenate([m4u5, m3u5])
- m4u5 = conv_bnorm(512, name='M4_conv_bnorm_u5') (m4u5)
- m4u4 = SubpixelUpsampling(m4c5, m4c4)
- m4u4 = concatenate([m4u4, m1u4])
- m4u4 = concatenate([m4u4, m2u4])
- m4u4 = concatenate([m4u4, m3u4])
- m4u4 = conv_bnorm(256, name='M4_conv_bnorm_u4') (m4u4)
- m4u3 = SubpixelUpsampling(m4u4, m4c3)
- m4u3 = concatenate([m4u3, m1u3])
- m4u3 = concatenate([m4u3, m2u3])
- m4u3 = concatenate([m4u3, m3u3])
- m4u3 = conv_bnorm(128, name='M4_conv_bnorm_u3') (m4u3)
- m4u2 = SubpixelUpsampling(m4u3, m4c2)
- m4u2 = concatenate([m4u2, m1u2])
- m4u2 = concatenate([m4u2, m2u2])
- m4u2 = concatenate([m4u2, m3u2])
- m4u2 = conv_bnorm(64, name='M4_conv_bnorm_u2') (m4u2)
- m4u1 = SubpixelUpsampling(m4u2, m4c1)
- m4u1 = concatenate([m4u1, m1u1])
- m4u1 = concatenate([m4u1, m2u1])
- m4u1 = concatenate([m4u1, m3u1])
- m4u1 = conv_bnorm(32, name='M4_conv_bnorm_u1') (m4u1)
- m4out = Conv2D(1, (1, 1), name='M4_output', activation='sigmoid') (m4u1)
- #K.clear_session()
- #model = Model(inputs=[inputs], outputs=[m1out, m2out, m3out, m4out])
- K.clear_session()
- model = Model(inputs=[inputs], outputs=m4out)
- # %%
- from tensorflow.keras.layers import Lambda
- class conv_bnorm(tf.keras.layers.Layer):
- def __init__(self, f, **kwargs):
- super(conv_bnorm, self).__init__(**kwargs)
- self.conv_1 = Conv2D(f, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')
- self.norm_1 = BatchNormalization()
- self.conv_2 = Conv2D(f, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')
- self.norm_2 = BatchNormalization()
- def call(self, inputs):
- x = self.conv_1(inputs)
- x = self.norm_1(x)
- x = self.conv_2(x)
- x = self.norm_2(x)
- return x
- def SubpixelUpsampling(x, y):
- depth = tf.keras.backend.int_shape(x)[-1]
- def depth_to_space(x):
- return tf.nn.depth_to_space(x, 2)
- x = Conv2D(filters=depth*2, kernel_size=(1,1), strides=1, padding='same', )(x)
- x = Lambda(depth_to_space)(x)
- x = concatenate([x, y])
- return x
- inputs = Input((256,256,3), name='Input')
- m1c1 = conv_bnorm(32, name='M1_conv_bnorm_d1') (inputs)
- m1p1 = MaxPooling2D(name='M1_pool1') (m1c1)
- m1c2 = conv_bnorm(64, name='M1_conv_bnorm_d2') (m1p1)
- m1p2 = MaxPooling2D(name='M1_pool2') (m1c2)
- m1c3 = conv_bnorm(128, name='M1_conv_bnorm_d3') (m1p2)
- m1p3 = MaxPooling2D(name='M1_pool3') (m1c3)
- m1c4 = conv_bnorm(256, name='M1_conv_bnorm_d4') (m1p3)
- m1p4 = MaxPooling2D(name='M1_pool4') (m1c4)
- m1c5 = conv_bnorm(512, name='M1_conv_bnorm_d5') (m1p4)
- m1p5 = MaxPooling2D(name='M1_pool5') (m1c5)
- m1c6 = conv_bnorm(1024, name='M1_conv_bnorm_d6') (m1p5) # Bottleneck
- m1u5 = SubpixelUpsampling(m1c6, m1c5)
- m1u5 = conv_bnorm(512, name='M1_conv_bnorm5_u5') (m1u5)
- m1u4 = SubpixelUpsampling(m1u5, m1c4)
- m1u4 = conv_bnorm(256, name='M1_conv_bnorm_u4') (m1u4)
- m1u3 = SubpixelUpsampling(m1u4, m1c3)
- m1u3 = conv_bnorm(128, name='M1_conv_bnorm_u3') (m1u3)
- m1u2 = SubpixelUpsampling(m1u3, m1c2)
- m1u2 = conv_bnorm(64, name='M1_conv_bnorm_u2') (m1u2)
- m1u1 = SubpixelUpsampling(m1u2, m1c1)
- m1u1 = conv_bnorm(32, name='M1_conv_bnorm_u1') (m1u1)
- m1out = Conv2D(1, (1, 1), name='M1_output', activation='sigmoid') (m1u1) # Output
- #-----------------------------------------------------------------------------
- m2inp = concatenate([m1u1, inputs])
- m2c1 = conv_bnorm(32, name='M2_conv_bnorm_d1') (m2inp)
- m2p1 = MaxPooling2D(name='M2_pool1') (m2c1)
- m2c2 = conv_bnorm(64, name='M2_conv_bnorm_d2') (m2p1)
- m2p2 = MaxPooling2D(name='M2_pool2') (m2c2)
- m2c3 = conv_bnorm(128, name='M2_conv_bnorm_d3') (m2p2)
- m2p3 = MaxPooling2D(name='M2_pool3') (m2c3)
- m2c4 = conv_bnorm(256, name='M2_conv_bnorm_d4') (m2p3)
- m2p4 = MaxPooling2D(name='M2_pool4') (m2c4)
- m2c5 = conv_bnorm(512, name='M2_conv_bnorm_d5') (m2p4)
- m2p5 = MaxPooling2D(name='M2_pool5') (m2c5)
- m2c6 = conv_bnorm(1024, name='M2_conv_bnorm_d6') (m2p5)
- m2u5 = SubpixelUpsampling(m2c6, m2c5)
- m2u5 = concatenate([m2u5, m1u5])
- m2u5 = conv_bnorm(512, name='M2_conv_bnorm_u5') (m2u5)
- m2u4 = SubpixelUpsampling(m2c5, m2c4)
- m2u4 = concatenate([m2u4, m1u4])
- m2u4 = conv_bnorm(256, name='M2_conv_bnorm_u4') (m2u4)
- m2u3 = SubpixelUpsampling(m2u4, m2c3)
- m2u3 = concatenate([m2u3, m1u3])
- m2u3 = conv_bnorm(128, name='M2_conv_bnorm_u3') (m2u3)
- m2u2 = SubpixelUpsampling(m2u3, m2c2)
- m2u2 = concatenate([m2u2, m1u2])
- m2u2 = conv_bnorm(64, name='M2_conv_bnorm_u2') (m2u2)
- m2u1 = SubpixelUpsampling(m2u2, m2c1)
- m2u1 = concatenate([m2u1, m1u1])
- m2u1 = conv_bnorm(32, name='M2_conv_bnorm_u1') (m2u1)
- m2out = Conv2D(1, (1, 1), name='M2_output', activation='sigmoid') (m2u1)
- #-----------------------------------------------------------------------------
- m3inp = concatenate([m2u1, inputs])
- m3c1 = conv_bnorm(32, name='M3_conv_bnorm_d1') (m3inp)
- m3p1 = MaxPooling2D(name='M3_pool1') (m3c1)
- m3c2 = conv_bnorm(64, name='M3_conv_bnorm_d2') (m3p1)
- m3p2 = MaxPooling2D(name='M3_pool2') (m3c2)
- m3c3 = conv_bnorm(128, name='M3_conv_bnorm_d3') (m3p2)
- m3p3 = MaxPooling2D(name='M3_pool3') (m3c3)
- m3c4 = conv_bnorm(256, name='M3_conv_bnorm_d4') (m3p3)
- m3p4 = MaxPooling2D(name='M3_pool4') (m3c4)
- m3c5 = conv_bnorm(512, name='M3_conv_bnorm_d5') (m3p4)
- m3p5 = MaxPooling2D(name='M3_pool5') (m3c5)
- m3c6 = conv_bnorm(1024, name='M3_conv_bnorm_d6') (m3p5)
- m3u5 = SubpixelUpsampling(m3c6, m3c5)
- m3u5 = concatenate([m3u5, m1u5])
- m3u5 = concatenate([m3u5, m2u5])
- m3u5 = conv_bnorm(512, name='M3_conv_bnorm_u5') (m3u5)
- m3u4 = SubpixelUpsampling(m3c5, m3c4)
- m3u4 = concatenate([m3u4, m1u4])
- m3u4 = concatenate([m3u4, m2u4])
- m3u4 = conv_bnorm(256, name='M3_conv_bnorm_u4') (m3u4)
- m3u3 = SubpixelUpsampling(m3u4, m3c3)
- m3u3 = concatenate([m3u3, m1u3])
- m3u3 = concatenate([m3u3, m2u3])
- m3u3 = conv_bnorm(128, name='M3_conv_bnorm_u3') (m3u3)
- m3u2 = SubpixelUpsampling(m3u3, m3c2)
- m3u2 = concatenate([m3u2, m1u2])
- m3u2 = concatenate([m3u2, m2u2])
- m3u2 = conv_bnorm(64, name='M3_conv_bnorm_u2') (m3u2)
- m3u1 = SubpixelUpsampling(m3u2, m3c1)
- m3u1 = concatenate([m3u1, m1u1])
- m3u1 = concatenate([m3u1, m2u1])
- m3u1 = conv_bnorm(32, name='M3_conv_bnorm_u1') (m3u1)
- m3out = Conv2D(1, (1, 1), name='M3_output', activation='sigmoid') (m3u1)
- #-----------------------------------------------------------------------------
- m4inp = concatenate([m3u1, inputs])
- m4c1 = conv_bnorm(32, name='M4_conv_bnorm_d1') (m4inp)
- m4p1 = MaxPooling2D(name='M4_pool1') (m4c1)
- m4c2 = conv_bnorm(64, name='M4_conv_bnorm_d2') (m4p1)
- m4p2 = MaxPooling2D(name='M4_pool2') (m4c2)
- m4c3 = conv_bnorm(128, name='M4_conv_bnorm_d3') (m4p2)
- m4p3 = MaxPooling2D(name='M4_pool3') (m4c3)
- m4c4 = conv_bnorm(256, name='M4_conv_bnorm_d4') (m4p3)
- m4p4 = MaxPooling2D(name='M4_pool4') (m4c4)
- m4c5 = conv_bnorm(512, name='M4_conv_bnorm_d5') (m4p4)
- m4p5 = MaxPooling2D(name='M4_pool5') (m4c5)
- m4c6 = conv_bnorm(1024, name='M4_conv_bnorm_d6') (m4p5)
- m4u5 = SubpixelUpsampling(m4c6, m4c5)
- m4u5 = concatenate([m4u5, m1u5])
- m4u5 = concatenate([m4u5, m2u5])
- m4u5 = concatenate([m4u5, m3u5])
- m4u5 = conv_bnorm(512, name='M4_conv_bnorm_u5') (m4u5)
- m4u4 = SubpixelUpsampling(m4c5, m4c4)
- m4u4 = concatenate([m4u4, m1u4])
- m4u4 = concatenate([m4u4, m2u4])
- m4u4 = concatenate([m4u4, m3u4])
- m4u4 = conv_bnorm(256, name='M4_conv_bnorm_u4') (m4u4)
- m4u3 = SubpixelUpsampling(m4u4, m4c3)
- m4u3 = concatenate([m4u3, m1u3])
- m4u3 = concatenate([m4u3, m2u3])
- m4u3 = concatenate([m4u3, m3u3])
- m4u3 = conv_bnorm(128, name='M4_conv_bnorm_u3') (m4u3)
- m4u2 = SubpixelUpsampling(m4u3, m4c2)
- m4u2 = concatenate([m4u2, m1u2])
- m4u2 = concatenate([m4u2, m2u2])
- m4u2 = concatenate([m4u2, m3u2])
- m4u2 = conv_bnorm(64, name='M4_conv_bnorm_u2') (m4u2)
- m4u1 = SubpixelUpsampling(m4u2, m4c1)
- m4u1 = concatenate([m4u1, m1u1])
- m4u1 = concatenate([m4u1, m2u1])
- m4u1 = concatenate([m4u1, m3u1])
- m4u1 = conv_bnorm(32, name='M4_conv_bnorm_u1') (m4u1)
- m4out = Conv2D(1, (1, 1), name='M4_output', activation='sigmoid') (m4u1)
- K.clear_session()
- model = Model(inputs=[inputs], outputs=m4out)
- #K.clear_session()
- #model = Model(inputs=[inputs], outputs=[m1out, m2out, m3out, m4out])
- # %%
- from tensorflow.keras.layers import Lambda
- class conv_bnorm(tf.keras.layers.Layer):
- def __init__(self, f, **kwargs):
- super(conv_bnorm, self).__init__(**kwargs)
- self.conv_1 = Conv2D(f, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')
- self.norm_1 = BatchNormalization()
- self.conv_2 = Conv2D(f, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')
- self.norm_2 = BatchNormalization()
- def call(self, inputs):
- x = self.conv_1(inputs)
- x = self.norm_1(x)
- x = self.conv_2(x)
- x = self.norm_2(x)
- return x
- def SubpixelUpsampling(x, y):
- depth = tf.keras.backend.int_shape(x)[-1]
- def depth_to_space(x):
- return tf.nn.depth_to_space(x, 2)
- x = Conv2D(filters=depth*2, kernel_size=(1,1), strides=1, padding='same', )(x)
- x = Lambda(depth_to_space)(x)
- x = concatenate([x, y])
- return x
- inputs = Input((256,256,3), name='Input')
- m1c1 = conv_bnorm(32, name='M1_conv_bnorm_d1') (inputs)
- m1p1 = MaxPooling2D(name='M1_pool1') (m1c1)
- m1c2 = conv_bnorm(64, name='M1_conv_bnorm_d2') (m1p1)
- m1p2 = MaxPooling2D(name='M1_pool2') (m1c2)
- m1c3 = conv_bnorm(128, name='M1_conv_bnorm_d3') (m1p2)
- m1p3 = MaxPooling2D(name='M1_pool3') (m1c3)
- m1c4 = conv_bnorm(256, name='M1_conv_bnorm_d4') (m1p3)
- m1p4 = MaxPooling2D(name='M1_pool4') (m1c4)
- m1c5 = conv_bnorm(512, name='M1_conv_bnorm_d5') (m1p4)
- m1p5 = MaxPooling2D(name='M1_pool5') (m1c5)
- m1c6 = conv_bnorm(1024, name='M1_conv_bnorm_d6') (m1p5) # Bottleneck
- m1u5 = SubpixelUpsampling(m1c6, m1c5)
- m1u5 = conv_bnorm(512, name='M1_conv_bnorm5_u5') (m1u5)
- m1u4 = SubpixelUpsampling(m1u5, m1c4)
- m1u4 = conv_bnorm(256, name='M1_conv_bnorm_u4') (m1u4)
- m1u3 = SubpixelUpsampling(m1u4, m1c3)
- m1u3 = conv_bnorm(128, name='M1_conv_bnorm_u3') (m1u3)
- m1u2 = SubpixelUpsampling(m1u3, m1c2)
- m1u2 = conv_bnorm(64, name='M1_conv_bnorm_u2') (m1u2)
- m1u1 = SubpixelUpsampling(m1u2, m1c1)
- m1u1 = conv_bnorm(32, name='M1_conv_bnorm_u1') (m1u1)
- m1out = Conv2D(1, (1, 1), name='M1_output', activation='sigmoid') (m1u1) # Output
- #-----------------------------------------------------------------------------
- m2inp = concatenate([m1u1, inputs])
- m2c1 = conv_bnorm(32, name='M2_conv_bnorm_d1') (m2inp)
- m2p1 = MaxPooling2D(name='M2_pool1') (m2c1)
- m2c2 = conv_bnorm(64, name='M2_conv_bnorm_d2') (m2p1)
- m2p2 = MaxPooling2D(name='M2_pool2') (m2c2)
- m2c3 = conv_bnorm(128, name='M2_conv_bnorm_d3') (m2p2)
- m2p3 = MaxPooling2D(name='M2_pool3') (m2c3)
- m2c4 = conv_bnorm(256, name='M2_conv_bnorm_d4') (m2p3)
- m2p4 = MaxPooling2D(name='M2_pool4') (m2c4)
- m2c5 = conv_bnorm(512, name='M2_conv_bnorm_d5') (m2p4)
- m2p5 = MaxPooling2D(name='M2_pool5') (m2c5)
- m2c6 = conv_bnorm(1024, name='M2_conv_bnorm_d6') (m2p5)
- m2u5 = SubpixelUpsampling(m2c6, m2c5)
- m2u5 = concatenate([m2u5, m1u5])
- m2u5 = conv_bnorm(512, name='M2_conv_bnorm_u5') (m2u5)
- m2u4 = SubpixelUpsampling(m2c5, m2c4)
- m2u4 = concatenate([m2u4, m1u4])
- m2u4 = conv_bnorm(256, name='M2_conv_bnorm_u4') (m2u4)
- m2u3 = SubpixelUpsampling(m2u4, m2c3)
- m2u3 = concatenate([m2u3, m1u3])
- m2u3 = conv_bnorm(128, name='M2_conv_bnorm_u3') (m2u3)
- m2u2 = SubpixelUpsampling(m2u3, m2c2)
- m2u2 = concatenate([m2u2, m1u2])
- m2u2 = conv_bnorm(64, name='M2_conv_bnorm_u2') (m2u2)
- m2u1 = SubpixelUpsampling(m2u2, m2c1)
- m2u1 = concatenate([m2u1, m1u1])
- m2u1 = conv_bnorm(32, name='M2_conv_bnorm_u1') (m2u1)
- m2out = Conv2D(1, (1, 1), name='M2_output', activation='sigmoid') (m2u1)
- #-----------------------------------------------------------------------------
- m3inp = concatenate([m2u1, inputs])
- m3c1 = conv_bnorm(32, name='M3_conv_bnorm_d1') (m3inp)
- m3p1 = MaxPooling2D(name='M3_pool1') (m3c1)
- m3c2 = conv_bnorm(64, name='M3_conv_bnorm_d2') (m3p1)
- m3p2 = MaxPooling2D(name='M3_pool2') (m3c2)
- m3c3 = conv_bnorm(128, name='M3_conv_bnorm_d3') (m3p2)
- m3p3 = MaxPooling2D(name='M3_pool3') (m3c3)
- m3c4 = conv_bnorm(256, name='M3_conv_bnorm_d4') (m3p3)
- m3p4 = MaxPooling2D(name='M3_pool4') (m3c4)
- m3c5 = conv_bnorm(512, name='M3_conv_bnorm_d5') (m3p4)
- m3p5 = MaxPooling2D(name='M3_pool5') (m3c5)
- m3c6 = conv_bnorm(1024, name='M3_conv_bnorm_d6') (m3p5)
- m3u5 = SubpixelUpsampling(m3c6, m3c5)
- m3u5 = concatenate([m3u5, m1u5])
- m3u5 = concatenate([m3u5, m2u5])
- m3u5 = conv_bnorm(512, name='M3_conv_bnorm_u5') (m3u5)
- m3u4 = SubpixelUpsampling(m3c5, m3c4)
- m3u4 = concatenate([m3u4, m1u4])
- m3u4 = concatenate([m3u4, m2u4])
- m3u4 = conv_bnorm(256, name='M3_conv_bnorm_u4') (m3u4)
- m3u3 = SubpixelUpsampling(m3u4, m3c3)
- m3u3 = concatenate([m3u3, m1u3])
- m3u3 = concatenate([m3u3, m2u3])
- m3u3 = conv_bnorm(128, name='M3_conv_bnorm_u3') (m3u3)
- m3u2 = SubpixelUpsampling(m3u3, m3c2)
- m3u2 = concatenate([m3u2, m1u2])
- m3u2 = concatenate([m3u2, m2u2])
- m3u2 = conv_bnorm(64, name='M3_conv_bnorm_u2') (m3u2)
- m3u1 = SubpixelUpsampling(m3u2, m3c1)
- m3u1 = concatenate([m3u1, m1u1])
- m3u1 = concatenate([m3u1, m2u1])
- m3u1 = conv_bnorm(32, name='M3_conv_bnorm_u1') (m3u1)
- m3out = Conv2D(1, (1, 1), name='M3_output', activation='sigmoid') (m3u1)
- #-----------------------------------------------------------------------------
- m4inp = concatenate([m3u1, inputs])
- m4c1 = conv_bnorm(32, name='M4_conv_bnorm_d1') (m4inp)
- m4p1 = MaxPooling2D(name='M4_pool1') (m4c1)
- m4c2 = conv_bnorm(64, name='M4_conv_bnorm_d2') (m4p1)
- m4p2 = MaxPooling2D(name='M4_pool2') (m4c2)
- m4c3 = conv_bnorm(128, name='M4_conv_bnorm_d3') (m4p2)
- m4p3 = MaxPooling2D(name='M4_pool3') (m4c3)
- m4c4 = conv_bnorm(256, name='M4_conv_bnorm_d4') (m4p3)
- m4p4 = MaxPooling2D(name='M4_pool4') (m4c4)
- m4c5 = conv_bnorm(512, name='M4_conv_bnorm_d5') (m4p4)
- m4p5 = MaxPooling2D(name='M4_pool5') (m4c5)
- m4c6 = conv_bnorm(1024, name='M4_conv_bnorm_d6') (m4p5)
- m4u5 = SubpixelUpsampling(m4c6, m4c5)
- m4u5 = concatenate([m4u5, m1u5])
- m4u5 = concatenate([m4u5, m2u5])
- m4u5 = concatenate([m4u5, m3u5])
- m4u5 = conv_bnorm(512, name='M4_conv_bnorm_u5') (m4u5)
- m4u4 = SubpixelUpsampling(m4c5, m4c4)
- m4u4 = concatenate([m4u4, m1u4])
- m4u4 = concatenate([m4u4, m2u4])
- m4u4 = concatenate([m4u4, m3u4])
- m4u4 = conv_bnorm(256, name='M4_conv_bnorm_u4') (m4u4)
- m4u3 = SubpixelUpsampling(m4u4, m4c3)
- m4u3 = concatenate([m4u3, m1u3])
- m4u3 = concatenate([m4u3, m2u3])
- m4u3 = concatenate([m4u3, m3u3])
- m4u3 = conv_bnorm(128, name='M4_conv_bnorm_u3') (m4u3)
- m4u2 = SubpixelUpsampling(m4u3, m4c2)
- m4u2 = concatenate([m4u2, m1u2])
- m4u2 = concatenate([m4u2, m2u2])
- m4u2 = concatenate([m4u2, m3u2])
- m4u2 = conv_bnorm(64, name='M4_conv_bnorm_u2') (m4u2)
- m4u1 = SubpixelUpsampling(m4u2, m4c1)
- m4u1 = concatenate([m4u1, m1u1])
- m4u1 = concatenate([m4u1, m2u1])
- m4u1 = concatenate([m4u1, m3u1])
- m4u1 = conv_bnorm(32, name='M4_conv_bnorm_u1') (m4u1)
- m4out = Conv2D(1, (1, 1), name='M4_output', activation='sigmoid') (m4u1)
- K.clear_session()
- model = Model(inputs=[inputs], outputs=m4out)
- #K.clear_session()
- #model = Model(inputs=[inputs], outputs=[m1out, m2out, m3out, m4out])
- # %% [markdown]
- # loss, matric &compile
- # %%
- def dice_loss(y_true, y_pred):
- intersection = tf.reduce_sum(y_true * y_pred) + 1.0
- dice_score = (2. * intersection + 1.0) / (tf.reduce_sum(y_true) + tf.reduce_sum(y_pred) + 1.0)
- dice_loss = 1. - dice_score
- return dice_loss
- def dice(y_true, y_pred):
- intersection = tf.reduce_sum(y_true * y_pred) + 1.0
- dice_score = (2. * intersection + 1.0) / (tf.reduce_sum(y_true) + tf.reduce_sum(y_pred) + 1.0)
- return dice_score
- def bce_dice_loss(y_true, y_pred):
- return binary_crossentropy(y_true, y_pred) + dice_loss(y_true, y_pred)
- def iou(y_true, y_pred):
- y_true = tf.cast(y_true>0.5, tf.float32)
- y_pred = tf.cast(y_pred>0.5, tf.float32)
- intersection = tf.reduce_sum(y_true * y_pred) + 1.0
- union = tf.reduce_sum(y_true) + tf.reduce_sum(y_pred) - intersection + 1.0
- iou = intersection/union
- return iou
- # %%
- import numpy as np
- from sklearn.metrics import roc_auc_score
- import time
- auc_scores = []
- start = time.time()
- for i in range(5):
- print(f"\n🔥 Run {i+1}")
- # 🔥 CLEAR OLD MODEL
- import tensorflow as tf
- tf.keras.backend.clear_session()
- # 🔥 RE-RUN MODEL CELLS MANUALLY (IMPORTANT)
- # 👉 இங்க code இல்ல — மேல உள்ள model cells run ஆகணும்
- # 👉 இப்ப model already memoryல இருக்கும்
- model.compile(
- optimizer='adam',
- loss='binary_crossentropy',
- metrics=[iou, dice]
- )
- model.fit(
- ds_train,
- steps_per_epoch=20,
- epochs=40,
- validation_data=ds_valid,
- validation_steps=4,
- verbose=1
- )
- y_true = []
- y_pred = []
- for x, y in ds_valid:
- preds = model.predict(x)
- y_true.extend(y.numpy().flatten())
- y_pred.extend(preds.flatten())
- if len(y_true) > 1000:
- break
- auc = roc_auc_score(y_true, y_pred)
- print("AUC:", auc)
- auc_scores.append(auc)
- end = time.time()
- print("\n📊 AUC Scores:", auc_scores)
- print("⏱️ Training Time:", end - start)
- # %%
- import matplotlib.pyplot as plt
- import numpy as np
- auc_scores = [0.9629, 0.9581, 0.9499, 0.9563, 0.9524]
- runs = np.arange(1, len(auc_scores)+1)
- plt.figure()
- plt.bar(runs, auc_scores)
- plt.xlabel("Run Number")
- plt.ylabel("AUC Score")
- plt.title("AUC Across Multiple Runs")
- plt.xticks(runs)
- plt.ylim(0.94, 0.97)
- plt.show()
- # %%
- import matplotlib.pyplot as plt
- import numpy as np
- auc_scores = np.array([0.9629, 0.9581, 0.9499, 0.9563, 0.9524])
- mean_auc = np.mean(auc_scores)
- std_auc = np.std(auc_scores)
- ci = 1.96 * (std_auc / np.sqrt(len(auc_scores)))
- plt.figure()
- plt.errorbar(1, mean_auc, yerr=ci, fmt='o', capsize=5)
- plt.xlim(0, 2)
- plt.xticks([1], ["Model"])
- plt.ylabel("AUC Score")
- plt.title("Mean AUC with 95% Confidence Interval")
- plt.ylim(0.94, 0.97)
- plt.show()
- # %%
- plt.figure()
- plt.plot(runs, auc_scores, marker='o')
- plt.xlabel("Run Number")
- plt.ylabel("AUC Score")
- plt.title("AUC Stability Across Runs")
- plt.grid()
- plt.show()
- # %%
- from tensorflow.keras.optimizers import Nadam
- from tensorflow.keras.optimizers import Adam
- model.compile(
- optimizer='adam',
- loss='binary_crossentropy',
- metrics=[iou, dice]
- )
- # %%
- from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau
- earlystopping = EarlyStopping(
- monitor='val_loss',
- min_delta=0,
- patience=10,
- verbose=1,
- restore_best_weights=True)
- reducelr = ReduceLROnPlateau(
- monitor='val_loss',
- factor=0.1,
- patience=3,
- verbose=1,
- min_delta=0.0001 )
- callbacks = [earlystopping, reducelr]
- # %%
- tf.keras.utils.plot_model(
- model, to_file='model_UNET++.png', show_shapes=False, show_layer_names=True,
- rankdir='TB', expand_nested=False, dpi=50
- )
- # %%
- model.summary()
- # %% [markdown]
- # **fit**
- # %%
- import os
- save_path = "/content/drive/My Drive/Vessel_Project"
- # Create folder if not exists
- os.makedirs(save_path, exist_ok=True)
- print("✅ Folder Ready")
- # %%
- # Mount Google Drive
- # Save model
- model.save("/content/drive/My Drive/Vessel_Project/vessel_model.keras")
- print("✅ Model Saved Successfully")
- # %%
- print(model.output_shape)
- # %%
- test_generator = Val_Generator(test_images_files, test_mask_files,
- batch_size=20,
- img_dim=(batch_img_dim[1], batch_img_dim[2]),
- augmentation=True)
- for x_test, y_test in test_generator:
- break
- # ✅ FIX HERE (remove [0])
- y_pred = model.predict(x_test)
- # Flatten
- y_true = (y_test > 0.5).astype(np.uint8).flatten()
- y_pred = (y_pred > 0.5).astype(np.uint8).flatten()
- from sklearn.metrics import classification_report, roc_auc_score
- report = classification_report(y_true, y_pred, output_dict=True)
- Precision = report['1']['precision']
- Recall = report['1']['recall']
- F1_score = report['1']['f1-score']
- Sensitivity = Recall
- Specificity = report['0']['recall']
- IOU = (Precision * Recall) / (Precision + Recall - Precision * Recall)
- # ⚠️ AUC (use probability before threshold)
- y_pred_prob = model.predict(x_test).flatten()
- AUC = roc_auc_score(y_true, y_pred_prob)
- print("Precision score: {0:.2f}\n".format(Precision))
- print("Recall score: {0:.2f}\n".format(Recall))
- print("F1-Score: {0:.2f}\n".format(F1_score))
- print("Sensitivity: {0:.2f}\n".format(Sensitivity))
- print("Specificity: {0:.2f}\n".format(Specificity))
- print("IOU: {0:.2f}\n".format(IOU))
- print("AUC: {0:.2f}\n".format(AUC))
- print('-'*50,'\n')
- print(classification_report(y_true, y_pred))
- # %%
- # Get one batch
- for x_test, y_test in test_generator:
- break
- # Predict
- y_pred_prob = model.predict(x_test)
- # ✅ Ensure same shape
- print("y_test shape:", y_test.shape)
- print("y_pred shape:", y_pred_prob.shape)
- # Flatten BOTH equally
- y_true = y_test.reshape(-1)
- y_pred_prob = y_pred_prob.reshape(-1)
- # Threshold
- y_pred = (y_pred_prob > 0.5).astype(np.uint8)
- y_true = (y_true > 0.5).astype(np.uint8)
- from sklearn.metrics import classification_report, roc_auc_score
- # ✅ NOW NO ERROR
- report = classification_report(y_true, y_pred, output_dict=True)
- Precision = report['1']['precision']
- Recall = report['1']['recall']
- F1_score = report['1']['f1-score']
- Sensitivity = Recall
- Specificity = report['0']['recall']
- IOU = (Precision * Recall) / (Precision + Recall - Precision * Recall)
- # AUC (use probability)
- AUC = roc_auc_score(y_true, y_pred_prob)
- print("Precision:", Precision)
- print("Recall:", Recall)
- print("F1:", F1_score)
- print("Sensitivity:", Sensitivity)
- print("Specificity:", Specificity)
- print("IOU:", IOU)
- print("AUC:", AUC)
- print("\n", classification_report(y_true, y_pred))
- # %%
- test_generator = Val_Generator(test_images_files, test_mask_files,
- batch_size=20,
- img_dim=(batch_img_dim[1], batch_img_dim[2]),
- augmentation=True)
- for x_test, y_test in test_generator:
- break
- # ✅ PREDICT (NO INDEX)
- y_pred_prob = model.predict(x_test)
- # ✅ SAME SHAPE CHECK
- print("y_test:", y_test.shape)
- print("y_pred:", y_pred_prob.shape)
- # Flatten
- y_true = (y_test > 0.5).astype(np.uint8).reshape(-1)
- y_pred_prob = y_pred_prob.reshape(-1)
- # Threshold
- y_pred = (y_pred_prob > 0.5).astype(np.uint8)
- from sklearn.metrics import classification_report, roc_auc_score
- report = classification_report(y_true, y_pred, output_dict=True)
- Precision = report['1']['precision']
- Recall = report['1']['recall']
- F1_score = report['1']['f1-score']
- Sensitivity = Recall
- Specificity = report['0']['recall']
- IOU = (Precision * Recall) / (Precision + Recall - Precision * Recall)
- # ✅ AUC (USE PROBABILITY)
- AUC = roc_auc_score(y_true, y_pred_prob)
- print("Precision:", Precision)
- print("Recall:", Recall)
- print("F1:", F1_score)
- print("Sensitivity:", Sensitivity)
- print("Specificity:", Specificity)
- print("IOU:", IOU)
- print("AUC:", AUC)
- print("\n", classification_report(y_true, y_pred))
- # %%
- for x_test, y_test in test_generator:
- break
- # ✅ NO INDEX
- y_pred_prob = model.predict(x_test)
- # Flatten properly
- y_true = (y_test > 0.5).astype(np.uint8).reshape(-1)
- y_pred_prob = y_pred_prob.reshape(-1)
- # Threshold
- y_pred = (y_pred_prob > 0.5).astype(np.uint8)
- from sklearn.metrics import classification_report, roc_auc_score
- report = classification_report(y_true, y_pred, output_dict=True)
- Precision = report['1']['precision']
- Recall = report['1']['recall']
- F1_score = report['1']['f1-score']
- Sensitivity = Recall
- Specificity = report['0']['recall']
- IOU = (Precision * Recall) / (Precision + Recall - Precision * Recall)
- AUC = roc_auc_score(y_true, y_pred_prob)
- print("Precision:", Precision)
- print("Recall:", Recall)
- print("F1:", F1_score)
- print("Sensitivity:", Sensitivity)
- print("Specificity:", Specificity)
- print("IOU:", IOU)
- print("AUC:", AUC)
- print("\n", classification_report(y_true, y_pred))
- # %%
- test_generator = Val_Generator(test_images_files, test_mask_files,
- batch_size=20,
- img_dim=(batch_img_dim[1], batch_img_dim[2]),
- augmentation=True)
- for x_test, y_test in test_generator:
- break
- # ✅ ONLY THIS
- y_pred_prob = model.predict(x_test)
- # Shape check (optional but useful)
- print("y_test:", y_test.shape)
- print("y_pred:", y_pred_prob.shape)
- # Flatten properly
- y_true = (y_test > 0.5).astype(np.uint8).reshape(-1)
- y_pred_prob = y_pred_prob.reshape(-1)
- # Threshold
- y_pred = (y_pred_prob > 0.5).astype(np.uint8)
- from sklearn.metrics import classification_report, roc_auc_score
- report = classification_report(y_true, y_pred, output_dict=True)
- Precision = report['1']['precision']
- Recall = report['1']['recall']
- F1_score = report['1']['f1-score']
- Sensitivity = Recall
- Specificity = report['0']['recall']
- IOU = (Precision * Recall) / (Precision + Recall - Precision * Recall)
- AUC = roc_auc_score(y_true, y_pred_prob)
- print("Precision:", Precision)
- print("Recall:", Recall)
- print("F1:", F1_score)
- print("Sensitivity:", Sensitivity)
- print("Specificity:", Specificity)
- print("IOU:", IOU)
- print("AUC:", AUC)
- print("\n", classification_report(y_true, y_pred))
- # %%
- valid_generator = Val_Generator(
- test_images_files,
- test_mask_files,
- batch_size=1,
- img_dim=(batch_img_dim[1], batch_img_dim[2]),
- augmentation=False
- )
- x_val = []
- y_val = []
- p_val = []
- for x, y in valid_generator:
- # ✅ ONLY ONE PREDICTION
- pred = model.predict(x)
- x_val.append(np.squeeze(x, 0))
- y_val.append(np.squeeze(y, 0))
- p_val.append(np.squeeze(pred, 0))
- # Convert to array
- x_val = np.array(x_val)
- y_val = np.array(y_val)
- p_val = np.array(p_val)
- # %%
- # ================== INIT (MUST ADD FIRST) ==================
- x_val = []
- y_val = []
- p_val1 = []
- p_val2 = []
- p_val3 = []
- p_val4 = []
- p_val5 = []
- # ================== PREDICTION LOOP ==================
- for x, y in valid_generator:
- preds = model.predict(x) # ✅ only once (VERY IMPORTANT)
- # ✅ Handle multi-output / single-output
- if isinstance(preds, list):
- p1 = (preds[0] + preds[1] + preds[2] + preds[3]) / 4
- p2 = preds[3]
- p3 = preds[2]
- p4 = preds[1]
- p5 = preds[0]
- else:
- p1 = preds
- p2 = preds
- p3 = preds
- p4 = preds
- p5 = preds
- # ✅ Store values
- x_val.append(np.squeeze(x, axis=0))
- y_val.append(np.squeeze(y, axis=0))
- p_val1.append(np.squeeze(p1, axis=0))
- p_val2.append(np.squeeze(p2, axis=0))
- p_val3.append(np.squeeze(p3, axis=0))
- p_val4.append(np.squeeze(p4, axis=0))
- p_val5.append(np.squeeze(p5, axis=0))
- # ================== CONVERT TO NUMPY ==================
- x_val = np.array(x_val)
- y_val = np.array(y_val)
- p_val1 = np.array(p_val1)
- p_val2 = np.array(p_val2)
- p_val3 = np.array(p_val3)
- p_val4 = np.array(p_val4)
- p_val5 = np.array(p_val5)
- # ================== PLOTTING ==================
- num = min(5, len(x_val)) # ✅ avoid empty plots
- figsize = (20, 3)
- # 🔹 Images
- fig, axes = plt.subplots(1, num, figsize=figsize)
- fig.suptitle('Images', fontsize=15)
- for img, ax in zip(x_val[:num], axes):
- ax.imshow(img)
- ax.axis('off')
- plt.tight_layout()
- plt.show()
- # 🔹 Ground Truth
- fig, axes = plt.subplots(1, num, figsize=figsize)
- fig.suptitle('Original Masks', fontsize=15)
- for img, ax in zip(y_val[:num], axes):
- ax.imshow(np.squeeze(img), cmap='gray')
- ax.axis('off')
- plt.tight_layout()
- plt.show()
- # 🔹 Predicted (Average of 4)
- fig, axes = plt.subplots(1, num, figsize=figsize)
- fig.suptitle('Predicted Masks (All Outputs Fusion)', fontsize=15)
- for img, ax in zip(p_val1[:num], axes):
- ax.imshow(np.squeeze(img), cmap='gray')
- ax.axis('off')
- plt.tight_layout()
- plt.show()
- # 🔹 Output 4
- fig, axes = plt.subplots(1, num, figsize=figsize)
- fig.suptitle('Predicted Masks (Output 4)', fontsize=15)
- for img, ax in zip(p_val2[:num], axes):
- ax.imshow(np.squeeze(img), cmap='gray')
- ax.axis('off')
- plt.tight_layout()
- plt.show()
- # 🔹 Output 3
- fig, axes = plt.subplots(1, num, figsize=figsize)
- fig.suptitle('Predicted Masks (Output 3)', fontsize=15)
- for img, ax in zip(p_val3[:num], axes):
- ax.imshow(np.squeeze(img), cmap='gray')
- ax.axis('off')
- plt.tight_layout()
- plt.show()
- # 🔹 Output 2
- fig, axes = plt.subplots(1, num, figsize=figsize)
- fig.suptitle('Predicted Masks (Output 2)', fontsize=15)
- for img, ax in zip(p_val4[:num], axes):
- ax.imshow(np.squeeze(img), cmap='gray')
- ax.axis('off')
- plt.tight_layout()
- plt.show()
- # 🔹 Output 1
- fig, axes = plt.subplots(1, num, figsize=figsize)
- fig.suptitle('Predicted Masks (Output 1)', fontsize=15)
- for img, ax in zip(p_val5[:num], axes):
- ax.imshow(np.squeeze(img), cmap='gray')
- ax.axis('off')
- plt.tight_layout()
- plt.show()
- # %%
- # ✅ Generate prediction AFTER training (safe placement)
- try:
- y_pred_prob = model.predict(X_test)
- except NameError:
- print("Model ")
- # %%
- # ✅ Improved AUC Calculation (no effect on other metrics)
- from sklearn.metrics import roc_auc_score, confusion_matrix, accuracy_score, precision_score, recall_score, f1_score, roc_curve
- import numpy as np
- import matplotlib.pyplot as plt
- # ----------------------------
- # Check variable
- # ----------------------------
- if 'y_pred_prob' not in globals():
- raise ValueError("y_pred_prob not found")
- # ----------------------------
- # Flatten (segmentation case)
- # ----------------------------
- y_true = y_test.flatten()
- y_prob = y_pred_prob.flatten()
- # Binary prediction
- y_pred = (y_prob > 0.5).astype(int)
- # ----------------------------
- # Confusion Matrix
- # ----------------------------
- tn, fp, fn, tp = confusion_matrix(y_true, y_pred).ravel()
- # ----------------------------
- # Metrics
- # ----------------------------
- accuracy = (tp + tn) / (tp + tn + fp + fn)
- sensitivity = tp / (tp + fn + 1e-7) # Recall
- specificity = tn / (tn + fp + 1e-7)
- precision = tp / (tp + fp + 1e-7)
- f1 = f1_score(y_true, y_pred)
- # IoU (Jaccard Index)
- iou = tp / (tp + fp + fn + 1e-7)
- # Dice Coefficient
- dice = (2 * tp) / (2 * tp + fp + fn + 1e-7)
- # AUC
- epsilon = 1e-6
- y_prob = np.clip(y_prob, epsilon, 1 - epsilon)
- auc = roc_auc_score(y_true, y_prob)
- # ----------------------------
- # Print Results
- # ----------------------------
- print("Accuracy :", round(accuracy, 4))
- print("Specificity :", round(specificity, 4))
- print("Sensitivity :", round(sensitivity, 4))
- print("Precision :", round(precision, 4))
- print("F1 Score :", round(f1, 4))
- print("IoU :", round(iou, 4))
- print("Dice Score :", round(dice, 4))
- print("AUC :", round(auc, 4))
- # ----------------------------
- # ROC Curve
- # ----------------------------
- fpr, tpr, _ = roc_curve(y_true, y_prob)
- plt.figure()
- plt.plot(fpr, tpr, label=f"AUC = {auc:.3f}")
- plt.plot([0, 1], [0, 1], linestyle='--')
- plt.xlabel("False Positive Rate")
- plt.ylabel("True Positive Rate")
- plt.title("ROC Curve")
- plt.legend()
- plt.grid()
- plt.show()
- # %%
- # =============================
- # IMPORTS
- # =============================
- import numpy as np
- import matplotlib.pyplot as plt
- from sklearn.metrics import (
- roc_auc_score, confusion_matrix, f1_score,
- roc_curve, precision_score, recall_score
- )
- # =============================
- # CHECK VARIABLES
- # =============================
- if 'y_pred_prob' not in globals() or 'y_test' not in globals():
- raise ValueError("❌ y_test or y_pred_prob not found. Run prediction first.")
- # =============================
- # PREPARE DATA
- # =============================
- y_true = y_test.flatten()
- y_prob = y_pred_prob.flatten()
- # Threshold
- y_pred = (y_prob > 0.5).astype(int)
- # =============================
- # CONFUSION MATRIX VALUES
- # =============================
- tn, fp, fn, tp = confusion_matrix(y_true, y_pred).ravel()
- # =============================
- # METRICS
- # =============================
- accuracy = (tp + tn) / (tp + tn + fp + fn)
- sensitivity = tp / (tp + fn + 1e-7)
- specificity = tn / (tn + fp + 1e-7)
- precision = precision_score(y_true, y_pred)
- recall = recall_score(y_true, y_pred)
- f1 = f1_score(y_true, y_pred)
- iou = tp / (tp + fp + fn + 1e-7)
- dice = (2 * tp) / (2 * tp + fp + fn + 1e-7)
- # AUC
- epsilon = 1e-6
- y_prob = np.clip(y_prob, epsilon, 1 - epsilon)
- auc = roc_auc_score(y_true, y_prob)
- # =============================
- # PRINT RESULTS
- # =============================
- print("\n📊 PERFORMANCE METRICS")
- print("Accuracy :", round(accuracy, 4))
- print("Specificity :", round(specificity, 4))
- print("Sensitivity :", round(sensitivity, 4))
- print("Precision :", round(precision, 4))
- print("Recall :", round(recall, 4))
- print("F1 Score :", round(f1, 4))
- print("IoU :", round(iou, 4))
- print("Dice Score :", round(dice, 4))
- print("AUC :", round(auc, 4))
- # =============================
- # ROC CURVE
- # =============================
- fpr, tpr, _ = roc_curve(y_true, y_prob)
- plt.figure()
- plt.plot(fpr, tpr, label=f"AUC = {auc:.4f}")
- plt.plot([0, 1], [0, 1], linestyle='--')
- plt.xlabel("False Positive Rate")
- plt.ylabel("True Positive Rate")
- plt.title("ROC Curve")
- plt.legend()
- plt.grid()
- plt.show()
- # =============================
- # CONFUSION MATRIX (REFINED)
- # =============================
- cm = confusion_matrix(y_true, y_pred)
- plt.figure(figsize=(6,5))
- plt.imshow(cm, cmap='Blues')
- plt.title("Confusion Matrix")
- plt.xlabel("Predicted Label")
- plt.ylabel("True Label")
- plt.xticks([0,1], ["Pred 0", "Pred 1"])
- plt.yticks([0,1], ["True 0", "True 1"])
- threshold = cm.max() / 2
- for i in range(cm.shape[0]):
- for j in range(cm.shape[1]):
- color = "white" if cm[i, j] > threshold else "black"
- plt.text(j, i, f"{cm[i, j]}",
- ha="center", va="center",
- color=color, fontsize=12, fontweight='bold')
- plt.colorbar()
- plt.tight_layout()
- plt.show()
- # =============================
- # BOOTSTRAP CI
- # =============================
- def bootstrap_ci(y_true, y_pred, metric_func, n_bootstrap=500):
- scores = []
- n = len(y_true)
- for _ in range(n_bootstrap):
- idx = np.random.choice(n, n, replace=True)
- score = metric_func(y_true[idx], y_pred[idx])
- scores.append(score)
- scores = np.array(scores)
- return scores.mean(), np.percentile(scores, 2.5), np.percentile(scores, 97.5)
- # =============================
- # CUSTOM METRICS FOR CI
- # =============================
- def dice_func(y_true, y_pred):
- intersection = np.sum(y_true * y_pred)
- return (2 * intersection) / (np.sum(y_true) + np.sum(y_pred) + 1e-6)
- def iou_func(y_true, y_pred):
- intersection = np.sum(y_true * y_pred)
- union = np.sum(y_true) + np.sum(y_pred) - intersection
- return intersection / (union + 1e-6)
- # =============================
- # CALCULATE CI
- # =============================
- mean_auc, low_auc, high_auc = bootstrap_ci(y_true, y_prob, roc_auc_score)
- mean_f1, low_f1, high_f1 = bootstrap_ci(y_true, y_pred, f1_score)
- mean_dice, low_dice, high_dice = bootstrap_ci(y_true, y_pred, dice_func)
- mean_iou, low_iou, high_iou = bootstrap_ci(y_true, y_pred, iou_func)
- mean_prec, low_prec, high_prec = bootstrap_ci(y_true, y_pred, precision_score)
- mean_rec, low_rec, high_rec = bootstrap_ci(y_true, y_pred, recall_score)
- # =============================
- # PRINT CI RESULTS
- # =============================
- print("\n📈 STATISTICAL ANALYSIS (95% CI)")
- print(f"AUC : {mean_auc:.4f} ({low_auc:.4f} - {high_auc:.4f})")
- print(f"Dice : {mean_dice:.4f} ({low_dice:.4f} - {high_dice:.4f})")
- print(f"IoU : {mean_iou:.4f} ({low_iou:.4f} - {high_iou:.4f})")
- print(f"F1 Score : {mean_f1:.4f} ({low_f1:.4f} - {high_f1:.4f})")
- print(f"Precision : {mean_prec:.4f} ({low_prec:.4f} - {high_prec:.4f})")
- print(f"Recall : {mean_rec:.4f} ({low_rec:.4f} - {high_rec:.4f})")
- # %%
- # =============================
- # RANDOM SEED (REPRODUCIBILITY)
- # =============================
- import os, random, time
- import numpy as np
- import tensorflow as tf
- SEED = 42
- os.environ['PYTHONHASHSEED'] = str(SEED)
- random.seed(SEED)
- np.random.seed(SEED)
- tf.random.set_seed(SEED)
- print(f"✅ Random Seed Set: {SEED}")
- # =============================
- # IMPORTS
- # =============================
- import matplotlib.pyplot as plt
- from sklearn.metrics import (
- roc_auc_score, confusion_matrix, f1_score,
- roc_curve, precision_score, recall_score
- )
- from sklearn.model_selection import train_test_split
- # =============================
- # CHECK VARIABLES
- # =============================
- if 'y_pred_prob' not in globals() or 'y_test' not in globals():
- raise ValueError("❌ y_test or y_pred_prob not found. Run prediction first.")
- # =============================
- # PREPARE DATA
- # =============================
- y_true = y_test.flatten()
- y_prob = y_pred_prob.flatten()
- # Threshold
- y_pred = (y_prob > 0.5).astype(int)
- # =============================
- # TRAINING TIME (example placeholder)
- # =============================
- # 👉 NOTE: இந்த பகுதி model.fit() இருக்கும் இடத்தில add பண்ணணும்
- # Example:
- # start_train = time.time()
- # model.fit(...)
- # end_train = time.time()
- # training_time = end_train - start_train
- training_time = "ADD_WHERE_MODEL_FIT"
- # =============================
- # INFERENCE TIME
- # =============================
- start_inf = time.time()
- _ = y_pred_prob # already predicted (if not, use model.predict)
- end_inf = time.time()
- inference_time = end_inf - start_inf
- per_image_time = inference_time / len(y_true)
- # =============================
- # CONFUSION MATRIX VALUES
- # =============================
- tn, fp, fn, tp = confusion_matrix(y_true, y_pred).ravel()
- # =============================
- # METRICS
- # =============================
- accuracy = (tp + tn) / (tp + tn + fp + fn)
- sensitivity = tp / (tp + fn + 1e-7)
- specificity = tn / (tn + fp + 1e-7)
- precision = precision_score(y_true, y_pred)
- recall = recall_score(y_true, y_pred)
- f1 = f1_score(y_true, y_pred)
- iou = tp / (tp + fp + fn + 1e-7)
- dice = (2 * tp) / (2 * tp + fp + fn + 1e-7)
- # AUC
- epsilon = 1e-6
- y_prob = np.clip(y_prob, epsilon, 1 - epsilon)
- auc = roc_auc_score(y_true, y_prob)
- # =============================
- # PRINT RESULTS
- # =============================
- print("\n📊 PERFORMANCE METRICS")
- print("Accuracy :", round(accuracy, 4))
- print("Specificity :", round(specificity, 4))
- print("Sensitivity :", round(sensitivity, 4))
- print("Precision :", round(precision, 4))
- print("Recall :", round(recall, 4))
- print("F1 Score :", round(f1, 4))
- print("IoU :", round(iou, 4))
- print("Dice Score :", round(dice, 4))
- print("AUC :", round(auc, 4))
- print("\n⏱️ TIMING")
- print(f"Inference Time (Total): {inference_time:.4f} sec")
- print(f"Inference Time per image: {per_image_time:.6f} sec")
- # =============================
- # ROC CURVE
- # =============================
- fpr, tpr, _ = roc_curve(y_true, y_prob)
- plt.figure()
- plt.plot(fpr, tpr, label=f"AUC = {auc:.4f}")
- plt.plot([0, 1], [0, 1], linestyle='--')
- plt.xlabel("False Positive Rate")
- plt.ylabel("True Positive Rate")
- plt.title("ROC Curve")
- plt.legend()
- plt.grid()
- plt.show()
- # =============================
- # CONFUSION MATRIX (REFINED)
- # =============================
- cm = confusion_matrix(y_true, y_pred)
- plt.figure(figsize=(6,5))
- plt.imshow(cm, cmap='Blues')
- plt.title("Confusion Matrix")
- plt.xlabel("Predicted Label")
- plt.ylabel("True Label")
- plt.xticks([0,1], ["Pred 0", "Pred 1"])
- plt.yticks([0,1], ["True 0", "True 1"])
- threshold = cm.max() / 2
- for i in range(cm.shape[0]):
- for j in range(cm.shape[1]):
- color = "white" if cm[i, j] > threshold else "black"
- plt.text(j, i, f"{cm[i, j]}",
- ha="center", va="center",
- color=color, fontsize=12, fontweight='bold')
- plt.colorbar()
- plt.tight_layout()
- plt.show()
- # =============================
- # BOOTSTRAP CI
- # =============================
- def bootstrap_ci(y_true, y_pred, metric_func, n_bootstrap=500):
- scores = []
- n = len(y_true)
- for _ in range(n_bootstrap):
- idx = np.random.choice(n, n, replace=True)
- score = metric_func(y_true[idx], y_pred[idx])
- scores.append(score)
- scores = np.array(scores)
- return scores.mean(), np.percentile(scores, 2.5), np.percentile(scores, 97.5)
- # =============================
- # CUSTOM METRICS FOR CI
- # =============================
- def dice_func(y_true, y_pred):
- intersection = np.sum(y_true * y_pred)
- return (2 * intersection) / (np.sum(y_true) + np.sum(y_pred) + 1e-6)
- def iou_func(y_true, y_pred):
- intersection = np.sum(y_true * y_pred)
- union = np.sum(y_true) + np.sum(y_pred) - intersection
- return intersection / (union + 1e-6)
- # =============================
- # CALCULATE CI
- # =============================
- mean_auc, low_auc, high_auc = bootstrap_ci(y_true, y_prob, roc_auc_score)
- mean_f1, low_f1, high_f1 = bootstrap_ci(y_true, y_pred, f1_score)
- mean_dice, low_dice, high_dice = bootstrap_ci(y_true, y_pred, dice_func)
- mean_iou, low_iou, high_iou = bootstrap_ci(y_true, y_pred, iou_func)
- mean_prec, low_prec, high_prec = bootstrap_ci(y_true, y_pred, precision_score)
- mean_rec, low_rec, high_rec = bootstrap_ci(y_true, y_pred, recall_score)
- # =============================
- # PRINT CI RESULTS
- # =============================
- print("\n📈 STATISTICAL ANALYSIS (95% CI)")
- print(f"AUC : {mean_auc:.4f} ({low_auc:.4f} - {high_auc:.4f})")
- print(f"Dice : {mean_dice:.4f} ({low_dice:.4f} - {high_dice:.4f})")
- print(f"IoU : {mean_iou:.4f} ({low_iou:.4f} - {high_iou:.4f})")
- print(f"F1 Score : {mean_f1:.4f} ({low_f1:.4f} - {high_f1:.4f})")
- print(f"Precision : {mean_prec:.4f} ({low_prec:.4f} - {high_prec:.4f})")
- print(f"Recall : {mean_rec:.4f} ({low_rec:.4f} - {high_rec:.4f})")
- # %%
- import matplotlib.pyplot as plt
- # =============================
- # METRICS VALUES
- # =============================
- metrics = [
- "Accuracy", "Specificity", "Sensitivity",
- "Precision", "Recall", "F1 Score",
- "IoU", "Dice", "AUC"
- ]
- values = [
- 0.9494, 0.976, 0.8254,
- 0.881, 0.8254, 0.8523,
- 0.7426, 0.8523, 0.9718
- ]
- # =============================
- # BAR GRAPH
- # =============================
- plt.figure(figsize=(10,5))
- plt.bar(metrics, values)
- # Labels
- plt.xlabel("Metrics")
- plt.ylabel("Score")
- plt.title(" Proposed Model Performance Metrics")
- # Rotate x labels
- plt.xticks(rotation=30)
- # Add values on top
- for i, v in enumerate(values):
- plt.text(i, v + 0.01, f"{v:.2f}", ha='center')
- plt.ylim(0, 1.05)
- plt.grid()
- plt.tight_layout()
- plt.show()
- # %%
- import matplotlib.pyplot as plt
- from sklearn.metrics import roc_curve, auc, precision_recall_curve
- # =============================
- # CHECK VARIABLES
- # =============================
- if 'y_pred_prob' not in globals() or 'y_test' not in globals():
- raise ValueError("❌ y_test or y_pred_prob not found")
- # =============================
- # PREPARE DATA
- # =============================
- y_true = y_test.flatten()
- y_prob = y_pred_prob.flatten()
- # =============================
- # ROC CURVE
- # =============================
- fpr, tpr, _ = roc_curve(y_true, y_prob)
- roc_auc = auc(fpr, tpr)
- plt.figure(figsize=(6,5))
- plt.plot(fpr, tpr, label=f"AUC = {roc_auc:.4f}")
- plt.plot([0,1], [0,1], linestyle='--')
- plt.xlabel("False Positive Rate")
- plt.ylabel("True Positive Rate")
- plt.title("ROC Curve")
- plt.legend(loc="lower right")
- plt.grid()
- plt.tight_layout()
- plt.show()
- # =============================
- # PRECISION-RECALL CURVE
- # =============================
- precision, recall, _ = precision_recall_curve(y_true, y_prob)
- pr_auc = auc(recall, precision)
- plt.figure(figsize=(6,5))
- plt.plot(recall, precision, label=f"PR AUC = {pr_auc:.4f}")
- plt.xlabel("Recall")
- plt.ylabel("Precision")
- plt.title("Precision-Recall Curve")
- plt.legend(loc="lower left")
- plt.grid()
- plt.tight_layout()
- plt.show()
- # %%
- import matplotlib.pyplot as plt
- metrics = ['AUC', 'Dice', 'IoU', 'F1', 'Precision', 'Recall']
- means = [0.9710, 0.8523, 0.7426, 0.8523, 0.8810, 0.8255]
- # CI half-width (upper-lower)/2
- errors = [
- (0.9714-0.9706)/2,
- (0.8534-0.8511)/2,
- (0.7442-0.7407)/2,
- (0.8535-0.8513)/2,
- (0.8822-0.8796)/2,
- (0.8271-0.8239)/2
- ]
- plt.figure()
- plt.bar(metrics, means, yerr=errors)
- plt.xlabel("Metrics")
- plt.ylabel("Values")
- plt.title("Performance with 95% Confidence Intervals")
- plt.show()
- # %%
- print(type(x_test))
- print(x_test.shape)
- print(type(y_test))
- # %%
- print(type(model))
41598_2026_48475_MOESM2_ESM.ipynb, no license · at the source
Overview
- Computer Science and Engineering, University College of Engineering Villupuram, Villupuram, Tamilnadu India
- Electronics and Communication Engineering, V R S College of Engineering and Technology, Arasur, Tamilnadu India
- Faculty of Business and Communications, INTI International University, Persiaran Perdana BBN Putra Nilai, Nilai, Negeri Sembilan 71800 Malaysia
- Information Technology, St. Joseph’s College of Engineering, Chennai, Tamilnadu India
Abstract
The abstract is not reproduced here: the paper's license (CC BY-NC-ND) does not allow it. Read it in the paper, at the publisher or on Europe PMC.
Repositories
Its files are read in the Code ↔ Paper reader above, with 4 matches between paragraphs and lines of code.
supp:PMC13234283/41598_2026_48475_MOESM1_ESM.ipynb
Availability: 1 check, the latest on 29 September 2026: the link answers (HTTP 200)
- 29 September 2026: the link answers (HTTP 200)
1 file
- 41598_2026_48475_MOESM1_
ESM.ipynb , Jupyter, 443 lines, 1 match
supp:PMC13234283/41598_2026_48475_MOESM2_ESM.ipynb
Availability: 1 check, the latest on 29 September 2026: the link answers (HTTP 200)
- 29 September 2026: the link answers (HTTP 200)
1 file
- 41598_2026_48475_MOESM2_
ESM.ipynb , Jupyter, 2,034 lines, 2 matches
supp:PMC13234283/41598_2026_48475_MOESM3_ESM.ipynb
Availability: 1 check, the latest on 29 September 2026: the link answers (HTTP 200)
- 29 September 2026: the link answers (HTTP 200)
1 file
- 41598_2026_48475_MOESM3_
ESM.ipynb , Jupyter, 1,942 lines, 1 match
The paper's code and data availability statement is in the Data section.
Tracing map
Proposed by the machine: these links were found in the paper and verified at the source, without human review. The map will receive a Zenodo DOI once one of the paper's authors has validated it with their ORCID.
What the map holds:
- 3 repositories of the authors' code, each at its verified commit, with its license and how the link was found in the paper;
- 3 scripts, each with its path and the digest of its content;
- 4 matches between paragraphs of the paper and lines of the code (method lexical-v1);
- neither the text of the paper nor the code itself.
Its JSON (tracing-map.json) is deposited on Zenodo with its DOI once the map is validated.
Data
No dataset and no data link were found in the paper.
Code and data availability statement
The paper has a code and data availability statement. Its license (CC BY-NC-ND) does not allow reproducing it here; in short, from what the harvester recognized in it:
- it says that the data are available on request
Read it in the paper: doi.org/10.1038/s41598-026-48475-6.
Versions
The history of this record: each version stored by the harvester or made by a correction of its authors or of the maintainers of its code, and what changed in its facts. The texts of the paper (its abstract, its availability statements) are not part of it; versions that changed only those are not listed.
Version 1, 29 September 2026: the first record
Recorded: type, language, journal, volume, issue, pages, dates, 6 authors, 12 keywords, 9 MeSH terms, 10 references.
Cite
This paper
Sivaraman, J., Paramarthalingam, A., Thirunavukkarasu, A., Vasudevan, A., Hui, S. E., & Samiayya, D. (2026). Optimized U-net model for precise retinal blood vessel segmentation from colour fundus images. Scientific reports, 16(1), 17230. https://
BibTeX
@article{sivaraman2026op
author = {Sivaraman, Jegan and Paramarthalingam, Arjun and Thirunavukkarasu, Arulnancy and Vasudevan, Asokan and Hui, Soon Eu and Samiayya, Duraimurugan},
title = {{Optimized U-net model for precise retinal blood vessel segmentation from colour fundus images}},
journal = {Scientific reports},
year = {2026},
month = apr,
volume = {16},
number = {1},
pages = {17230},
publisher = {Nature Publishing Group},
issn = {2045-2322},
doi = {10.1038/
url = {https://
pmid = {41974826},
pmcid = {PMC13234283}
}
RIS
TY - JOUR
AU - Sivaraman, Jegan
AU - Paramarthalingam, Arjun
AU - Thirunavukkarasu, Arulnancy
AU - Vasudevan, Asokan
AU - Hui, Soon Eu
AU - Samiayya, Duraimurugan
TI - Optimized U-net model for precise retinal blood vessel segmentation from colour fundus images
T2 - Scientific reports
J2 - Sci Rep
PY - 2026
DA - 2026/
VL - 16
IS - 1
SP - 17230
SN - 2045-2322
PB - Nature Publishing Group
DO - 10.1038/
UR - https://
LA - en
ER -
CSL-JSON
{
"id": "10.1038/
"type": "article-journal",
"title": "Optimized U-net model for precise retinal blood vessel segmentation from colour fundus images",
"container-title": "Scientific reports",
"author": [
{
"family": "Sivaraman",
"given": "Jegan"
},
{
"family": "Paramarthalingam",
"given": "Arjun"
},
{
"family": "Thirunavukkarasu",
"given": "Arulnancy"
},
{
"family": "Vasudevan",
"given": "Asokan"
},
{
"family": "Hui",
"given": "Soon Eu"
},
{
"family": "Samiayya",
"given": "Duraimurugan"
}
],
"container-title-short":
"volume": "16",
"issue": "1",
"page": "17230",
"DOI": "10.1038/
"PMID": "41974826",
"PMCID": "PMC13234283",
"ISSN": "2045-2322",
"publisher": "Nature Publishing Group",
"URL": "https://
"language": "en",
"issued": {
"date-parts": [
[
2026,
4,
13
]
]
}
}
The tracing map gets a citation of its own once an author has validated it and it has a DOI.
Similar papers
The papers with a page that share the most with this one: the tools found in their code, their categories, datasets, cited references and authors, the rarest counting most.
- [1] doi:10.1371/journal.pone.0347867 [code]
- LiteFeatNet: A parameter-efficient and performance-centric deep learning model for multi-ocular disease identification using intermediate feature reduction from fundus images.Journal: PloS oneIn common: Keras, TensorFlow, OpenCV, 5 other tools, other, methods / tools
- [2] doi:10.1038/s41597-025-05174-7 [code]
- A large-scale MEG and EEG dataset for object recognition in naturalistic scenesJournal: n/aIn common: Keras, TensorFlow, OpenCV, 5 other tools, methods / tools
- [3] doi:10.1016/j.xcrm.2026.102766 [code]
- A longitudinal single-cell and spatial multiomic atlas of pediatric high-grade glioma.Journal: Cell reports. MedicineIn common: Keras, TensorFlow, OpenCV, 5 other tools, other condition
- [4] doi:10.1126/sciadv.aed3650 [code]
- Truthful visualizations for mass spectrometry imaging enable high-spatial-resolution interactive &
lt;i& gt;m/ z& lt;/ i& gt; mapping and exploration. Journal: Science advancesIn common: Keras, TensorFlow, OpenCV, 4 other tools, other, methods / tools - [5] doi:10.1038/s42003-026-10957-8 [code]
- Brain defence by the extracellular matrix protein Cochlin.Journal: Communications biologyIn common: Keras, TensorFlow, OpenCV, 5 other tools
- [6] doi:10.1371/journal.pcbi.1014571 [code]
- SynAPSeg: A novel dataset and image analysis framework for deep learning-based synapse detection and quantification.Journal: PLoS computational biologyIn common: Keras, TensorFlow, OpenCV, 5 other tools
- [7] doi:10.1186/s12880-026-02481-2 [code]
- Deep learning-based neuroanatomical profiling reveals population-specific brain changes in multiple sclerosis: a large-scale Middle Eastern study.Journal: BMC medical imagingIn common: Keras, TensorFlow, OpenCV, 5 other tools
- [8] doi: [code]
- Real-time closed-loop feedback system for mouse mesoscale cortical signal and movement controlJournal: eLifeIn common: Keras, TensorFlow, OpenCV, 5 other tools
- [9] doi:10.1126/sciadv.aee6952 [code]
- Wafer-scale SOT-MRAM for analog crossbar array applications.Journal: Science advancesIn common: Keras, TensorFlow, OpenCV, 5 other tools
- [10] doi:10.1364/boe.605322 [code]
- Generalized plaque digitization framework for multi-dimensional mesoscopic images.Journal: Biomedical optics expressIn common: Keras, TensorFlow, OpenCV, 5 other tools
Contribute
The authors of this paper can claim it, correct its record and validate its tracing map, and the maintainers of its code (its owner, or a public member of its organization) correct what it says of their repository; anyone signed in can ask for its removal. Every request goes to OSCR's own machine, which answers it; your account page follows them.
Sign in with ORCID to claim this paper as one of its authors, correct its record or validate its tracing map: when the paper's metadata lists your ORCID iD, you are recognized at once. Maintainers of its code: sign in with GitHub, then claim the repository on your account page.
Claim this paper
Correct its record
Say what each link of this record is, remove the ones that are not the paper's, add the ones that are missing. The correction becomes a new version of the record, in its Versions section.
Validate its tracing map
You validate the map as this page shows it: 3 repositories of the authors' code, each at its verified commit and with its license, 3 scripts, and 4 matches between paragraphs and code (see the Code and Map sections). It then receives a DOI on Zenodo, with you (your ORCID iD) and OSCR as its creators; the code itself is not deposited.
The map's fingerprint: sha256:257d987f95f35d82…
Add the badge to its README
The badge links the code to this page. Copy one of these into the README of the paper's code: only you decide where it goes, and nothing is changed for you.
Markdown
[.
Discussion, reproductions, activity
Discussion: questions and error reports about this paper and its code, from signed-in readers and its authors. It opens with sign-in.
Reproductions: reports from readers who ran the authors' code: what they reproduced, with which environment, commit and data. It opens with sign-in.
Activity: what happens around this paper: new versions of its record, its map's validation, discussions and reproductions. It opens with sign-in.
