OSCR

Optimized U-net model for precise retinal blood vessel segmentation from colour fundus images.

Code ↔ Paper

4 matches between paragraphs of the paper and lines of its authors' code, computed by the harvester (lexical-v1). Click a colored paragraph or line to see its counterpart.

The 4 matches
  1. [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. [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. [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. [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

  1. # %%
  2. # %%
  3. from google.colab import drive
  4. drive.mount('/content/drive')
  5. # %%
  6. import os
  7. train_images_path = '/content/drive/My Drive/Data/dataset/VesselNet/VesselNet/dataset/train/origin'
  8. train_mask_path = '/content/drive/My Drive/Data/dataset/VesselNet/VesselNet/dataset/train/groundtruth'
  9. test_images_path = '/content/drive/My Drive/Data/dataset/VesselNet/VesselNet/test/origin'
  10. test_mask_path = '/content/drive/My Drive/Data/dataset/VesselNet/VesselNet/test/groundtruth'
  11. train_images_files = sorted([os.path.join(train_images_path, i) for i in os.listdir(train_images_path)])
  12. train_mask_files = sorted([os.path.join(train_mask_path, i) for i in os.listdir(train_mask_path)])
  13. test_images_files = sorted([os.path.join(test_images_path, i) for i in os.listdir(test_images_path)])
  14. test_mask_files = sorted([os.path.join(test_mask_path, i) for i in os.listdir(test_mask_path)])
  15. # %%
  16. print(len(train_images_files))
  17. print(len(train_mask_files))
  18. print(len(test_images_files))
  19. print(len(test_mask_files))
  20. # %%
  21. import cv2
  22. import math
  23. import numpy as np
  24. import matplotlib.pyplot as plt
  25. import seaborn as sns
  26. sns.set()
  27. import tensorflow as tf
  28. import tensorflow.keras.backend as K
  29. from tensorflow.keras.utils import Sequence
  30. from tensorflow.keras.models import Model
  31. from tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, Conv2DTranspose, concatenate, BatchNormalization, Dropout, average
  32. from tensorflow.keras.losses import binary_crossentropy
  33. from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau
  34. # ✅ FINAL FIXED albumentations (latest compatible)
  35. from albumentations import (
  36. Compose, OneOf,
  37. CLAHE, HorizontalFlip, VerticalFlip, Rotate,
  38. RGBShift, RandomBrightnessContrast,
  39. Transpose, ShiftScaleRotate, RandomRotate90,
  40. OpticalDistortion, GridDistortion, ElasticTransform,
  41. ChannelShuffle, RandomCrop
  42. )
  43. from sklearn.metrics import classification_report
  44. from PIL import Image
  45. # %%
  46. def read_image(file_loc, dim=(256,256)):
  47. img = Image.open(file_loc)
  48. img = img.resize(dim)
  49. img = np.array(img)
  50. return img
  51. def read_mask(file_loc, dim=(256,256)):
  52. img = Image.open(file_loc)
  53. img = img.resize(dim)
  54. img = np.array(img)
  55. img = (img>0).astype(np.uint8)
  56. return img
  57. #...............................................................................................................
  58. class Train_Generator(Sequence):
  59. def __init__(self, x_set, y_set, batch_size=5, img_dim=(512,512), augmentation=False):
  60. self.x = x_set
  61. self.y = y_set
  62. self.batch_size = batch_size
  63. self.img_dim = img_dim
  64. self.augmentation = augmentation
  65. def __len__(self):
  66. return math.ceil(len(self.x) / self.batch_size)
  67. aug = Compose(
  68. [
  69. CLAHE(always_apply=True, p=1.0),
  70. OneOf([
  71. HorizontalFlip(p=0.5),
  72. VerticalFlip(p=0.5),
  73. Transpose()
  74. ], p=1.0),
  75. OneOf([
  76. ShiftScaleRotate(),
  77. RandomRotate90()
  78. ], p=0.9),
  79. OneOf([
  80. OpticalDistortion(),
  81. GridDistortion(),
  82. ElasticTransform(),
  83. ], p=0.4),
  84. OneOf([
  85. RGBShift(),
  86. RandomBrightnessContrast()
  87. ], p=0.2)
  88. ])
  89. def __getitem__(self, idx):
  90. batch_x = self.x[idx * self.batch_size:(idx + 1) * self.batch_size]
  91. batch_y = self.y[idx * self.batch_size:(idx + 1) * self.batch_size]
  92. batch_x = np.array([read_image(file_name, self.img_dim) for file_name in batch_x])
  93. batch_y = np.array([read_mask(file_name, self.img_dim) for file_name in batch_y])
  94. if self.augmentation is True:
  95. aug = [self.aug(image=i, mask=j) for i, j in zip(batch_x, batch_y)]
  96. batch_x = np.array([i['image'] for i in aug])
  97. batch_y = np.array([j['mask'] for j in aug])
  98. batch_y = np.expand_dims(batch_y, -1)
  99. #return batch_x/255.0, [batch_y, batch_y, batch_y, batch_y]
  100. return batch_x/255.0, batch_y/1.0
  101. #...............................................................................................................
  102. class Val_Generator(Sequence):
  103. def __init__(self, x_set, y_set, batch_size=5, img_dim=(512,512), augmentation=False):
  104. self.x = x_set
  105. self.y = y_set
  106. self.batch_size = batch_size
  107. self.img_dim = img_dim
  108. self.augmentation = augmentation
  109. def __len__(self):
  110. return math.ceil(len(self.x) / self.batch_size)
  111. aug = Compose(
  112. [
  113. CLAHE(always_apply=True, p=1.0)
  114. ])
  115. def __getitem__(self, idx):
  116. batch_x = self.x[idx * self.batch_size:(idx + 1) * self.batch_size]
  117. batch_y = self.y[idx * self.batch_size:(idx + 1) * self.batch_size]
  118. batch_x = np.array([read_image(file_name, self.img_dim) for file_name in batch_x])
  119. batch_y = np.array([read_mask(file_name, self.img_dim) for file_name in batch_y])
  120. if self.augmentation is True:
  121. aug = [self.aug(image=i, mask=j) for i, j in zip(batch_x, batch_y)]
  122. batch_x = np.array([i['image'] for i in aug])
  123. batch_y = np.array([j['mask'] for j in aug])
  124. batch_y = np.expand_dims(batch_y, -1)
  125. return batch_x/255.0, batch_y/1.0
  126. # return batch_x/255.0, [batch_y, batch_y, batch_y, batch_y]
  127. # %% [markdown]
  128. # Input pipeline
  129. # %%
  130. batch_img_dim = (10, 256, 256, 3)
  131. batch_msk_dim = (10, 256, 256, 1)
  132. def train_generator():
  133. 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__()
  134. def valid_generator():
  135. 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__()
  136. ds_train = tf.data.Dataset.from_generator(
  137. train_generator,
  138. output_types=(tf.float32, tf.float32),
  139. 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]])
  140. ).repeat()
  141. ds_valid = tf.data.Dataset.from_generator(
  142. valid_generator,
  143. output_types=(tf.float32, tf.float32),
  144. 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]])
  145. ).repeat()
  146. # %%
  147. for i, j in ds_train:
  148. break
  149. fig, axes = plt.subplots(1, 10, figsize=(30,5))
  150. axes = axes.flatten()
  151. for img, ax in zip(i[:10], axes[:10]):
  152. ax.imshow(img)
  153. ax.axis('off')
  154. plt.show()
  155. fig, axes = plt.subplots(1, 10, figsize=(30,5))
  156. axes = axes.flatten()
  157. for img, ax in zip(j[:10], axes[:10]):
  158. ax.imshow(np.squeeze(img, -1), cmap='gray')
  159. ax.axis('off')
  160. plt.show()
  161. # %%
  162. for i, j in ds_valid:
  163. break
  164. fig, axes = plt.subplots(1, 5, figsize=(10,3))
  165. fig.suptitle('CLAHE-d Val Images', fontsize=15)
  166. axes = axes.flatten()
  167. for img, ax in zip(i[:5], axes[:5]):
  168. ax.imshow(img)
  169. ax.axis('off')
  170. plt.tight_layout()
  171. plt.show()
  172. fig, axes = plt.subplots(1, 5, figsize=(10,3))
  173. fig.suptitle('CLAHE-d Val Masks', fontsize=15)
  174. axes = axes.flatten()
  175. for img, ax in zip(j[:5], axes[:5]):
  176. ax.imshow(np.squeeze(img, -1), cmap='gray')
  177. ax.axis('off')
  178. plt.tight_layout()
  179. plt.show()
  180. # %% [markdown]
  181. # **model**
  182. # %% [markdown]
  183. # %%
  184. from tensorflow.keras.layers import Lambda
  185. class conv_bnorm(tf.keras.layers.Layer):
  186. def __init__(self, f, **kwargs):
  187. super(conv_bnorm, self).__init__(**kwargs)
  188. self.conv_1 = Conv2D(f, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')
  189. self.norm_1 = BatchNormalization()
  190. self.conv_2 = Conv2D(f, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')
  191. self.norm_2 = BatchNormalization()
  192. def call(self, inputs):
  193. x = self.conv_1(inputs)
  194. x = self.norm_1(x)
  195. x = self.conv_2(x)
  196. x = self.norm_2(x)
  197. return x
  198. def SubpixelUpsampling(x, y):
  199. depth = tf.keras.backend.int_shape(x)[-1]
  200. def depth_to_space(x):
  201. return tf.nn.depth_to_space(x, 2)
  202. x = Conv2D(filters=depth*2, kernel_size=(1,1), strides=1, padding='same', )(x)
  203. x = Lambda(depth_to_space)(x)
  204. x = concatenate([x, y])
  205. return x
  206. inputs = Input((256,256,3), name='Input')
  207. m1c1 = conv_bnorm(32, name='M1_conv_bnorm_d1') (inputs)
  208. m1p1 = MaxPooling2D(name='M1_pool1') (m1c1)
  209. m1c2 = conv_bnorm(64, name='M1_conv_bnorm_d2') (m1p1)
  210. m1p2 = MaxPooling2D(name='M1_pool2') (m1c2)
  211. m1c3 = conv_bnorm(128, name='M1_conv_bnorm_d3') (m1p2)
  212. m1p3 = MaxPooling2D(name='M1_pool3') (m1c3)
  213. m1c4 = conv_bnorm(256, name='M1_conv_bnorm_d4') (m1p3)
  214. m1p4 = MaxPooling2D(name='M1_pool4') (m1c4)
  215. m1c5 = conv_bnorm(512, name='M1_conv_bnorm_d5') (m1p4)
  216. m1p5 = MaxPooling2D(name='M1_pool5') (m1c5)
  217. m1c6 = conv_bnorm(1024, name='M1_conv_bnorm_d6') (m1p5) # Bottleneck
  218. m1u5 = SubpixelUpsampling(m1c6, m1c5)
  219. m1u5 = conv_bnorm(512, name='M1_conv_bnorm5_u5') (m1u5)
  220. m1u4 = SubpixelUpsampling(m1u5, m1c4)
  221. m1u4 = conv_bnorm(256, name='M1_conv_bnorm_u4') (m1u4)
  222. m1u3 = SubpixelUpsampling(m1u4, m1c3)
  223. m1u3 = conv_bnorm(128, name='M1_conv_bnorm_u3') (m1u3)
  224. m1u2 = SubpixelUpsampling(m1u3, m1c2)
  225. m1u2 = conv_bnorm(64, name='M1_conv_bnorm_u2') (m1u2)
  226. m1u1 = SubpixelUpsampling(m1u2, m1c1)
  227. m1u1 = conv_bnorm(32, name='M1_conv_bnorm_u1') (m1u1)
  228. m1out = Conv2D(1, (1, 1), name='M1_output', activation='sigmoid') (m1u1) # Output
  229. #-----------------------------------------------------------------------------
  230. m2inp = concatenate([m1u1, inputs])
  231. m2c1 = conv_bnorm(32, name='M2_conv_bnorm_d1') (m2inp)
  232. m2p1 = MaxPooling2D(name='M2_pool1') (m2c1)
  233. m2c2 = conv_bnorm(64, name='M2_conv_bnorm_d2') (m2p1)
  234. m2p2 = MaxPooling2D(name='M2_pool2') (m2c2)
  235. m2c3 = conv_bnorm(128, name='M2_conv_bnorm_d3') (m2p2)
  236. m2p3 = MaxPooling2D(name='M2_pool3') (m2c3)
  237. m2c4 = conv_bnorm(256, name='M2_conv_bnorm_d4') (m2p3)
  238. m2p4 = MaxPooling2D(name='M2_pool4') (m2c4)
  239. m2c5 = conv_bnorm(512, name='M2_conv_bnorm_d5') (m2p4)
  240. m2p5 = MaxPooling2D(name='M2_pool5') (m2c5)
  241. m2c6 = conv_bnorm(1024, name='M2_conv_bnorm_d6') (m2p5)
  242. m2u5 = SubpixelUpsampling(m2c6, m2c5)
  243. m2u5 = concatenate([m2u5, m1u5])
  244. m2u5 = conv_bnorm(512, name='M2_conv_bnorm_u5') (m2u5)
  245. m2u4 = SubpixelUpsampling(m2c5, m2c4)
  246. m2u4 = concatenate([m2u4, m1u4])
  247. m2u4 = conv_bnorm(256, name='M2_conv_bnorm_u4') (m2u4)
  248. m2u3 = SubpixelUpsampling(m2u4, m2c3)
  249. m2u3 = concatenate([m2u3, m1u3])
  250. m2u3 = conv_bnorm(128, name='M2_conv_bnorm_u3') (m2u3)
  251. m2u2 = SubpixelUpsampling(m2u3, m2c2)
  252. m2u2 = concatenate([m2u2, m1u2])
  253. m2u2 = conv_bnorm(64, name='M2_conv_bnorm_u2') (m2u2)
  254. m2u1 = SubpixelUpsampling(m2u2, m2c1)
  255. m2u1 = concatenate([m2u1, m1u1])
  256. m2u1 = conv_bnorm(32, name='M2_conv_bnorm_u1') (m2u1)
  257. m2out = Conv2D(1, (1, 1), name='M2_output', activation='sigmoid') (m2u1)
  258. #-----------------------------------------------------------------------------
  259. m3inp = concatenate([m2u1, inputs])
  260. m3c1 = conv_bnorm(32, name='M3_conv_bnorm_d1') (m3inp)
  261. m3p1 = MaxPooling2D(name='M3_pool1') (m3c1)
  262. m3c2 = conv_bnorm(64, name='M3_conv_bnorm_d2') (m3p1)
  263. m3p2 = MaxPooling2D(name='M3_pool2') (m3c2)
  264. m3c3 = conv_bnorm(128, name='M3_conv_bnorm_d3') (m3p2)
  265. m3p3 = MaxPooling2D(name='M3_pool3') (m3c3)
  266. m3c4 = conv_bnorm(256, name='M3_conv_bnorm_d4') (m3p3)
  267. m3p4 = MaxPooling2D(name='M3_pool4') (m3c4)
  268. m3c5 = conv_bnorm(512, name='M3_conv_bnorm_d5') (m3p4)
  269. m3p5 = MaxPooling2D(name='M3_pool5') (m3c5)
  270. m3c6 = conv_bnorm(1024, name='M3_conv_bnorm_d6') (m3p5)
  271. m3u5 = SubpixelUpsampling(m3c6, m3c5)
  272. m3u5 = concatenate([m3u5, m1u5])
  273. m3u5 = concatenate([m3u5, m2u5])
  274. m3u5 = conv_bnorm(512, name='M3_conv_bnorm_u5') (m3u5)
  275. m3u4 = SubpixelUpsampling(m3c5, m3c4)
  276. m3u4 = concatenate([m3u4, m1u4])
  277. m3u4 = concatenate([m3u4, m2u4])
  278. m3u4 = conv_bnorm(256, name='M3_conv_bnorm_u4') (m3u4)
  279. m3u3 = SubpixelUpsampling(m3u4, m3c3)
  280. m3u3 = concatenate([m3u3, m1u3])
  281. m3u3 = concatenate([m3u3, m2u3])
  282. m3u3 = conv_bnorm(128, name='M3_conv_bnorm_u3') (m3u3)
  283. m3u2 = SubpixelUpsampling(m3u3, m3c2)
  284. m3u2 = concatenate([m3u2, m1u2])
  285. m3u2 = concatenate([m3u2, m2u2])
  286. m3u2 = conv_bnorm(64, name='M3_conv_bnorm_u2') (m3u2)
  287. m3u1 = SubpixelUpsampling(m3u2, m3c1)
  288. m3u1 = concatenate([m3u1, m1u1])
  289. m3u1 = concatenate([m3u1, m2u1])
  290. m3u1 = conv_bnorm(32, name='M3_conv_bnorm_u1') (m3u1)
  291. m3out = Conv2D(1, (1, 1), name='M3_output', activation='sigmoid') (m3u1)
  292. #-----------------------------------------------------------------------------
  293. m4inp = concatenate([m3u1, inputs])
  294. m4c1 = conv_bnorm(32, name='M4_conv_bnorm_d1') (m4inp)
  295. m4p1 = MaxPooling2D(name='M4_pool1') (m4c1)
  296. m4c2 = conv_bnorm(64, name='M4_conv_bnorm_d2') (m4p1)
  297. m4p2 = MaxPooling2D(name='M4_pool2') (m4c2)
  298. m4c3 = conv_bnorm(128, name='M4_conv_bnorm_d3') (m4p2)
  299. m4p3 = MaxPooling2D(name='M4_pool3') (m4c3)
  300. m4c4 = conv_bnorm(256, name='M4_conv_bnorm_d4') (m4p3)
  301. m4p4 = MaxPooling2D(name='M4_pool4') (m4c4)
  302. m4c5 = conv_bnorm(512, name='M4_conv_bnorm_d5') (m4p4)
  303. m4p5 = MaxPooling2D(name='M4_pool5') (m4c5)
  304. m4c6 = conv_bnorm(1024, name='M4_conv_bnorm_d6') (m4p5)
  305. m4u5 = SubpixelUpsampling(m4c6, m4c5)
  306. m4u5 = concatenate([m4u5, m1u5])
  307. m4u5 = concatenate([m4u5, m2u5])
  308. m4u5 = concatenate([m4u5, m3u5])
  309. m4u5 = conv_bnorm(512, name='M4_conv_bnorm_u5') (m4u5)
  310. m4u4 = SubpixelUpsampling(m4c5, m4c4)
  311. m4u4 = concatenate([m4u4, m1u4])
  312. m4u4 = concatenate([m4u4, m2u4])
  313. m4u4 = concatenate([m4u4, m3u4])
  314. m4u4 = conv_bnorm(256, name='M4_conv_bnorm_u4') (m4u4)
  315. m4u3 = SubpixelUpsampling(m4u4, m4c3)
  316. m4u3 = concatenate([m4u3, m1u3])
  317. m4u3 = concatenate([m4u3, m2u3])
  318. m4u3 = concatenate([m4u3, m3u3])
  319. m4u3 = conv_bnorm(128, name='M4_conv_bnorm_u3') (m4u3)
  320. m4u2 = SubpixelUpsampling(m4u3, m4c2)
  321. m4u2 = concatenate([m4u2, m1u2])
  322. m4u2 = concatenate([m4u2, m2u2])
  323. m4u2 = concatenate([m4u2, m3u2])
  324. m4u2 = conv_bnorm(64, name='M4_conv_bnorm_u2') (m4u2)
  325. m4u1 = SubpixelUpsampling(m4u2, m4c1)
  326. m4u1 = concatenate([m4u1, m1u1])
  327. m4u1 = concatenate([m4u1, m2u1])
  328. m4u1 = concatenate([m4u1, m3u1])
  329. m4u1 = conv_bnorm(32, name='M4_conv_bnorm_u1') (m4u1)
  330. m4out = Conv2D(1, (1, 1), name='M4_output', activation='sigmoid') (m4u1)
  331. #K.clear_session()
  332. #model = Model(inputs=[inputs], outputs=[m1out, m2out, m3out, m4out])
  333. K.clear_session()
  334. model = Model(inputs=[inputs], outputs=m4out)
  335. # %%
  336. from tensorflow.keras.layers import Lambda
  337. class conv_bnorm(tf.keras.layers.Layer):
  338. def __init__(self, f, **kwargs):
  339. super(conv_bnorm, self).__init__(**kwargs)
  340. self.conv_1 = Conv2D(f, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')
  341. self.norm_1 = BatchNormalization()
  342. self.conv_2 = Conv2D(f, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')
  343. self.norm_2 = BatchNormalization()
  344. def call(self, inputs):
  345. x = self.conv_1(inputs)
  346. x = self.norm_1(x)
  347. x = self.conv_2(x)
  348. x = self.norm_2(x)
  349. return x
  350. def SubpixelUpsampling(x, y):
  351. depth = tf.keras.backend.int_shape(x)[-1]
  352. def depth_to_space(x):
  353. return tf.nn.depth_to_space(x, 2)
  354. x = Conv2D(filters=depth*2, kernel_size=(1,1), strides=1, padding='same', )(x)
  355. x = Lambda(depth_to_space)(x)
  356. x = concatenate([x, y])
  357. return x
  358. inputs = Input((256,256,3), name='Input')
  359. m1c1 = conv_bnorm(32, name='M1_conv_bnorm_d1') (inputs)
  360. m1p1 = MaxPooling2D(name='M1_pool1') (m1c1)
  361. m1c2 = conv_bnorm(64, name='M1_conv_bnorm_d2') (m1p1)
  362. m1p2 = MaxPooling2D(name='M1_pool2') (m1c2)
  363. m1c3 = conv_bnorm(128, name='M1_conv_bnorm_d3') (m1p2)
  364. m1p3 = MaxPooling2D(name='M1_pool3') (m1c3)
  365. m1c4 = conv_bnorm(256, name='M1_conv_bnorm_d4') (m1p3)
  366. m1p4 = MaxPooling2D(name='M1_pool4') (m1c4)
  367. m1c5 = conv_bnorm(512, name='M1_conv_bnorm_d5') (m1p4)
  368. m1p5 = MaxPooling2D(name='M1_pool5') (m1c5)
  369. m1c6 = conv_bnorm(1024, name='M1_conv_bnorm_d6') (m1p5) # Bottleneck
  370. m1u5 = SubpixelUpsampling(m1c6, m1c5)
  371. m1u5 = conv_bnorm(512, name='M1_conv_bnorm5_u5') (m1u5)
  372. m1u4 = SubpixelUpsampling(m1u5, m1c4)
  373. m1u4 = conv_bnorm(256, name='M1_conv_bnorm_u4') (m1u4)
  374. m1u3 = SubpixelUpsampling(m1u4, m1c3)
  375. m1u3 = conv_bnorm(128, name='M1_conv_bnorm_u3') (m1u3)
  376. m1u2 = SubpixelUpsampling(m1u3, m1c2)
  377. m1u2 = conv_bnorm(64, name='M1_conv_bnorm_u2') (m1u2)
  378. m1u1 = SubpixelUpsampling(m1u2, m1c1)
  379. m1u1 = conv_bnorm(32, name='M1_conv_bnorm_u1') (m1u1)
  380. m1out = Conv2D(1, (1, 1), name='M1_output', activation='sigmoid') (m1u1) # Output
  381. #-----------------------------------------------------------------------------
  382. m2inp = concatenate([m1u1, inputs])
  383. m2c1 = conv_bnorm(32, name='M2_conv_bnorm_d1') (m2inp)
  384. m2p1 = MaxPooling2D(name='M2_pool1') (m2c1)
  385. m2c2 = conv_bnorm(64, name='M2_conv_bnorm_d2') (m2p1)
  386. m2p2 = MaxPooling2D(name='M2_pool2') (m2c2)
  387. m2c3 = conv_bnorm(128, name='M2_conv_bnorm_d3') (m2p2)
  388. m2p3 = MaxPooling2D(name='M2_pool3') (m2c3)
  389. m2c4 = conv_bnorm(256, name='M2_conv_bnorm_d4') (m2p3)
  390. m2p4 = MaxPooling2D(name='M2_pool4') (m2c4)
  391. m2c5 = conv_bnorm(512, name='M2_conv_bnorm_d5') (m2p4)
  392. m2p5 = MaxPooling2D(name='M2_pool5') (m2c5)
  393. m2c6 = conv_bnorm(1024, name='M2_conv_bnorm_d6') (m2p5)
  394. m2u5 = SubpixelUpsampling(m2c6, m2c5)
  395. m2u5 = concatenate([m2u5, m1u5])
  396. m2u5 = conv_bnorm(512, name='M2_conv_bnorm_u5') (m2u5)
  397. m2u4 = SubpixelUpsampling(m2c5, m2c4)
  398. m2u4 = concatenate([m2u4, m1u4])
  399. m2u4 = conv_bnorm(256, name='M2_conv_bnorm_u4') (m2u4)
  400. m2u3 = SubpixelUpsampling(m2u4, m2c3)
  401. m2u3 = concatenate([m2u3, m1u3])
  402. m2u3 = conv_bnorm(128, name='M2_conv_bnorm_u3') (m2u3)
  403. m2u2 = SubpixelUpsampling(m2u3, m2c2)
  404. m2u2 = concatenate([m2u2, m1u2])
  405. m2u2 = conv_bnorm(64, name='M2_conv_bnorm_u2') (m2u2)
  406. m2u1 = SubpixelUpsampling(m2u2, m2c1)
  407. m2u1 = concatenate([m2u1, m1u1])
  408. m2u1 = conv_bnorm(32, name='M2_conv_bnorm_u1') (m2u1)
  409. m2out = Conv2D(1, (1, 1), name='M2_output', activation='sigmoid') (m2u1)
  410. #-----------------------------------------------------------------------------
  411. m3inp = concatenate([m2u1, inputs])
  412. m3c1 = conv_bnorm(32, name='M3_conv_bnorm_d1') (m3inp)
  413. m3p1 = MaxPooling2D(name='M3_pool1') (m3c1)
  414. m3c2 = conv_bnorm(64, name='M3_conv_bnorm_d2') (m3p1)
  415. m3p2 = MaxPooling2D(name='M3_pool2') (m3c2)
  416. m3c3 = conv_bnorm(128, name='M3_conv_bnorm_d3') (m3p2)
  417. m3p3 = MaxPooling2D(name='M3_pool3') (m3c3)
  418. m3c4 = conv_bnorm(256, name='M3_conv_bnorm_d4') (m3p3)
  419. m3p4 = MaxPooling2D(name='M3_pool4') (m3c4)
  420. m3c5 = conv_bnorm(512, name='M3_conv_bnorm_d5') (m3p4)
  421. m3p5 = MaxPooling2D(name='M3_pool5') (m3c5)
  422. m3c6 = conv_bnorm(1024, name='M3_conv_bnorm_d6') (m3p5)
  423. m3u5 = SubpixelUpsampling(m3c6, m3c5)
  424. m3u5 = concatenate([m3u5, m1u5])
  425. m3u5 = concatenate([m3u5, m2u5])
  426. m3u5 = conv_bnorm(512, name='M3_conv_bnorm_u5') (m3u5)
  427. m3u4 = SubpixelUpsampling(m3c5, m3c4)
  428. m3u4 = concatenate([m3u4, m1u4])
  429. m3u4 = concatenate([m3u4, m2u4])
  430. m3u4 = conv_bnorm(256, name='M3_conv_bnorm_u4') (m3u4)
  431. m3u3 = SubpixelUpsampling(m3u4, m3c3)
  432. m3u3 = concatenate([m3u3, m1u3])
  433. m3u3 = concatenate([m3u3, m2u3])
  434. m3u3 = conv_bnorm(128, name='M3_conv_bnorm_u3') (m3u3)
  435. m3u2 = SubpixelUpsampling(m3u3, m3c2)
  436. m3u2 = concatenate([m3u2, m1u2])
  437. m3u2 = concatenate([m3u2, m2u2])
  438. m3u2 = conv_bnorm(64, name='M3_conv_bnorm_u2') (m3u2)
  439. m3u1 = SubpixelUpsampling(m3u2, m3c1)
  440. m3u1 = concatenate([m3u1, m1u1])
  441. m3u1 = concatenate([m3u1, m2u1])
  442. m3u1 = conv_bnorm(32, name='M3_conv_bnorm_u1') (m3u1)
  443. m3out = Conv2D(1, (1, 1), name='M3_output', activation='sigmoid') (m3u1)
  444. #-----------------------------------------------------------------------------
  445. m4inp = concatenate([m3u1, inputs])
  446. m4c1 = conv_bnorm(32, name='M4_conv_bnorm_d1') (m4inp)
  447. m4p1 = MaxPooling2D(name='M4_pool1') (m4c1)
  448. m4c2 = conv_bnorm(64, name='M4_conv_bnorm_d2') (m4p1)
  449. m4p2 = MaxPooling2D(name='M4_pool2') (m4c2)
  450. m4c3 = conv_bnorm(128, name='M4_conv_bnorm_d3') (m4p2)
  451. m4p3 = MaxPooling2D(name='M4_pool3') (m4c3)
  452. m4c4 = conv_bnorm(256, name='M4_conv_bnorm_d4') (m4p3)
  453. m4p4 = MaxPooling2D(name='M4_pool4') (m4c4)
  454. m4c5 = conv_bnorm(512, name='M4_conv_bnorm_d5') (m4p4)
  455. m4p5 = MaxPooling2D(name='M4_pool5') (m4c5)
  456. m4c6 = conv_bnorm(1024, name='M4_conv_bnorm_d6') (m4p5)
  457. m4u5 = SubpixelUpsampling(m4c6, m4c5)
  458. m4u5 = concatenate([m4u5, m1u5])
  459. m4u5 = concatenate([m4u5, m2u5])
  460. m4u5 = concatenate([m4u5, m3u5])
  461. m4u5 = conv_bnorm(512, name='M4_conv_bnorm_u5') (m4u5)
  462. m4u4 = SubpixelUpsampling(m4c5, m4c4)
  463. m4u4 = concatenate([m4u4, m1u4])
  464. m4u4 = concatenate([m4u4, m2u4])
  465. m4u4 = concatenate([m4u4, m3u4])
  466. m4u4 = conv_bnorm(256, name='M4_conv_bnorm_u4') (m4u4)
  467. m4u3 = SubpixelUpsampling(m4u4, m4c3)
  468. m4u3 = concatenate([m4u3, m1u3])
  469. m4u3 = concatenate([m4u3, m2u3])
  470. m4u3 = concatenate([m4u3, m3u3])
  471. m4u3 = conv_bnorm(128, name='M4_conv_bnorm_u3') (m4u3)
  472. m4u2 = SubpixelUpsampling(m4u3, m4c2)
  473. m4u2 = concatenate([m4u2, m1u2])
  474. m4u2 = concatenate([m4u2, m2u2])
  475. m4u2 = concatenate([m4u2, m3u2])
  476. m4u2 = conv_bnorm(64, name='M4_conv_bnorm_u2') (m4u2)
  477. m4u1 = SubpixelUpsampling(m4u2, m4c1)
  478. m4u1 = concatenate([m4u1, m1u1])
  479. m4u1 = concatenate([m4u1, m2u1])
  480. m4u1 = concatenate([m4u1, m3u1])
  481. m4u1 = conv_bnorm(32, name='M4_conv_bnorm_u1') (m4u1)
  482. m4out = Conv2D(1, (1, 1), name='M4_output', activation='sigmoid') (m4u1)
  483. K.clear_session()
  484. model = Model(inputs=[inputs], outputs=m4out)
  485. #K.clear_session()
  486. #model = Model(inputs=[inputs], outputs=[m1out, m2out, m3out, m4out])
  487. # %%
  488. from tensorflow.keras.layers import Lambda
  489. class conv_bnorm(tf.keras.layers.Layer):
  490. def __init__(self, f, **kwargs):
  491. super(conv_bnorm, self).__init__(**kwargs)
  492. self.conv_1 = Conv2D(f, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')
  493. self.norm_1 = BatchNormalization()
  494. self.conv_2 = Conv2D(f, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')
  495. self.norm_2 = BatchNormalization()
  496. def call(self, inputs):
  497. x = self.conv_1(inputs)
  498. x = self.norm_1(x)
  499. x = self.conv_2(x)
  500. x = self.norm_2(x)
  501. return x
  502. def SubpixelUpsampling(x, y):
  503. depth = tf.keras.backend.int_shape(x)[-1]
  504. def depth_to_space(x):
  505. return tf.nn.depth_to_space(x, 2)
  506. x = Conv2D(filters=depth*2, kernel_size=(1,1), strides=1, padding='same', )(x)
  507. x = Lambda(depth_to_space)(x)
  508. x = concatenate([x, y])
  509. return x
  510. inputs = Input((256,256,3), name='Input')
  511. m1c1 = conv_bnorm(32, name='M1_conv_bnorm_d1') (inputs)
  512. m1p1 = MaxPooling2D(name='M1_pool1') (m1c1)
  513. m1c2 = conv_bnorm(64, name='M1_conv_bnorm_d2') (m1p1)
  514. m1p2 = MaxPooling2D(name='M1_pool2') (m1c2)
  515. m1c3 = conv_bnorm(128, name='M1_conv_bnorm_d3') (m1p2)
  516. m1p3 = MaxPooling2D(name='M1_pool3') (m1c3)
  517. m1c4 = conv_bnorm(256, name='M1_conv_bnorm_d4') (m1p3)
  518. m1p4 = MaxPooling2D(name='M1_pool4') (m1c4)
  519. m1c5 = conv_bnorm(512, name='M1_conv_bnorm_d5') (m1p4)
  520. m1p5 = MaxPooling2D(name='M1_pool5') (m1c5)
  521. m1c6 = conv_bnorm(1024, name='M1_conv_bnorm_d6') (m1p5) # Bottleneck
  522. m1u5 = SubpixelUpsampling(m1c6, m1c5)
  523. m1u5 = conv_bnorm(512, name='M1_conv_bnorm5_u5') (m1u5)
  524. m1u4 = SubpixelUpsampling(m1u5, m1c4)
  525. m1u4 = conv_bnorm(256, name='M1_conv_bnorm_u4') (m1u4)
  526. m1u3 = SubpixelUpsampling(m1u4, m1c3)
  527. m1u3 = conv_bnorm(128, name='M1_conv_bnorm_u3') (m1u3)
  528. m1u2 = SubpixelUpsampling(m1u3, m1c2)
  529. m1u2 = conv_bnorm(64, name='M1_conv_bnorm_u2') (m1u2)
  530. m1u1 = SubpixelUpsampling(m1u2, m1c1)
  531. m1u1 = conv_bnorm(32, name='M1_conv_bnorm_u1') (m1u1)
  532. m1out = Conv2D(1, (1, 1), name='M1_output', activation='sigmoid') (m1u1) # Output
  533. #-----------------------------------------------------------------------------
  534. m2inp = concatenate([m1u1, inputs])
  535. m2c1 = conv_bnorm(32, name='M2_conv_bnorm_d1') (m2inp)
  536. m2p1 = MaxPooling2D(name='M2_pool1') (m2c1)
  537. m2c2 = conv_bnorm(64, name='M2_conv_bnorm_d2') (m2p1)
  538. m2p2 = MaxPooling2D(name='M2_pool2') (m2c2)
  539. m2c3 = conv_bnorm(128, name='M2_conv_bnorm_d3') (m2p2)
  540. m2p3 = MaxPooling2D(name='M2_pool3') (m2c3)
  541. m2c4 = conv_bnorm(256, name='M2_conv_bnorm_d4') (m2p3)
  542. m2p4 = MaxPooling2D(name='M2_pool4') (m2c4)
  543. m2c5 = conv_bnorm(512, name='M2_conv_bnorm_d5') (m2p4)
  544. m2p5 = MaxPooling2D(name='M2_pool5') (m2c5)
  545. m2c6 = conv_bnorm(1024, name='M2_conv_bnorm_d6') (m2p5)
  546. m2u5 = SubpixelUpsampling(m2c6, m2c5)
  547. m2u5 = concatenate([m2u5, m1u5])
  548. m2u5 = conv_bnorm(512, name='M2_conv_bnorm_u5') (m2u5)
  549. m2u4 = SubpixelUpsampling(m2c5, m2c4)
  550. m2u4 = concatenate([m2u4, m1u4])
  551. m2u4 = conv_bnorm(256, name='M2_conv_bnorm_u4') (m2u4)
  552. m2u3 = SubpixelUpsampling(m2u4, m2c3)
  553. m2u3 = concatenate([m2u3, m1u3])
  554. m2u3 = conv_bnorm(128, name='M2_conv_bnorm_u3') (m2u3)
  555. m2u2 = SubpixelUpsampling(m2u3, m2c2)
  556. m2u2 = concatenate([m2u2, m1u2])
  557. m2u2 = conv_bnorm(64, name='M2_conv_bnorm_u2') (m2u2)
  558. m2u1 = SubpixelUpsampling(m2u2, m2c1)
  559. m2u1 = concatenate([m2u1, m1u1])
  560. m2u1 = conv_bnorm(32, name='M2_conv_bnorm_u1') (m2u1)
  561. m2out = Conv2D(1, (1, 1), name='M2_output', activation='sigmoid') (m2u1)
  562. #-----------------------------------------------------------------------------
  563. m3inp = concatenate([m2u1, inputs])
  564. m3c1 = conv_bnorm(32, name='M3_conv_bnorm_d1') (m3inp)
  565. m3p1 = MaxPooling2D(name='M3_pool1') (m3c1)
  566. m3c2 = conv_bnorm(64, name='M3_conv_bnorm_d2') (m3p1)
  567. m3p2 = MaxPooling2D(name='M3_pool2') (m3c2)
  568. m3c3 = conv_bnorm(128, name='M3_conv_bnorm_d3') (m3p2)
  569. m3p3 = MaxPooling2D(name='M3_pool3') (m3c3)
  570. m3c4 = conv_bnorm(256, name='M3_conv_bnorm_d4') (m3p3)
  571. m3p4 = MaxPooling2D(name='M3_pool4') (m3c4)
  572. m3c5 = conv_bnorm(512, name='M3_conv_bnorm_d5') (m3p4)
  573. m3p5 = MaxPooling2D(name='M3_pool5') (m3c5)
  574. m3c6 = conv_bnorm(1024, name='M3_conv_bnorm_d6') (m3p5)
  575. m3u5 = SubpixelUpsampling(m3c6, m3c5)
  576. m3u5 = concatenate([m3u5, m1u5])
  577. m3u5 = concatenate([m3u5, m2u5])
  578. m3u5 = conv_bnorm(512, name='M3_conv_bnorm_u5') (m3u5)
  579. m3u4 = SubpixelUpsampling(m3c5, m3c4)
  580. m3u4 = concatenate([m3u4, m1u4])
  581. m3u4 = concatenate([m3u4, m2u4])
  582. m3u4 = conv_bnorm(256, name='M3_conv_bnorm_u4') (m3u4)
  583. m3u3 = SubpixelUpsampling(m3u4, m3c3)
  584. m3u3 = concatenate([m3u3, m1u3])
  585. m3u3 = concatenate([m3u3, m2u3])
  586. m3u3 = conv_bnorm(128, name='M3_conv_bnorm_u3') (m3u3)
  587. m3u2 = SubpixelUpsampling(m3u3, m3c2)
  588. m3u2 = concatenate([m3u2, m1u2])
  589. m3u2 = concatenate([m3u2, m2u2])
  590. m3u2 = conv_bnorm(64, name='M3_conv_bnorm_u2') (m3u2)
  591. m3u1 = SubpixelUpsampling(m3u2, m3c1)
  592. m3u1 = concatenate([m3u1, m1u1])
  593. m3u1 = concatenate([m3u1, m2u1])
  594. m3u1 = conv_bnorm(32, name='M3_conv_bnorm_u1') (m3u1)
  595. m3out = Conv2D(1, (1, 1), name='M3_output', activation='sigmoid') (m3u1)
  596. #-----------------------------------------------------------------------------
  597. m4inp = concatenate([m3u1, inputs])
  598. m4c1 = conv_bnorm(32, name='M4_conv_bnorm_d1') (m4inp)
  599. m4p1 = MaxPooling2D(name='M4_pool1') (m4c1)
  600. m4c2 = conv_bnorm(64, name='M4_conv_bnorm_d2') (m4p1)
  601. m4p2 = MaxPooling2D(name='M4_pool2') (m4c2)
  602. m4c3 = conv_bnorm(128, name='M4_conv_bnorm_d3') (m4p2)
  603. m4p3 = MaxPooling2D(name='M4_pool3') (m4c3)
  604. m4c4 = conv_bnorm(256, name='M4_conv_bnorm_d4') (m4p3)
  605. m4p4 = MaxPooling2D(name='M4_pool4') (m4c4)
  606. m4c5 = conv_bnorm(512, name='M4_conv_bnorm_d5') (m4p4)
  607. m4p5 = MaxPooling2D(name='M4_pool5') (m4c5)
  608. m4c6 = conv_bnorm(1024, name='M4_conv_bnorm_d6') (m4p5)
  609. m4u5 = SubpixelUpsampling(m4c6, m4c5)
  610. m4u5 = concatenate([m4u5, m1u5])
  611. m4u5 = concatenate([m4u5, m2u5])
  612. m4u5 = concatenate([m4u5, m3u5])
  613. m4u5 = conv_bnorm(512, name='M4_conv_bnorm_u5') (m4u5)
  614. m4u4 = SubpixelUpsampling(m4c5, m4c4)
  615. m4u4 = concatenate([m4u4, m1u4])
  616. m4u4 = concatenate([m4u4, m2u4])
  617. m4u4 = concatenate([m4u4, m3u4])
  618. m4u4 = conv_bnorm(256, name='M4_conv_bnorm_u4') (m4u4)
  619. m4u3 = SubpixelUpsampling(m4u4, m4c3)
  620. m4u3 = concatenate([m4u3, m1u3])
  621. m4u3 = concatenate([m4u3, m2u3])
  622. m4u3 = concatenate([m4u3, m3u3])
  623. m4u3 = conv_bnorm(128, name='M4_conv_bnorm_u3') (m4u3)
  624. m4u2 = SubpixelUpsampling(m4u3, m4c2)
  625. m4u2 = concatenate([m4u2, m1u2])
  626. m4u2 = concatenate([m4u2, m2u2])
  627. m4u2 = concatenate([m4u2, m3u2])
  628. m4u2 = conv_bnorm(64, name='M4_conv_bnorm_u2') (m4u2)
  629. m4u1 = SubpixelUpsampling(m4u2, m4c1)
  630. m4u1 = concatenate([m4u1, m1u1])
  631. m4u1 = concatenate([m4u1, m2u1])
  632. m4u1 = concatenate([m4u1, m3u1])
  633. m4u1 = conv_bnorm(32, name='M4_conv_bnorm_u1') (m4u1)
  634. m4out = Conv2D(1, (1, 1), name='M4_output', activation='sigmoid') (m4u1)
  635. K.clear_session()
  636. model = Model(inputs=[inputs], outputs=m4out)
  637. #K.clear_session()
  638. #model = Model(inputs=[inputs], outputs=[m1out, m2out, m3out, m4out])
  639. # %% [markdown]
  640. # loss, matric &compile
  641. # %%
  642. def dice_loss(y_true, y_pred):
  643. intersection = tf.reduce_sum(y_true * y_pred) + 1.0
  644. dice_score = (2. * intersection + 1.0) / (tf.reduce_sum(y_true) + tf.reduce_sum(y_pred) + 1.0)
  645. dice_loss = 1. - dice_score
  646. return dice_loss
  647. def dice(y_true, y_pred):
  648. intersection = tf.reduce_sum(y_true * y_pred) + 1.0
  649. dice_score = (2. * intersection + 1.0) / (tf.reduce_sum(y_true) + tf.reduce_sum(y_pred) + 1.0)
  650. return dice_score
  651. def bce_dice_loss(y_true, y_pred):
  652. return binary_crossentropy(y_true, y_pred) + dice_loss(y_true, y_pred)
  653. def iou(y_true, y_pred):
  654. y_true = tf.cast(y_true>0.5, tf.float32)
  655. y_pred = tf.cast(y_pred>0.5, tf.float32)
  656. intersection = tf.reduce_sum(y_true * y_pred) + 1.0
  657. union = tf.reduce_sum(y_true) + tf.reduce_sum(y_pred) - intersection + 1.0
  658. iou = intersection/union
  659. return iou
  660. # %%
  661. import numpy as np
  662. from sklearn.metrics import roc_auc_score
  663. import time
  664. auc_scores = []
  665. start = time.time()
  666. for i in range(5):
  667. print(f"\n🔥 Run {i+1}")
  668. # 🔥 CLEAR OLD MODEL
  669. import tensorflow as tf
  670. tf.keras.backend.clear_session()
  671. # 🔥 RE-RUN MODEL CELLS MANUALLY (IMPORTANT)
  672. # 👉 இங்க code இல்ல — மேல உள்ள model cells run ஆகணும்
  673. # 👉 இப்ப model already memoryல இருக்கும்
  674. model.compile(
  675. optimizer='adam',
  676. loss='binary_crossentropy',
  677. metrics=[iou, dice]
  678. )
  679. model.fit(
  680. ds_train,
  681. steps_per_epoch=20,
  682. epochs=40,
  683. validation_data=ds_valid,
  684. validation_steps=4,
  685. verbose=1
  686. )
  687. y_true = []
  688. y_pred = []
  689. for x, y in ds_valid:
  690. preds = model.predict(x)
  691. y_true.extend(y.numpy().flatten())
  692. y_pred.extend(preds.flatten())
  693. if len(y_true) > 1000:
  694. break
  695. auc = roc_auc_score(y_true, y_pred)
  696. print("AUC:", auc)
  697. auc_scores.append(auc)
  698. end = time.time()
  699. print("\n📊 AUC Scores:", auc_scores)
  700. print("⏱️ Training Time:", end - start)
  701. # %%
  702. import matplotlib.pyplot as plt
  703. import numpy as np
  704. auc_scores = [0.9629, 0.9581, 0.9499, 0.9563, 0.9524]
  705. runs = np.arange(1, len(auc_scores)+1)
  706. plt.figure()
  707. plt.bar(runs, auc_scores)
  708. plt.xlabel("Run Number")
  709. plt.ylabel("AUC Score")
  710. plt.title("AUC Across Multiple Runs")
  711. plt.xticks(runs)
  712. plt.ylim(0.94, 0.97)
  713. plt.show()
  714. # %%
  715. import matplotlib.pyplot as plt
  716. import numpy as np
  717. auc_scores = np.array([0.9629, 0.9581, 0.9499, 0.9563, 0.9524])
  718. mean_auc = np.mean(auc_scores)
  719. std_auc = np.std(auc_scores)
  720. ci = 1.96 * (std_auc / np.sqrt(len(auc_scores)))
  721. plt.figure()
  722. plt.errorbar(1, mean_auc, yerr=ci, fmt='o', capsize=5)
  723. plt.xlim(0, 2)
  724. plt.xticks([1], ["Model"])
  725. plt.ylabel("AUC Score")
  726. plt.title("Mean AUC with 95% Confidence Interval")
  727. plt.ylim(0.94, 0.97)
  728. plt.show()
  729. # %%
  730. plt.figure()
  731. plt.plot(runs, auc_scores, marker='o')
  732. plt.xlabel("Run Number")
  733. plt.ylabel("AUC Score")
  734. plt.title("AUC Stability Across Runs")
  735. plt.grid()
  736. plt.show()
  737. # %%
  738. from tensorflow.keras.optimizers import Nadam
  739. from tensorflow.keras.optimizers import Adam
  740. model.compile(
  741. optimizer='adam',
  742. loss='binary_crossentropy',
  743. metrics=[iou, dice]
  744. )
  745. # %%
  746. from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau
  747. earlystopping = EarlyStopping(
  748. monitor='val_loss',
  749. min_delta=0,
  750. patience=10,
  751. verbose=1,
  752. restore_best_weights=True)
  753. reducelr = ReduceLROnPlateau(
  754. monitor='val_loss',
  755. factor=0.1,
  756. patience=3,
  757. verbose=1,
  758. min_delta=0.0001 )
  759. callbacks = [earlystopping, reducelr]
  760. # %%
  761. tf.keras.utils.plot_model(
  762. model, to_file='model_UNET++.png', show_shapes=False, show_layer_names=True,
  763. rankdir='TB', expand_nested=False, dpi=50
  764. )
  765. # %%
  766. model.summary()
  767. # %% [markdown]
  768. # **fit**
  769. # %%
  770. import os
  771. save_path = "/content/drive/My Drive/Vessel_Project"
  772. # Create folder if not exists
  773. os.makedirs(save_path, exist_ok=True)
  774. print("✅ Folder Ready")
  775. # %%
  776. # Mount Google Drive
  777. # Save model
  778. model.save("/content/drive/My Drive/Vessel_Project/vessel_model.keras")
  779. print("✅ Model Saved Successfully")
  780. # %%
  781. print(model.output_shape)
  782. # %%
  783. test_generator = Val_Generator(test_images_files, test_mask_files,
  784. batch_size=20,
  785. img_dim=(batch_img_dim[1], batch_img_dim[2]),
  786. augmentation=True)
  787. for x_test, y_test in test_generator:
  788. break
  789. # ✅ FIX HERE (remove [0])
  790. y_pred = model.predict(x_test)
  791. # Flatten
  792. y_true = (y_test > 0.5).astype(np.uint8).flatten()
  793. y_pred = (y_pred > 0.5).astype(np.uint8).flatten()
  794. from sklearn.metrics import classification_report, roc_auc_score
  795. report = classification_report(y_true, y_pred, output_dict=True)
  796. Precision = report['1']['precision']
  797. Recall = report['1']['recall']
  798. F1_score = report['1']['f1-score']
  799. Sensitivity = Recall
  800. Specificity = report['0']['recall']
  801. IOU = (Precision * Recall) / (Precision + Recall - Precision * Recall)
  802. # ⚠️ AUC (use probability before threshold)
  803. y_pred_prob = model.predict(x_test).flatten()
  804. AUC = roc_auc_score(y_true, y_pred_prob)
  805. print("Precision score: {0:.2f}\n".format(Precision))
  806. print("Recall score: {0:.2f}\n".format(Recall))
  807. print("F1-Score: {0:.2f}\n".format(F1_score))
  808. print("Sensitivity: {0:.2f}\n".format(Sensitivity))
  809. print("Specificity: {0:.2f}\n".format(Specificity))
  810. print("IOU: {0:.2f}\n".format(IOU))
  811. print("AUC: {0:.2f}\n".format(AUC))
  812. print('-'*50,'\n')
  813. print(classification_report(y_true, y_pred))
  814. # %%
  815. # Get one batch
  816. for x_test, y_test in test_generator:
  817. break
  818. # Predict
  819. y_pred_prob = model.predict(x_test)
  820. # ✅ Ensure same shape
  821. print("y_test shape:", y_test.shape)
  822. print("y_pred shape:", y_pred_prob.shape)
  823. # Flatten BOTH equally
  824. y_true = y_test.reshape(-1)
  825. y_pred_prob = y_pred_prob.reshape(-1)
  826. # Threshold
  827. y_pred = (y_pred_prob > 0.5).astype(np.uint8)
  828. y_true = (y_true > 0.5).astype(np.uint8)
  829. from sklearn.metrics import classification_report, roc_auc_score
  830. # ✅ NOW NO ERROR
  831. report = classification_report(y_true, y_pred, output_dict=True)
  832. Precision = report['1']['precision']
  833. Recall = report['1']['recall']
  834. F1_score = report['1']['f1-score']
  835. Sensitivity = Recall
  836. Specificity = report['0']['recall']
  837. IOU = (Precision * Recall) / (Precision + Recall - Precision * Recall)
  838. # AUC (use probability)
  839. AUC = roc_auc_score(y_true, y_pred_prob)
  840. print("Precision:", Precision)
  841. print("Recall:", Recall)
  842. print("F1:", F1_score)
  843. print("Sensitivity:", Sensitivity)
  844. print("Specificity:", Specificity)
  845. print("IOU:", IOU)
  846. print("AUC:", AUC)
  847. print("\n", classification_report(y_true, y_pred))
  848. # %%
  849. test_generator = Val_Generator(test_images_files, test_mask_files,
  850. batch_size=20,
  851. img_dim=(batch_img_dim[1], batch_img_dim[2]),
  852. augmentation=True)
  853. for x_test, y_test in test_generator:
  854. break
  855. # ✅ PREDICT (NO INDEX)
  856. y_pred_prob = model.predict(x_test)
  857. # ✅ SAME SHAPE CHECK
  858. print("y_test:", y_test.shape)
  859. print("y_pred:", y_pred_prob.shape)
  860. # Flatten
  861. y_true = (y_test > 0.5).astype(np.uint8).reshape(-1)
  862. y_pred_prob = y_pred_prob.reshape(-1)
  863. # Threshold
  864. y_pred = (y_pred_prob > 0.5).astype(np.uint8)
  865. from sklearn.metrics import classification_report, roc_auc_score
  866. report = classification_report(y_true, y_pred, output_dict=True)
  867. Precision = report['1']['precision']
  868. Recall = report['1']['recall']
  869. F1_score = report['1']['f1-score']
  870. Sensitivity = Recall
  871. Specificity = report['0']['recall']
  872. IOU = (Precision * Recall) / (Precision + Recall - Precision * Recall)
  873. # ✅ AUC (USE PROBABILITY)
  874. AUC = roc_auc_score(y_true, y_pred_prob)
  875. print("Precision:", Precision)
  876. print("Recall:", Recall)
  877. print("F1:", F1_score)
  878. print("Sensitivity:", Sensitivity)
  879. print("Specificity:", Specificity)
  880. print("IOU:", IOU)
  881. print("AUC:", AUC)
  882. print("\n", classification_report(y_true, y_pred))
  883. # %%
  884. for x_test, y_test in test_generator:
  885. break
  886. # ✅ NO INDEX
  887. y_pred_prob = model.predict(x_test)
  888. # Flatten properly
  889. y_true = (y_test > 0.5).astype(np.uint8).reshape(-1)
  890. y_pred_prob = y_pred_prob.reshape(-1)
  891. # Threshold
  892. y_pred = (y_pred_prob > 0.5).astype(np.uint8)
  893. from sklearn.metrics import classification_report, roc_auc_score
  894. report = classification_report(y_true, y_pred, output_dict=True)
  895. Precision = report['1']['precision']
  896. Recall = report['1']['recall']
  897. F1_score = report['1']['f1-score']
  898. Sensitivity = Recall
  899. Specificity = report['0']['recall']
  900. IOU = (Precision * Recall) / (Precision + Recall - Precision * Recall)
  901. AUC = roc_auc_score(y_true, y_pred_prob)
  902. print("Precision:", Precision)
  903. print("Recall:", Recall)
  904. print("F1:", F1_score)
  905. print("Sensitivity:", Sensitivity)
  906. print("Specificity:", Specificity)
  907. print("IOU:", IOU)
  908. print("AUC:", AUC)
  909. print("\n", classification_report(y_true, y_pred))
  910. # %%
  911. test_generator = Val_Generator(test_images_files, test_mask_files,
  912. batch_size=20,
  913. img_dim=(batch_img_dim[1], batch_img_dim[2]),
  914. augmentation=True)
  915. for x_test, y_test in test_generator:
  916. break
  917. # ✅ ONLY THIS
  918. y_pred_prob = model.predict(x_test)
  919. # Shape check (optional but useful)
  920. print("y_test:", y_test.shape)
  921. print("y_pred:", y_pred_prob.shape)
  922. # Flatten properly
  923. y_true = (y_test > 0.5).astype(np.uint8).reshape(-1)
  924. y_pred_prob = y_pred_prob.reshape(-1)
  925. # Threshold
  926. y_pred = (y_pred_prob > 0.5).astype(np.uint8)
  927. from sklearn.metrics import classification_report, roc_auc_score
  928. report = classification_report(y_true, y_pred, output_dict=True)
  929. Precision = report['1']['precision']
  930. Recall = report['1']['recall']
  931. F1_score = report['1']['f1-score']
  932. Sensitivity = Recall
  933. Specificity = report['0']['recall']
  934. IOU = (Precision * Recall) / (Precision + Recall - Precision * Recall)
  935. AUC = roc_auc_score(y_true, y_pred_prob)
  936. print("Precision:", Precision)
  937. print("Recall:", Recall)
  938. print("F1:", F1_score)
  939. print("Sensitivity:", Sensitivity)
  940. print("Specificity:", Specificity)
  941. print("IOU:", IOU)
  942. print("AUC:", AUC)
  943. print("\n", classification_report(y_true, y_pred))
  944. # %%
  945. valid_generator = Val_Generator(
  946. test_images_files,
  947. test_mask_files,
  948. batch_size=1,
  949. img_dim=(batch_img_dim[1], batch_img_dim[2]),
  950. augmentation=False
  951. )
  952. x_val = []
  953. y_val = []
  954. p_val = []
  955. for x, y in valid_generator:
  956. # ✅ ONLY ONE PREDICTION
  957. pred = model.predict(x)
  958. x_val.append(np.squeeze(x, 0))
  959. y_val.append(np.squeeze(y, 0))
  960. p_val.append(np.squeeze(pred, 0))
  961. # Convert to array
  962. x_val = np.array(x_val)
  963. y_val = np.array(y_val)
  964. p_val = np.array(p_val)
  965. # %%
  966. # ================== INIT (MUST ADD FIRST) ==================
  967. x_val = []
  968. y_val = []
  969. p_val1 = []
  970. p_val2 = []
  971. p_val3 = []
  972. p_val4 = []
  973. p_val5 = []
  974. # ================== PREDICTION LOOP ==================
  975. for x, y in valid_generator:
  976. preds = model.predict(x) # ✅ only once (VERY IMPORTANT)
  977. # ✅ Handle multi-output / single-output
  978. if isinstance(preds, list):
  979. p1 = (preds[0] + preds[1] + preds[2] + preds[3]) / 4
  980. p2 = preds[3]
  981. p3 = preds[2]
  982. p4 = preds[1]
  983. p5 = preds[0]
  984. else:
  985. p1 = preds
  986. p2 = preds
  987. p3 = preds
  988. p4 = preds
  989. p5 = preds
  990. # ✅ Store values
  991. x_val.append(np.squeeze(x, axis=0))
  992. y_val.append(np.squeeze(y, axis=0))
  993. p_val1.append(np.squeeze(p1, axis=0))
  994. p_val2.append(np.squeeze(p2, axis=0))
  995. p_val3.append(np.squeeze(p3, axis=0))
  996. p_val4.append(np.squeeze(p4, axis=0))
  997. p_val5.append(np.squeeze(p5, axis=0))
  998. # ================== CONVERT TO NUMPY ==================
  999. x_val = np.array(x_val)
  1000. y_val = np.array(y_val)
  1001. p_val1 = np.array(p_val1)
  1002. p_val2 = np.array(p_val2)
  1003. p_val3 = np.array(p_val3)
  1004. p_val4 = np.array(p_val4)
  1005. p_val5 = np.array(p_val5)
  1006. # ================== PLOTTING ==================
  1007. num = min(5, len(x_val)) # ✅ avoid empty plots
  1008. figsize = (20, 3)
  1009. # 🔹 Images
  1010. fig, axes = plt.subplots(1, num, figsize=figsize)
  1011. fig.suptitle('Images', fontsize=15)
  1012. for img, ax in zip(x_val[:num], axes):
  1013. ax.imshow(img)
  1014. ax.axis('off')
  1015. plt.tight_layout()
  1016. plt.show()
  1017. # 🔹 Ground Truth
  1018. fig, axes = plt.subplots(1, num, figsize=figsize)
  1019. fig.suptitle('Original Masks', fontsize=15)
  1020. for img, ax in zip(y_val[:num], axes):
  1021. ax.imshow(np.squeeze(img), cmap='gray')
  1022. ax.axis('off')
  1023. plt.tight_layout()
  1024. plt.show()
  1025. # 🔹 Predicted (Average of 4)
  1026. fig, axes = plt.subplots(1, num, figsize=figsize)
  1027. fig.suptitle('Predicted Masks (All Outputs Fusion)', fontsize=15)
  1028. for img, ax in zip(p_val1[:num], axes):
  1029. ax.imshow(np.squeeze(img), cmap='gray')
  1030. ax.axis('off')
  1031. plt.tight_layout()
  1032. plt.show()
  1033. # 🔹 Output 4
  1034. fig, axes = plt.subplots(1, num, figsize=figsize)
  1035. fig.suptitle('Predicted Masks (Output 4)', fontsize=15)
  1036. for img, ax in zip(p_val2[:num], axes):
  1037. ax.imshow(np.squeeze(img), cmap='gray')
  1038. ax.axis('off')
  1039. plt.tight_layout()
  1040. plt.show()
  1041. # 🔹 Output 3
  1042. fig, axes = plt.subplots(1, num, figsize=figsize)
  1043. fig.suptitle('Predicted Masks (Output 3)', fontsize=15)
  1044. for img, ax in zip(p_val3[:num], axes):
  1045. ax.imshow(np.squeeze(img), cmap='gray')
  1046. ax.axis('off')
  1047. plt.tight_layout()
  1048. plt.show()
  1049. # 🔹 Output 2
  1050. fig, axes = plt.subplots(1, num, figsize=figsize)
  1051. fig.suptitle('Predicted Masks (Output 2)', fontsize=15)
  1052. for img, ax in zip(p_val4[:num], axes):
  1053. ax.imshow(np.squeeze(img), cmap='gray')
  1054. ax.axis('off')
  1055. plt.tight_layout()
  1056. plt.show()
  1057. # 🔹 Output 1
  1058. fig, axes = plt.subplots(1, num, figsize=figsize)
  1059. fig.suptitle('Predicted Masks (Output 1)', fontsize=15)
  1060. for img, ax in zip(p_val5[:num], axes):
  1061. ax.imshow(np.squeeze(img), cmap='gray')
  1062. ax.axis('off')
  1063. plt.tight_layout()
  1064. plt.show()
  1065. # %%
  1066. # ✅ Generate prediction AFTER training (safe placement)
  1067. try:
  1068. y_pred_prob = model.predict(X_test)
  1069. except NameError:
  1070. print("Model ")
  1071. # %%
  1072. # ✅ Improved AUC Calculation (no effect on other metrics)
  1073. from sklearn.metrics import roc_auc_score, confusion_matrix, accuracy_score, precision_score, recall_score, f1_score, roc_curve
  1074. import numpy as np
  1075. import matplotlib.pyplot as plt
  1076. # ----------------------------
  1077. # Check variable
  1078. # ----------------------------
  1079. if 'y_pred_prob' not in globals():
  1080. raise ValueError("y_pred_prob not found")
  1081. # ----------------------------
  1082. # Flatten (segmentation case)
  1083. # ----------------------------
  1084. y_true = y_test.flatten()
  1085. y_prob = y_pred_prob.flatten()
  1086. # Binary prediction
  1087. y_pred = (y_prob > 0.5).astype(int)
  1088. # ----------------------------
  1089. # Confusion Matrix
  1090. # ----------------------------
  1091. tn, fp, fn, tp = confusion_matrix(y_true, y_pred).ravel()
  1092. # ----------------------------
  1093. # Metrics
  1094. # ----------------------------
  1095. accuracy = (tp + tn) / (tp + tn + fp + fn)
  1096. sensitivity = tp / (tp + fn + 1e-7) # Recall
  1097. specificity = tn / (tn + fp + 1e-7)
  1098. precision = tp / (tp + fp + 1e-7)
  1099. f1 = f1_score(y_true, y_pred)
  1100. # IoU (Jaccard Index)
  1101. iou = tp / (tp + fp + fn + 1e-7)
  1102. # Dice Coefficient
  1103. dice = (2 * tp) / (2 * tp + fp + fn + 1e-7)
  1104. # AUC
  1105. epsilon = 1e-6
  1106. y_prob = np.clip(y_prob, epsilon, 1 - epsilon)
  1107. auc = roc_auc_score(y_true, y_prob)
  1108. # ----------------------------
  1109. # Print Results
  1110. # ----------------------------
  1111. print("Accuracy :", round(accuracy, 4))
  1112. print("Specificity :", round(specificity, 4))
  1113. print("Sensitivity :", round(sensitivity, 4))
  1114. print("Precision :", round(precision, 4))
  1115. print("F1 Score :", round(f1, 4))
  1116. print("IoU :", round(iou, 4))
  1117. print("Dice Score :", round(dice, 4))
  1118. print("AUC :", round(auc, 4))
  1119. # ----------------------------
  1120. # ROC Curve
  1121. # ----------------------------
  1122. fpr, tpr, _ = roc_curve(y_true, y_prob)
  1123. plt.figure()
  1124. plt.plot(fpr, tpr, label=f"AUC = {auc:.3f}")
  1125. plt.plot([0, 1], [0, 1], linestyle='--')
  1126. plt.xlabel("False Positive Rate")
  1127. plt.ylabel("True Positive Rate")
  1128. plt.title("ROC Curve")
  1129. plt.legend()
  1130. plt.grid()
  1131. plt.show()
  1132. # %%
  1133. # =============================
  1134. # IMPORTS
  1135. # =============================
  1136. import numpy as np
  1137. import matplotlib.pyplot as plt
  1138. from sklearn.metrics import (
  1139. roc_auc_score, confusion_matrix, f1_score,
  1140. roc_curve, precision_score, recall_score
  1141. )
  1142. # =============================
  1143. # CHECK VARIABLES
  1144. # =============================
  1145. if 'y_pred_prob' not in globals() or 'y_test' not in globals():
  1146. raise ValueError("❌ y_test or y_pred_prob not found. Run prediction first.")
  1147. # =============================
  1148. # PREPARE DATA
  1149. # =============================
  1150. y_true = y_test.flatten()
  1151. y_prob = y_pred_prob.flatten()
  1152. # Threshold
  1153. y_pred = (y_prob > 0.5).astype(int)
  1154. # =============================
  1155. # CONFUSION MATRIX VALUES
  1156. # =============================
  1157. tn, fp, fn, tp = confusion_matrix(y_true, y_pred).ravel()
  1158. # =============================
  1159. # METRICS
  1160. # =============================
  1161. accuracy = (tp + tn) / (tp + tn + fp + fn)
  1162. sensitivity = tp / (tp + fn + 1e-7)
  1163. specificity = tn / (tn + fp + 1e-7)
  1164. precision = precision_score(y_true, y_pred)
  1165. recall = recall_score(y_true, y_pred)
  1166. f1 = f1_score(y_true, y_pred)
  1167. iou = tp / (tp + fp + fn + 1e-7)
  1168. dice = (2 * tp) / (2 * tp + fp + fn + 1e-7)
  1169. # AUC
  1170. epsilon = 1e-6
  1171. y_prob = np.clip(y_prob, epsilon, 1 - epsilon)
  1172. auc = roc_auc_score(y_true, y_prob)
  1173. # =============================
  1174. # PRINT RESULTS
  1175. # =============================
  1176. print("\n📊 PERFORMANCE METRICS")
  1177. print("Accuracy :", round(accuracy, 4))
  1178. print("Specificity :", round(specificity, 4))
  1179. print("Sensitivity :", round(sensitivity, 4))
  1180. print("Precision :", round(precision, 4))
  1181. print("Recall :", round(recall, 4))
  1182. print("F1 Score :", round(f1, 4))
  1183. print("IoU :", round(iou, 4))
  1184. print("Dice Score :", round(dice, 4))
  1185. print("AUC :", round(auc, 4))
  1186. # =============================
  1187. # ROC CURVE
  1188. # =============================
  1189. fpr, tpr, _ = roc_curve(y_true, y_prob)
  1190. plt.figure()
  1191. plt.plot(fpr, tpr, label=f"AUC = {auc:.4f}")
  1192. plt.plot([0, 1], [0, 1], linestyle='--')
  1193. plt.xlabel("False Positive Rate")
  1194. plt.ylabel("True Positive Rate")
  1195. plt.title("ROC Curve")
  1196. plt.legend()
  1197. plt.grid()
  1198. plt.show()
  1199. # =============================
  1200. # CONFUSION MATRIX (REFINED)
  1201. # =============================
  1202. cm = confusion_matrix(y_true, y_pred)
  1203. plt.figure(figsize=(6,5))
  1204. plt.imshow(cm, cmap='Blues')
  1205. plt.title("Confusion Matrix")
  1206. plt.xlabel("Predicted Label")
  1207. plt.ylabel("True Label")
  1208. plt.xticks([0,1], ["Pred 0", "Pred 1"])
  1209. plt.yticks([0,1], ["True 0", "True 1"])
  1210. threshold = cm.max() / 2
  1211. for i in range(cm.shape[0]):
  1212. for j in range(cm.shape[1]):
  1213. color = "white" if cm[i, j] > threshold else "black"
  1214. plt.text(j, i, f"{cm[i, j]}",
  1215. ha="center", va="center",
  1216. color=color, fontsize=12, fontweight='bold')
  1217. plt.colorbar()
  1218. plt.tight_layout()
  1219. plt.show()
  1220. # =============================
  1221. # BOOTSTRAP CI
  1222. # =============================
  1223. def bootstrap_ci(y_true, y_pred, metric_func, n_bootstrap=500):
  1224. scores = []
  1225. n = len(y_true)
  1226. for _ in range(n_bootstrap):
  1227. idx = np.random.choice(n, n, replace=True)
  1228. score = metric_func(y_true[idx], y_pred[idx])
  1229. scores.append(score)
  1230. scores = np.array(scores)
  1231. return scores.mean(), np.percentile(scores, 2.5), np.percentile(scores, 97.5)
  1232. # =============================
  1233. # CUSTOM METRICS FOR CI
  1234. # =============================
  1235. def dice_func(y_true, y_pred):
  1236. intersection = np.sum(y_true * y_pred)
  1237. return (2 * intersection) / (np.sum(y_true) + np.sum(y_pred) + 1e-6)
  1238. def iou_func(y_true, y_pred):
  1239. intersection = np.sum(y_true * y_pred)
  1240. union = np.sum(y_true) + np.sum(y_pred) - intersection
  1241. return intersection / (union + 1e-6)
  1242. # =============================
  1243. # CALCULATE CI
  1244. # =============================
  1245. mean_auc, low_auc, high_auc = bootstrap_ci(y_true, y_prob, roc_auc_score)
  1246. mean_f1, low_f1, high_f1 = bootstrap_ci(y_true, y_pred, f1_score)
  1247. mean_dice, low_dice, high_dice = bootstrap_ci(y_true, y_pred, dice_func)
  1248. mean_iou, low_iou, high_iou = bootstrap_ci(y_true, y_pred, iou_func)
  1249. mean_prec, low_prec, high_prec = bootstrap_ci(y_true, y_pred, precision_score)
  1250. mean_rec, low_rec, high_rec = bootstrap_ci(y_true, y_pred, recall_score)
  1251. # =============================
  1252. # PRINT CI RESULTS
  1253. # =============================
  1254. print("\n📈 STATISTICAL ANALYSIS (95% CI)")
  1255. print(f"AUC : {mean_auc:.4f} ({low_auc:.4f} - {high_auc:.4f})")
  1256. print(f"Dice : {mean_dice:.4f} ({low_dice:.4f} - {high_dice:.4f})")
  1257. print(f"IoU : {mean_iou:.4f} ({low_iou:.4f} - {high_iou:.4f})")
  1258. print(f"F1 Score : {mean_f1:.4f} ({low_f1:.4f} - {high_f1:.4f})")
  1259. print(f"Precision : {mean_prec:.4f} ({low_prec:.4f} - {high_prec:.4f})")
  1260. print(f"Recall : {mean_rec:.4f} ({low_rec:.4f} - {high_rec:.4f})")
  1261. # %%
  1262. # =============================
  1263. # RANDOM SEED (REPRODUCIBILITY)
  1264. # =============================
  1265. import os, random, time
  1266. import numpy as np
  1267. import tensorflow as tf
  1268. SEED = 42
  1269. os.environ['PYTHONHASHSEED'] = str(SEED)
  1270. random.seed(SEED)
  1271. np.random.seed(SEED)
  1272. tf.random.set_seed(SEED)
  1273. print(f"✅ Random Seed Set: {SEED}")
  1274. # =============================
  1275. # IMPORTS
  1276. # =============================
  1277. import matplotlib.pyplot as plt
  1278. from sklearn.metrics import (
  1279. roc_auc_score, confusion_matrix, f1_score,
  1280. roc_curve, precision_score, recall_score
  1281. )
  1282. from sklearn.model_selection import train_test_split
  1283. # =============================
  1284. # CHECK VARIABLES
  1285. # =============================
  1286. if 'y_pred_prob' not in globals() or 'y_test' not in globals():
  1287. raise ValueError("❌ y_test or y_pred_prob not found. Run prediction first.")
  1288. # =============================
  1289. # PREPARE DATA
  1290. # =============================
  1291. y_true = y_test.flatten()
  1292. y_prob = y_pred_prob.flatten()
  1293. # Threshold
  1294. y_pred = (y_prob > 0.5).astype(int)
  1295. # =============================
  1296. # TRAINING TIME (example placeholder)
  1297. # =============================
  1298. # 👉 NOTE: இந்த பகுதி model.fit() இருக்கும் இடத்தில add பண்ணணும்
  1299. # Example:
  1300. # start_train = time.time()
  1301. # model.fit(...)
  1302. # end_train = time.time()
  1303. # training_time = end_train - start_train
  1304. training_time = "ADD_WHERE_MODEL_FIT"
  1305. # =============================
  1306. # INFERENCE TIME
  1307. # =============================
  1308. start_inf = time.time()
  1309. _ = y_pred_prob # already predicted (if not, use model.predict)
  1310. end_inf = time.time()
  1311. inference_time = end_inf - start_inf
  1312. per_image_time = inference_time / len(y_true)
  1313. # =============================
  1314. # CONFUSION MATRIX VALUES
  1315. # =============================
  1316. tn, fp, fn, tp = confusion_matrix(y_true, y_pred).ravel()
  1317. # =============================
  1318. # METRICS
  1319. # =============================
  1320. accuracy = (tp + tn) / (tp + tn + fp + fn)
  1321. sensitivity = tp / (tp + fn + 1e-7)
  1322. specificity = tn / (tn + fp + 1e-7)
  1323. precision = precision_score(y_true, y_pred)
  1324. recall = recall_score(y_true, y_pred)
  1325. f1 = f1_score(y_true, y_pred)
  1326. iou = tp / (tp + fp + fn + 1e-7)
  1327. dice = (2 * tp) / (2 * tp + fp + fn + 1e-7)
  1328. # AUC
  1329. epsilon = 1e-6
  1330. y_prob = np.clip(y_prob, epsilon, 1 - epsilon)
  1331. auc = roc_auc_score(y_true, y_prob)
  1332. # =============================
  1333. # PRINT RESULTS
  1334. # =============================
  1335. print("\n📊 PERFORMANCE METRICS")
  1336. print("Accuracy :", round(accuracy, 4))
  1337. print("Specificity :", round(specificity, 4))
  1338. print("Sensitivity :", round(sensitivity, 4))
  1339. print("Precision :", round(precision, 4))
  1340. print("Recall :", round(recall, 4))
  1341. print("F1 Score :", round(f1, 4))
  1342. print("IoU :", round(iou, 4))
  1343. print("Dice Score :", round(dice, 4))
  1344. print("AUC :", round(auc, 4))
  1345. print("\n⏱️ TIMING")
  1346. print(f"Inference Time (Total): {inference_time:.4f} sec")
  1347. print(f"Inference Time per image: {per_image_time:.6f} sec")
  1348. # =============================
  1349. # ROC CURVE
  1350. # =============================
  1351. fpr, tpr, _ = roc_curve(y_true, y_prob)
  1352. plt.figure()
  1353. plt.plot(fpr, tpr, label=f"AUC = {auc:.4f}")
  1354. plt.plot([0, 1], [0, 1], linestyle='--')
  1355. plt.xlabel("False Positive Rate")
  1356. plt.ylabel("True Positive Rate")
  1357. plt.title("ROC Curve")
  1358. plt.legend()
  1359. plt.grid()
  1360. plt.show()
  1361. # =============================
  1362. # CONFUSION MATRIX (REFINED)
  1363. # =============================
  1364. cm = confusion_matrix(y_true, y_pred)
  1365. plt.figure(figsize=(6,5))
  1366. plt.imshow(cm, cmap='Blues')
  1367. plt.title("Confusion Matrix")
  1368. plt.xlabel("Predicted Label")
  1369. plt.ylabel("True Label")
  1370. plt.xticks([0,1], ["Pred 0", "Pred 1"])
  1371. plt.yticks([0,1], ["True 0", "True 1"])
  1372. threshold = cm.max() / 2
  1373. for i in range(cm.shape[0]):
  1374. for j in range(cm.shape[1]):
  1375. color = "white" if cm[i, j] > threshold else "black"
  1376. plt.text(j, i, f"{cm[i, j]}",
  1377. ha="center", va="center",
  1378. color=color, fontsize=12, fontweight='bold')
  1379. plt.colorbar()
  1380. plt.tight_layout()
  1381. plt.show()
  1382. # =============================
  1383. # BOOTSTRAP CI
  1384. # =============================
  1385. def bootstrap_ci(y_true, y_pred, metric_func, n_bootstrap=500):
  1386. scores = []
  1387. n = len(y_true)
  1388. for _ in range(n_bootstrap):
  1389. idx = np.random.choice(n, n, replace=True)
  1390. score = metric_func(y_true[idx], y_pred[idx])
  1391. scores.append(score)
  1392. scores = np.array(scores)
  1393. return scores.mean(), np.percentile(scores, 2.5), np.percentile(scores, 97.5)
  1394. # =============================
  1395. # CUSTOM METRICS FOR CI
  1396. # =============================
  1397. def dice_func(y_true, y_pred):
  1398. intersection = np.sum(y_true * y_pred)
  1399. return (2 * intersection) / (np.sum(y_true) + np.sum(y_pred) + 1e-6)
  1400. def iou_func(y_true, y_pred):
  1401. intersection = np.sum(y_true * y_pred)
  1402. union = np.sum(y_true) + np.sum(y_pred) - intersection
  1403. return intersection / (union + 1e-6)
  1404. # =============================
  1405. # CALCULATE CI
  1406. # =============================
  1407. mean_auc, low_auc, high_auc = bootstrap_ci(y_true, y_prob, roc_auc_score)
  1408. mean_f1, low_f1, high_f1 = bootstrap_ci(y_true, y_pred, f1_score)
  1409. mean_dice, low_dice, high_dice = bootstrap_ci(y_true, y_pred, dice_func)
  1410. mean_iou, low_iou, high_iou = bootstrap_ci(y_true, y_pred, iou_func)
  1411. mean_prec, low_prec, high_prec = bootstrap_ci(y_true, y_pred, precision_score)
  1412. mean_rec, low_rec, high_rec = bootstrap_ci(y_true, y_pred, recall_score)
  1413. # =============================
  1414. # PRINT CI RESULTS
  1415. # =============================
  1416. print("\n📈 STATISTICAL ANALYSIS (95% CI)")
  1417. print(f"AUC : {mean_auc:.4f} ({low_auc:.4f} - {high_auc:.4f})")
  1418. print(f"Dice : {mean_dice:.4f} ({low_dice:.4f} - {high_dice:.4f})")
  1419. print(f"IoU : {mean_iou:.4f} ({low_iou:.4f} - {high_iou:.4f})")
  1420. print(f"F1 Score : {mean_f1:.4f} ({low_f1:.4f} - {high_f1:.4f})")
  1421. print(f"Precision : {mean_prec:.4f} ({low_prec:.4f} - {high_prec:.4f})")
  1422. print(f"Recall : {mean_rec:.4f} ({low_rec:.4f} - {high_rec:.4f})")
  1423. # %%
  1424. import matplotlib.pyplot as plt
  1425. # =============================
  1426. # METRICS VALUES
  1427. # =============================
  1428. metrics = [
  1429. "Accuracy", "Specificity", "Sensitivity",
  1430. "Precision", "Recall", "F1 Score",
  1431. "IoU", "Dice", "AUC"
  1432. ]
  1433. values = [
  1434. 0.9494, 0.976, 0.8254,
  1435. 0.881, 0.8254, 0.8523,
  1436. 0.7426, 0.8523, 0.9718
  1437. ]
  1438. # =============================
  1439. # BAR GRAPH
  1440. # =============================
  1441. plt.figure(figsize=(10,5))
  1442. plt.bar(metrics, values)
  1443. # Labels
  1444. plt.xlabel("Metrics")
  1445. plt.ylabel("Score")
  1446. plt.title(" Proposed Model Performance Metrics")
  1447. # Rotate x labels
  1448. plt.xticks(rotation=30)
  1449. # Add values on top
  1450. for i, v in enumerate(values):
  1451. plt.text(i, v + 0.01, f"{v:.2f}", ha='center')
  1452. plt.ylim(0, 1.05)
  1453. plt.grid()
  1454. plt.tight_layout()
  1455. plt.show()
  1456. # %%
  1457. import matplotlib.pyplot as plt
  1458. from sklearn.metrics import roc_curve, auc, precision_recall_curve
  1459. # =============================
  1460. # CHECK VARIABLES
  1461. # =============================
  1462. if 'y_pred_prob' not in globals() or 'y_test' not in globals():
  1463. raise ValueError("❌ y_test or y_pred_prob not found")
  1464. # =============================
  1465. # PREPARE DATA
  1466. # =============================
  1467. y_true = y_test.flatten()
  1468. y_prob = y_pred_prob.flatten()
  1469. # =============================
  1470. # ROC CURVE
  1471. # =============================
  1472. fpr, tpr, _ = roc_curve(y_true, y_prob)
  1473. roc_auc = auc(fpr, tpr)
  1474. plt.figure(figsize=(6,5))
  1475. plt.plot(fpr, tpr, label=f"AUC = {roc_auc:.4f}")
  1476. plt.plot([0,1], [0,1], linestyle='--')
  1477. plt.xlabel("False Positive Rate")
  1478. plt.ylabel("True Positive Rate")
  1479. plt.title("ROC Curve")
  1480. plt.legend(loc="lower right")
  1481. plt.grid()
  1482. plt.tight_layout()
  1483. plt.show()
  1484. # =============================
  1485. # PRECISION-RECALL CURVE
  1486. # =============================
  1487. precision, recall, _ = precision_recall_curve(y_true, y_prob)
  1488. pr_auc = auc(recall, precision)
  1489. plt.figure(figsize=(6,5))
  1490. plt.plot(recall, precision, label=f"PR AUC = {pr_auc:.4f}")
  1491. plt.xlabel("Recall")
  1492. plt.ylabel("Precision")
  1493. plt.title("Precision-Recall Curve")
  1494. plt.legend(loc="lower left")
  1495. plt.grid()
  1496. plt.tight_layout()
  1497. plt.show()
  1498. # %%
  1499. import matplotlib.pyplot as plt
  1500. metrics = ['AUC', 'Dice', 'IoU', 'F1', 'Precision', 'Recall']
  1501. means = [0.9710, 0.8523, 0.7426, 0.8523, 0.8810, 0.8255]
  1502. # CI half-width (upper-lower)/2
  1503. errors = [
  1504. (0.9714-0.9706)/2,
  1505. (0.8534-0.8511)/2,
  1506. (0.7442-0.7407)/2,
  1507. (0.8535-0.8513)/2,
  1508. (0.8822-0.8796)/2,
  1509. (0.8271-0.8239)/2
  1510. ]
  1511. plt.figure()
  1512. plt.bar(metrics, means, yerr=errors)
  1513. plt.xlabel("Metrics")
  1514. plt.ylabel("Values")
  1515. plt.title("Performance with 95% Confidence Intervals")
  1516. plt.show()
  1517. # %%
  1518. print(type(x_test))
  1519. print(x_test.shape)
  1520. print(type(y_test))
  1521. # %%
  1522. print(type(model))

41598_2026_48475_MOESM2_ESM.ipynb, no license · at the source

Overview

Authors: Jegan Sivaraman1, Arjun Paramarthalingam1, Arulnancy Thirunavukkarasu2, Asokan Vasudevan3, Soon Eu Hui3, Duraimurugan Samiayya4
  1. Computer Science and Engineering, University College of Engineering Villupuram, Villupuram, Tamilnadu India
  2. Electronics and Communication Engineering, V R S College of Engineering and Technology, Arasur, Tamilnadu India
  3. Faculty of Business and Communications, INTI International University, Persiaran Perdana BBN Putra Nilai, Nilai, Negeri Sembilan 71800 Malaysia
  4. Information Technology, St. Joseph’s College of Engineering, Chennai, Tamilnadu India
Journal: Scientific reports, volume 16, issue 1, article 17230
Dates: received 25 January 2026; accepted 8 April 2026; published online 13 April 2026
Type: Research article · Language: English
License: CC BY-NC-ND
Identifiers: DOI 10.1038/s41598-026-48475-6 · PMID 41974826 · PMCID PMC13234283 · OpenAlex W7154041874
Open access: gold, a free copy (OpenAlex)
Status: code verified
Categories: other (modality), human (organism), other condition (population), methods / tools (subfield)
Methods: Connectivity, Statistics, Preprocessing, Machine learning, fMRI & imaging
Keywords: Convolutional neural network, U-Net, Deep learning, Blood vessel segmentation, Colour fundus images, Process innovation, Computational biology and bioinformatics, Diseases, Engineering, Health care, Mathematics and computing, Medical research
MeSH: Fundus Oculi*, Image Processing, Computer-Assisted*, Retinal Diseases*, Retinal Vessels*, Convolutional Neural Networks, Deep Learning, Diabetic Retinopathy, Humans, Neural Networks, Computer (* major topic)
Topic: Retinal Imaging and Analysis (Radiology, Nuclear Medicine and Imaging, Medicine), according to OpenAlex
Citations: not cited yet (Europe PMC); 24 references in the paper

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

License: none: the authors keep all their rights
State: the link answers, verified on 29 September 2026
Evidence: files inventoried
Languages: Jupyter (1)
Size: 1 file, 1 script
Software Heritage: not checked
Found in: the supplementary material
Holds: 1 notebook
Not found: README, license file, CITATION.cff, environment file, tests, continuous integration, documentation
Tools: Keras (1 file), Matplotlib (1 file), NumPy (1 file), OpenCV (1 file), Pillow (1 file), scikit-learn (1 file), seaborn (1 file), TensorFlow (1 file)
Availability: 1 check, the latest on 29 September 2026: the link answers (HTTP 200)
  • 29 September 2026: the link answers (HTTP 200)
1 file

supp:PMC13234283/41598_2026_48475_MOESM2_ESM.ipynb

License: none: the authors keep all their rights
State: the link answers, verified on 29 September 2026
Evidence: files inventoried
Languages: Jupyter (1)
Size: 1 file, 1 script
Software Heritage: not checked
Found in: the supplementary material
Holds: 1 notebook
Not found: README, license file, CITATION.cff, environment file, tests, continuous integration, documentation
Tools: Keras (1 file), Matplotlib (1 file), NumPy (1 file), OpenCV (1 file), Pillow (1 file), scikit-learn (1 file), seaborn (1 file), TensorFlow (1 file)
Availability: 1 check, the latest on 29 September 2026: the link answers (HTTP 200)
  • 29 September 2026: the link answers (HTTP 200)
1 file

supp:PMC13234283/41598_2026_48475_MOESM3_ESM.ipynb

License: none: the authors keep all their rights
State: the link answers, verified on 29 September 2026
Evidence: files inventoried
Languages: Jupyter (1)
Size: 1 file, 1 script
Software Heritage: not checked
Found in: the supplementary material
Holds: 1 notebook
Not found: README, license file, CITATION.cff, environment file, tests, continuous integration, documentation
Tools: Keras (1 file), Matplotlib (1 file), NumPy (1 file), OpenCV (1 file), Pillow (1 file), scikit-learn (1 file), seaborn (1 file), TensorFlow (1 file)
Availability: 1 check, the latest on 29 September 2026: the link answers (HTTP 200)
  • 29 September 2026: the link answers (HTTP 200)
1 file

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://doi.org/10.1038/s41598-026-48475-6

BibTeX

@article{sivaraman2026optimized,
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/s41598-026-48475-6},
url = {https://doi.org/10.1038/s41598-026-48475-6},
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/04/13
VL - 16
IS - 1
SP - 17230
SN - 2045-2322
PB - Nature Publishing Group
DO - 10.1038/s41598-026-48475-6
UR - https://doi.org/10.1038/s41598-026-48475-6
LA - en
ER -

CSL-JSON

{
"id": "10.1038/s41598-026-48475-6",
"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": "Sci Rep",
"volume": "16",
"issue": "1",
"page": "17230",
"DOI": "10.1038/s41598-026-48475-6",
"PMID": "41974826",
"PMCID": "PMC13234283",
"ISSN": "2045-2322",
"publisher": "Nature Publishing Group",
"URL": "https://doi.org/10.1038/s41598-026-48475-6",
"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 one
In 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 scenes
Journal: n/a
In 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. Medicine
In 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 <i>m/z</i> mapping and exploration.
Journal: Science advances
In 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 biology
In 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 biology
In 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 imaging
In common: Keras, TensorFlow, OpenCV, 5 other tools
[8] doi: [code]
Real-time closed-loop feedback system for mouse mesoscale cortical signal and movement control
Journal: eLife
In 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 advances
In 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 express
In 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.

Request its removal

To ask OSCR to remove this record, the copies of its authors' scripts or its tracing map, use the removal request page: signed in, you say who you are, what to remove and why, then review and confirm the request. Published rules decide every request (how).

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.