OSCR

LiteFeatNet: A parameter-efficient and performance-centric deep learning model for multi-ocular disease identification using intermediate feature reduction from fundus images.

Code ↔ Paper

3 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 3 matches
  1. [1] § 3. Materials and methods › 3.8. Experimental setup ↔ kerasMods.ipynb, lines 559–574 · score 0.68 · ReduceLROnPlateau, TensorFlow, Keras, scheduler, epochs, validation
  2. [2] § 3. Materials and methods › 3.8. Experimental setup ↔ code-nb-p.ipynb, lines 312–316 · score 0.62 · Cross Entropy, learning rate scheduler, Adam, optimizer, loss, train
  3. [3] § 3. Materials and methods › 3.8. Experimental setup ↔ kerasMods.ipynb, lines 559–574 · score 0.53 · ReduceLROnPlateau, Keras, schedulers, trained, model

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 · 617 lines · 21 KB · MIT · 2 matches

  1. # %%
  2. # libraries
  3. import os
  4. import cv2
  5. import numpy as np
  6. import pandas as pd
  7. import tensorflow as tf
  8. from tensorflow.keras import backend as K
  9. from sklearn.preprocessing import LabelEncoder
  10. from tensorflow.keras.utils import to_categorical
  11. from tensorflow.keras.applications import MobileNet,MobileNetV2, VGG16, Xception, NASNetMobile, DenseNet121, EfficientNetB5,EfficientNetB0,EfficientNetV2B0
  12. from tensorflow.keras import Input, Model
  13. from tensorflow.keras.layers import Conv2D, MaxPooling2D,ReLU,SeparableConv2D,Conv2DTranspose,GlobalAveragePooling2D,GlobalMaxPooling2D,Add,Activation, Dense, Dropout, Flatten, BatchNormalization, Concatenate, Activation
  14. from tensorflow.keras.optimizers import Adam, SGD
  15. from tensorflow.keras.regularizers import l2
  16. from tensorflow.keras.preprocessing.image import ImageDataGenerator
  17. import time
  18. import gc
  19. import matplotlib.pyplot as plt
  20. import seaborn as sns
  21. from tensorflow.keras.models import load_model
  22. from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix
  23. # %%
  24. # initial
  25. K.clear_session()
  26. gc.collect()
  27. imgSize = (224,224)
  28. inputShape = tuple(list(imgSize) + [3])
  29. batchSize = 32
  30. print(inputShape)
  31. # %%
  32. # I/O paths
  33. outPath = '/kaggle/working/'
  34. trainImagesPath = '/kaggle/input/dataset/training/images/'
  35. trainLabelsPath = '/kaggle/input/dataset/training/labels.xlsx'
  36. testImagesPath = '/kaggle/input/dataset/testing/images/'
  37. testLabelsPath = '/kaggle/input/dataset/testing/labels.xlsx'
  38. valImagesPath = '/kaggle/input/dataset/validation/images/'
  39. valLabelsPath = '/kaggle/input/dataset/validation/labels.xlsx'
  40. # %%
  41. # model handling
  42. def saveModel(model,savePath,modName):
  43. model.save(savePath + modName + '.h5')
  44. def printModelSummary(model):
  45. print(model.summary())
  46. # %%
  47. # time information
  48. def saveTime(time1,time2,savePath):
  49. time_data = {'Training_Time': [time1],'Testing_Time': [time2]}
  50. time_df = pd.DataFrame(time_data)
  51. time_df.to_excel(savePath + 'time.xlsx',index=False)
  52. # %%
  53. # epch vs. accuracy
  54. def plotAccuracy(hist,savePath):
  55. epochs = range(1, len(hist.history['accuracy']) + 1)
  56. plt.figure(figsize=(8,6))
  57. plt.plot(epochs, hist.history['accuracy'], label='Train Accuracy')
  58. plt.plot(epochs, hist.history['val_accuracy'], label='Validation Accuracy')
  59. plt.xlabel('Epoch', fontsize=12)
  60. plt.ylabel('Accuracy', fontsize=12)
  61. plt.xticks(ticks=range(0, len(epochs)+1, 5))
  62. plt.grid(True,linestyle='--', linewidth=0.5, color='gray')
  63. plt.legend()
  64. plt.savefig(savePath + 'accuracy_plot.png', dpi=1200)
  65. plt.show()
  66. # %%
  67. # epoch vs. loss
  68. def plotLoss(hist,savePath):
  69. epochs = range(1, len(hist.history['loss']) + 1)
  70. plt.figure(figsize=(8,6))
  71. plt.plot(epochs, hist.history['loss'], label='Train Loss')
  72. plt.plot(epochs, hist.history['val_loss'], label='Validation Loss')
  73. plt.xlabel('Epoch',fontsize=12)
  74. plt.ylabel('Loss', fontsize=12)
  75. plt.xticks(ticks=range(0, len(epochs)+1, 5))
  76. plt.grid(True,linestyle='--', linewidth=0.5, color='gray')
  77. plt.legend()
  78. plt.savefig(savePath + 'loss_plot.png', dpi=1200)
  79. plt.show()
  80. # %%
  81. # model history
  82. def saveModelRunHistory(hist,savePath):
  83. epochs = list(range(1, len(hist.history['accuracy']) + 1))
  84. train_acc = hist.history['accuracy']
  85. val_acc = hist.history['val_accuracy']
  86. train_loss = hist.history['loss']
  87. val_loss = hist.history['val_loss']
  88. modelHistory_df = pd.DataFrame({
  89. 'Epoch': epochs,
  90. 'Training Accuracy': train_acc,
  91. 'Validation Accuracy': val_acc,
  92. 'Training Loss': train_loss,
  93. 'Validation Loss': val_loss
  94. })
  95. modelHistory_df.to_excel(savePath + 'history_file.xlsx', index=False)
  96. # %%
  97. # calculate metrics (overall)
  98. def testMetricsOverall(Ypred,Yact,savePath):
  99. accuracy = accuracy_score(Yact, Ypred)
  100. precision = precision_score(Yact, Ypred, average='weighted', zero_division=0)
  101. recall = recall_score(Yact, Ypred, average='weighted', zero_division=0)
  102. f1 = f1_score(Yact, Ypred, average='weighted', zero_division=0)
  103. print(f"Accuracy: {accuracy}")
  104. print(f"Precision: {precision}")
  105. print(f"Recall: {recall}")
  106. print(f"F1-Score: {f1}")
  107. metrics = {'Metric': ['Accuracy', 'Precision', 'Recall', 'F1-Score'],
  108. 'Score': [accuracy, precision, recall, f1]
  109. }
  110. overallMetrics_df = pd.DataFrame(metrics)
  111. overallMetrics_df.to_excel(savePath + 'overall_metrics.xlsx', index=False)
  112. # %%
  113. # calculate metrics (class-wise breakdown)
  114. def testMetricsClassWise(Ypred,Yact,classEncoding,savePath):
  115. classLabels = list(classEncoding.keys())
  116. accuracy_list = []
  117. precision_list = []
  118. recall_list = []
  119. f1_list = []
  120. TP_list = []
  121. TN_list = []
  122. FP_list = []
  123. FN_list = []
  124. TPR_list = []
  125. TNR_list = []
  126. FPR_list = []
  127. FNR_list = []
  128. for label in classLabels:
  129. encoded_label = classEncoding[label]
  130. TP = np.sum((Ypred == encoded_label) & (Yact == encoded_label))
  131. TP_list.append(TP)
  132. FN = np.sum((Ypred != encoded_label) & (Yact == encoded_label))
  133. FN_list.append(FN)
  134. FP = np.sum((Ypred == encoded_label) & (Yact != encoded_label))
  135. FP_list.append(FP)
  136. TN = np.sum((Ypred != encoded_label) & (Yact != encoded_label))
  137. TN_list.append(TN)
  138. accuracy = (TP + TN) / (TP + TN + FP + FN)
  139. accuracy_list.append(accuracy)
  140. precision = precision_score(Yact, Ypred, labels=[encoded_label], average='macro', zero_division=0)
  141. precision_list.append(precision)
  142. recall = recall_score(Yact, Ypred, labels=[encoded_label], average='macro', zero_division=0)
  143. recall_list.append(recall)
  144. f1 = f1_score(Yact, Ypred, labels=[encoded_label], average='macro', zero_division=0)
  145. f1_list.append(f1)
  146. TPR = TP / (TP + FN) if (TP + FN) != 0 else 0
  147. TPR_list.append(TPR)
  148. TNR = TN / (TN + FP) if (TN + FP) != 0 else 0
  149. TNR_list.append(TNR)
  150. FPR = 1 - TNR
  151. FPR_list.append(FPR)
  152. FNR = 1 - TPR
  153. FNR_list.append(FNR)
  154. classwiseMetrics_df = pd.DataFrame({
  155. 'Class': classLabels,
  156. 'TP':TP_list,
  157. 'TN':TN_list,
  158. 'FP':FP_list,
  159. 'FN':FN_list,
  160. 'Accuracy': accuracy_list,
  161. 'Precision': precision_list,
  162. 'Recall': recall_list,
  163. 'F1-Score': f1_list,
  164. 'TPR': TPR_list,
  165. 'TNR': TNR_list,
  166. 'FPR': FPR_list,
  167. 'FNR': FNR_list})
  168. classwiseMetrics_df.to_excel(savePath + 'classwise_metrics.xlsx', index=False)
  169. # %%
  170. # create confusion matrix
  171. def createConfusionMatrix(Ypred,Yact,classEncoding,savePath):
  172. classLabels = list(classEncoding.keys())
  173. conf_matrix = confusion_matrix(Yact, Ypred)
  174. plt.figure(figsize=(12, 10))
  175. ax = sns.heatmap(conf_matrix, annot=False, fmt='d', cmap='Blues',cbar=True,
  176. linewidths=0.5, linecolor='gray',
  177. xticklabels=classLabels, yticklabels=classLabels)
  178. for i in range(conf_matrix.shape[0]):
  179. for j in range(conf_matrix.shape[1]):
  180. ax.text(j + 0.5, i + 0.5, str(conf_matrix[i, j]), ha="center", va="center",
  181. color="black", fontsize=12)
  182. cbar = ax.collections[0].colorbar
  183. cbar.ax.yaxis.set_major_formatter(plt.ScalarFormatter())
  184. cbar.ax.yaxis.set_tick_params(labelsize=14)
  185. plt.title('Confusion Matrix', fontsize=16)
  186. plt.xlabel('Predicted Label', fontsize=14)
  187. plt.ylabel('True Label', fontsize=14)
  188. plt.xticks(fontsize=12)
  189. plt.yticks(fontsize=12)
  190. plt.savefig(savePath + 'confusion_matrix.png', dpi=1200)
  191. plt.show()
  192. # %%
  193. # pre-process images
  194. def preProcess(input_img):
  195. output_img = cv2.cvtColor(input_img,cv2.COLOR_BGR2RGB)
  196. output_img = output_img.astype(np.float32) / 255.0
  197. return output_img
  198. # %%
  199. # read images and labels
  200. def readData(imageFolderPath,labelFilePath):
  201. images = []
  202. labels = []
  203. labels_df = pd.read_excel(labelFilePath)
  204. for idx, row in labels_df.iterrows():
  205. img_path = os.path.join(imageFolderPath, row['imageID'])
  206. image = cv2.imread(img_path)
  207. image = cv2.resize(image, imgSize)
  208. image = preProcess(image)
  209. images.append(image)
  210. labels.append(row['disease'])
  211. return np.array(images),np.array(labels)
  212. # %%
  213. def getTotalLabels(trainLabels,testLabels,valLabels):
  214. totalLabels = 0
  215. totalTrainLabels = len(set(list(trainLabels)))
  216. totalTestLabels = len(set(list(testLabels)))
  217. totalValLabels = len(set(list(valLabels)))
  218. if (totalTrainLabels == totalTestLabels and totalTrainLabels == totalValLabels):
  219. totalLabels = totalTrainLabels
  220. else:
  221. print('Total Labels Mismatch in Dataset Splits')
  222. return totalLabels
  223. # %%
  224. def oneHotEncoder(trainLabels, testLabels, valLabels,numLabels):
  225. label_encoder = LabelEncoder()
  226. all_labels = np.concatenate([trainLabels, testLabels, valLabels])
  227. label_encoder.fit(all_labels)
  228. trainLabels_encoded = label_encoder.transform(trainLabels)
  229. testLabels_encoded = label_encoder.transform(testLabels)
  230. valLabels_encoded = label_encoder.transform(valLabels)
  231. class_names = label_encoder.classes_
  232. class_to_encoder = {class_name: idx for idx, class_name in enumerate(class_names)}
  233. trainLabels_1Hot = to_categorical(trainLabels_encoded,num_classes=numLabels)
  234. testLabels_1Hot = to_categorical(testLabels_encoded,num_classes=numLabels)
  235. valLabels_1Hot = to_categorical(valLabels_encoded,num_classes=numLabels)
  236. return trainLabels_1Hot, testLabels_1Hot, valLabels_1Hot,class_to_encoder
  237. # %%
  238. # read images and labels
  239. Xtrain, Ytrain = readData(trainImagesPath,trainLabelsPath)
  240. Xtest, Ytest = readData(testImagesPath,testLabelsPath)
  241. Xval, Yval = readData(valImagesPath,valLabelsPath)
  242. totalLabels = getTotalLabels(Ytrain, Ytest, Yval)
  243. Ytrain, Ytest, Yval, class_encoding = oneHotEncoder(Ytrain, Ytest, Yval,totalLabels)
  244. print(Xtrain.shape)
  245. print(Xtest.shape)
  246. print(Xval.shape)
  247. print(class_encoding)
  248. # %%
  249. # comparison model
  250. def compMod1(inputShape,numLabels):
  251. inp = Input(shape = inputShape)
  252. baseModel = NASNetMobile(include_top=False, input_shape=inputShape, weights='imagenet',input_tensor=inp)
  253. baseModel.trainable = False
  254. baseModel_output = baseModel.output
  255. x = GlobalAveragePooling2D()(baseModel_output)
  256. x = Flatten()(x)
  257. x = Dense(1024,activation='relu')(x)
  258. x = Dropout(0.3)(x)
  259. output = Dense(numLabels,activation='softmax')(x)
  260. model = Model(inp,output,name='compMod1')
  261. opt = Adam(learning_rate=0.001)
  262. model.compile(optimizer = opt,loss='categorical_crossentropy',metrics=['accuracy'])
  263. return model
  264. # %%
  265. # reference model
  266. def ltftnet(inputShape,numLabels):
  267. inp = Input(shape = inputShape)
  268. baseModel = NASNetMobile(include_top=False, input_shape=inputShape, weights='imagenet',input_tensor=inp)
  269. baseModel.trainable = False
  270. baseModel_output = baseModel.get_layer('normal_concat_12').output
  271. x = Conv2D(512,(1,1),activation='relu')(baseModel_output)
  272. x = GlobalAveragePooling2D()(x)
  273. x = BatchNormalization(name='head-batchnorm-1')(x)
  274. x = Dense(512, activation='relu',name='head-dense-2')(x)
  275. x = Dropout(0.3,name='head-dropout-1')(x)
  276. x = Dense(256, activation='relu',name='head-dense-4')(x)
  277. output = Dense(numLabels, activation='softmax',name='class')(x)
  278. model = Model(inp,output,name='usmanrafi')
  279. opt = Adam(learning_rate=1e-4)
  280. model.compile(optimizer = opt,loss='categorical_crossentropy',metrics=['accuracy'])
  281. return model
  282. # %%
  283. # comparison model
  284. def compMod2(inputShape,numLabels):
  285. inp = Input(shape = inputShape)
  286. x = Conv2D(32,(3,3),activation='relu',strides=1)(inp)
  287. x = MaxPooling2D((2,2))(x)
  288. x = Conv2D(64,(3,3),activation='relu',strides=1)(x)
  289. x = MaxPooling2D((2,2))(x)
  290. x = Conv2D(128,(3,3),activation='relu',strides=1)(x)
  291. x = MaxPooling2D((2,2))(x)
  292. x = Conv2D(256,(3,3),activation='relu',strides=1)(x)
  293. x = MaxPooling2D((2,2))(x)
  294. x = Flatten()(x)
  295. x = Dropout(0.4)(x)
  296. output = Dense(numLabels, activation='softmax',name='class')(x)
  297. model = Model(inp,output,name='compMod2')
  298. opt = Adam(learning_rate=0.001)
  299. model.compile(optimizer = opt,loss='categorical_crossentropy',metrics=['accuracy'])
  300. return model
  301. # %%
  302. # comparison model
  303. def compMod3(inputShape,numLabels):
  304. inp = Input(shape=inputShape)
  305. baseModel1 = DenseNet121(include_top=False, input_shape=inputShape, weights='imagenet',input_tensor=inp)
  306. baseModel1.trainable = False
  307. baseModel1_output = baseModel1.output
  308. baseModel2 = EfficientNetB5(include_top=False, input_shape=inputShape, weights='imagenet',input_tensor=inp)
  309. baseModel2.trainable = False
  310. baseModel2_output = baseModel2.output
  311. f = Concatenate()([baseModel1_output,baseModel2_output])
  312. gap = GlobalAveragePooling2D()(f)
  313. gmp = GlobalMaxPooling2D()(f)
  314. x = Add()([gap,gmp])
  315. x = Flatten()(x)
  316. x = BatchNormalization()(x)
  317. x = Dropout(0.25)(x)
  318. x = Dense(512,activation='relu')(x)
  319. x = BatchNormalization()(x)
  320. x = Dropout(0.25)(x)
  321. output = Dense(numLabels,activation='softmax')(x)
  322. model = Model(inp,output,name='compMod3')
  323. opt = Adam(learning_rate=0.001)
  324. model.compile(optimizer=opt,loss='categorical_crossentropy',metrics=['accuracy'])
  325. return model
  326. # %%
  327. # comparison model
  328. def transBlock(x):
  329. x = SeparableConv2D(64, (1, 1), padding='same')(x)
  330. x = BatchNormalization()(x)
  331. x = ReLU()(x)
  332. x = SeparableConv2D(128, (3, 3), padding='same')(x)
  333. x = BatchNormalization()(x)
  334. x = ReLU()(x)
  335. x = SeparableConv2D(256, (1, 1), padding='same')(x)
  336. x = BatchNormalization()(x)
  337. x = ReLU()(x)
  338. x = Conv2DTranspose(256, (3, 3), strides=(2, 2), padding='same')(x)
  339. x = MaxPooling2D((2, 2))(x)
  340. return x
  341. def addLayer(x):
  342. x = SeparableConv2D(256, (1, 1), padding='same')(x)
  343. x = BatchNormalization()(x)
  344. return x
  345. def compMod4(inputShape, numLabels):
  346. inp = Input(shape=inputShape)
  347. vgg_input = Input(shape=inputShape)
  348. vgg_base = VGG16(include_top=False, input_tensor=vgg_input, weights='imagenet')
  349. vgg_base.trainable = False
  350. leftOut = vgg_base.output
  351. leftOut_TransBlock = transBlock(leftOut)
  352. leftOut_Addl = addLayer(leftOut)
  353. leftF = Add()([leftOut_TransBlock, leftOut_Addl])
  354. vgg_model = Model(vgg_input, leftF)
  355. xcep_input = Input(shape=inputShape)
  356. xcep_base = Xception(include_top=False, input_tensor=xcep_input, weights='imagenet')
  357. xcep_base.trainable = False
  358. rightOut = xcep_base.output
  359. rightOut_TransBlock = transBlock(rightOut)
  360. rightOut_Addl = addLayer(rightOut)
  361. rightF = Add()([rightOut_TransBlock, rightOut_Addl])
  362. xcep_model = Model(xcep_input, rightF)
  363. leftF_out = vgg_model(inp)
  364. rightF_out = xcep_model(inp)
  365. f = Add()([leftF_out, rightF_out])
  366. x = Flatten()(f)
  367. x = Dense(256)(x)
  368. x = Dropout(0.2)(x)
  369. x = Dense(128)(x)
  370. x = Dropout(0.3)(x)
  371. x = Dense(64)(x)
  372. output = Dense(numLabels, activation='softmax')(x)
  373. model = Model(inp, output,name='compMod4')
  374. opt = Adam(learning_rate=0.001)
  375. model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])
  376. return model
  377. # %%
  378. # Fine-tuned transfer learning model
  379. def ftmod1(inputShape,numLabels):
  380. inp = Input(shape=inputShape)
  381. baseModel = NASNetMobile(include_top=True, input_shape=inputShape, weights='imagenet',input_tensor=inp)
  382. baseModel.trainable = False
  383. baseModel_secondLastLayer = baseModel.layers[-2].output
  384. output = Dense(numLabels,activation='softmax')(baseModel_secondLastLayer)
  385. model = Model(inp,output,name='ftmod1')
  386. opt = Adam(0.001)
  387. model.compile(optimizer=opt,loss='categorical_crossentropy',metrics=['accuracy'])
  388. return model
  389. # %%
  390. # Fine-tuned transfer learning model
  391. def ftmod2(inputShape,numLabels):
  392. inp = Input(shape=inputShape)
  393. baseModel = MobileNet(include_top=True, input_shape=inputShape, weights='imagenet',input_tensor=inp)
  394. baseModel.trainable = False
  395. baseModel_secondLastLayer = baseModel.layers[-2].output
  396. output = Dense(numLabels,activation='softmax')(baseModel_secondLastLayer)
  397. model = Model(inp,output,name='ftmod2')
  398. opt = Adam(0.001)
  399. model.compile(optimizer=opt,loss='categorical_crossentropy',metrics=['accuracy'])
  400. return model
  401. # %%
  402. # Fine-tuned transfer learning model
  403. def ftmod3(inputShape,numLabels):
  404. inp = Input(shape=inputShape)
  405. baseModel = MobileNetV2(include_top=True, input_shape=inputShape, weights='imagenet',input_tensor=inp)
  406. baseModel.trainable = False
  407. baseModel_secondLastLayer = baseModel.layers[-2].output
  408. output = Dense(numLabels,activation='softmax')(baseModel_secondLastLayer)
  409. model = Model(inp,output,name='ftmod3')
  410. opt = Adam(0.001)
  411. model.compile(optimizer=opt,loss='categorical_crossentropy',metrics=['accuracy'])
  412. return model
  413. # %%
  414. # Fine-tuned transfer learning model
  415. def ftmod4(inputShape,numLabels):
  416. inp = Input(shape=inputShape)
  417. baseModel = DenseNet121(include_top=True, input_shape=inputShape, weights='imagenet',input_tensor=inp)
  418. baseModel.trainable = False
  419. baseModel_secondLastLayer = baseModel.layers[-2].output
  420. output = Dense(numLabels,activation='softmax')(baseModel_secondLastLayer)
  421. model = Model(inp,output,name='ftmod4')
  422. opt = Adam(0.001)
  423. model.compile(optimizer=opt,loss='categorical_crossentropy',metrics=['accuracy'])
  424. return model
  425. # %%
  426. # Fine-tuned transfer learning model
  427. def ftmod5(inputShape,numLabels):
  428. inp = Input(shape=inputShape)
  429. baseModel = EfficientNetB0(include_top=True, input_shape=inputShape, weights='imagenet',input_tensor=inp)
  430. baseModel.trainable = False
  431. #baseModel_secondLastLayer = baseModel.layers[-2].output
  432. baseModel_secondLastLayer = baseModel.get_layer('top_dropout').output
  433. output = Dense(numLabels,activation='softmax')(baseModel_secondLastLayer)
  434. model = Model(inp,output,name='ftmod5')
  435. opt = Adam(0.001)
  436. model.compile(optimizer=opt,loss='categorical_crossentropy',metrics=['accuracy'])
  437. return model
  438. # %%
  439. # Fine-tuned transfer learning model
  440. def ftmod6(inputShape,numLabels):
  441. inp = Input(shape=inputShape)
  442. baseModel = EfficientNetV2B0(include_top=True, input_shape=inputShape, weights='imagenet',input_tensor=inp)
  443. baseModel.trainable = False
  444. #baseModel_secondLastLayer = baseModel.layers[-2].output
  445. baseModel_secondLastLayer = baseModel.get_layer('top_dropout').output
  446. output = Dense(numLabels,activation='softmax')(baseModel_secondLastLayer)
  447. model = Model(inp,output,name='ftmod6')
  448. opt = Adam(0.001)
  449. model.compile(optimizer=opt,loss='categorical_crossentropy',metrics=['accuracy'])
  450. return model
  451. # %%
  452. # comparison model
  453. def compMod5(inputShape,numLabels):
  454. inp = Input(shape=inputShape)
  455. baseModel = NASNetMobile(include_top=False, input_shape=inputShape, weights='imagenet',input_tensor=inp)
  456. baseModel.trainable = False
  457. baseModel_output = baseModel.output
  458. x = GlobalAveragePooling2D()(baseModel_output)
  459. output = Dense(numLabels,activation='softmax')(x)
  460. model = Model(inp,output,name="compMod5")
  461. opt = Adam(learning_rate=0.001)
  462. model.compile(optimizer=opt,loss='categorical_crossentropy',metrics=['accuracy'])
  463. return model
  464. # %%
  465. # comparison model
  466. def compMod6(inputShape,numLabels):
  467. inp = Input(shape=inputShape)
  468. baseModel = NASNetMobile(include_top=False, input_shape=inputShape, weights='imagenet',input_tensor=inp)
  469. baseModel.trainable = False
  470. baseModel_output = baseModel.output
  471. x = Flatten()(baseModel_output)
  472. x = Dense(256,activation='relu')(x)
  473. x = Dropout(0.35)(x)
  474. x = Dense(128,activation='relu')(x)
  475. x = Dropout(0.35)(x)
  476. output = Dense(numLabels,activation='softmax')(x)
  477. model = Model(inp,output,name="compMod6")
  478. opt = Adam(learning_rate=0.001)
  479. model.compile(optimizer=opt,loss='categorical_crossentropy',metrics=['accuracy'])
  480. return model
  481. # %%
  482. # Get Model for training
  483. myModel = ltftnet((Xtrain[0].shape),totalLabels)
  484. printModelSummary(myModel)
  485. # %%
  486. # image augmentation
  487. train_datagen = ImageDataGenerator(
  488. rotation_range=30,
  489. width_shift_range=0.2,
  490. height_shift_range=0.2,
  491. shear_range=0.2,
  492. zoom_range=0.2,
  493. horizontal_flip=True,
  494. fill_mode='nearest'
  495. )
  496. train_generator = train_datagen.flow(
  497. Xtrain,
  498. Ytrain,
  499. batch_size=batchSize
  500. )
  501. # %%
  502. # LR Scheduler
  503. reduce_lr = tf.keras.callbacks.ReduceLROnPlateau(
  504. monitor='val_accuracy',
  505. factor=0.5,
  506. patience=3,
  507. verbose=1,
  508. min_lr=1e-7
  509. )
  510. # training loop
  511. trainingTime = 0
  512. numEpochs = 30
  513. start = time.time()
  514. history = myModel.fit(train_generator,steps_per_epoch=len(train_generator),epochs=numEpochs,validation_data=(Xval,Yval),shuffle=True,verbose=1,callbacks=[reduce_lr])
  515. end = time.time()
  516. trainingTime = end - start
  517. # %%
  518. # Loading models with saved weights and biases for generalizability
  519. modelPath = 'path/modName.h5'
  520. myModel = load_model(modelPath)
  521. print(myModel.summary())
  522. # %%
  523. # Warmup model
  524. dummy_input = np.random.rand(1, 224, 224, 3).astype(np.float32)
  525. _ = myModel.predict(dummy_input, batch_size=1)
  526. # test
  527. testingTime = 0
  528. start = time.time()
  529. Ypred = myModel.predict(Xtest)
  530. end = time.time()
  531. testingTime = end - start
  532. Ypred = np.argmax(Ypred, axis=1)
  533. Yact = np.argmax(Ytest, axis=1)
  534. # %%
  535. # Print total number of actual labels and model's predicted labels
  536. print(len(Ypred))
  537. print(len(Yact))
  538. # %%
  539. # results
  540. saveTime(trainingTime,testingTime,outPath)
  541. saveModelRunHistory(history,outPath)
  542. saveModel(myModel,outPath,'modelName')
  543. # %%
  544. # results
  545. plotAccuracy(history,outPath)
  546. plotLoss(history,outPath)
  547. # %%
  548. # results
  549. testMetricsOverall(Ypred,Yact,outPath)
  550. testMetricsClassWise(Ypred,Yact,class_encoding,outPath)
  551. createConfusionMatrix(Ypred,Yact,class_encoding,outPath)

kerasMods.ipynb at commit de72ecc, under MIT · at the source

Overview

Authors: Usman Rafi1, Qamar Nawaz1, Muhammad Ahsan Latif1, Aisha Khatoon2
ORCID iDs: Usman Rafi
  1. Department of Computer Science, Faculty of Sciences, University of Agriculture, Faisalabad, Punjab, Pakistan
  2. Department of Pathology, Faculty of Veterinary Science, University of Agriculture, Faisalabad, Punjab, Pakistan
Institutions: University of Agriculture Faisalabad (Pakistan)
Journal: PloS one, volume 21, issue 5, article e0347867
Dates: received 20 August 2025; accepted 8 April 2026; published online 11 May 2026
Type: Research article · Language: English
License: CC BY
Identifiers: DOI 10.1371/journal.pone.0347867 · PMID 42113782 · PMCID PMC13160359 · OpenAlex W7160855737
Open access: gold, a free copy (OpenAlex)
Status: code verified
Categories: other (modality), human (organism), methods / tools (subfield)
Methods: Machine learning
MeSH: Deep Learning*, Fundus Oculi*, Image Processing, Computer-Assisted*, Retinal Diseases*, Algorithms, Convolutional Neural Networks, Humans (* major topic)
Topic: Retinal Imaging and Analysis (Radiology, Nuclear Medicine and Imaging, Medicine), according to OpenAlex
Citations: not cited yet (Europe PMC); 66 references in the paper

Abstract

Convolutional Neural Networks (CNNs) require a larger amount of input samples and computing resources to learn discriminative features for accurate identification of multiple retinal conditions, making the development and deployment of such models challenging on limited computing resources. This study presents a robust CNN (called LiteFeatNet) that requires fewer trainable parameters, computational resources, and processing time for accurate prediction. To enhance robustness and reduce computational time, a pre-trained NASNetMobile backbone is employed, and a method for time-efficient discriminative feature extraction from deep intermediate layers is proposed. The extracted features are refined using a spatially-aware feature map reduction module and classified using a custom classification module with fewer number of trainable parameters, reduced computational resource requirements, and computational time. Experiments are conducted using 1824 images from three distinct class labels in the Retinal Fundus Multi-Disease Image Dataset (RFMiD), with a 60:20:20 train-validation-test split. The LiteFeatNet architecture has a compact size (19.87 MB) and was trained using a standard pre-processing pipeline and training configurations. It outperformed twelve state-of-the-art models, achieving the highest testing accuracy of 90.33%, precision of 90.69%, recall of 90.33%, and F1-score of 90.27%, with a fast, impressive inference time of 4 milliseconds per image. Further, a generalizability study was also conducted using an external dataset, RFMiD 2.0, and the LiteFeatNet achieved competitive performance with quicker testing time compared to other architectures. To evaluate the scalability and adaptability of our proposed integrated framework for larger multi-class problems, we assessed the scalability by increasing class label complexity using two additional disease categories. Results validated the effectiveness and computational efficiency of this integrated framework compared with 9 baseline architectures. An ablation study was also conducted using the LiteFeatNet and two top-performing transfer learning architectures to validate that the synergistic combination of deep feature extraction and feature map refinement is the primary design decision behind the success of the LiteFeatNet architecture. The evaluation metrics, thus obtained, strongly suggest that the proposed LiteFeatNet is lightweight, fast, and robust, rendering it suitable for deployment in low-resource clinical settings.

Reproduced under the paper's license (CC BY), from the paper cited above.

Repository

Its files are read in the Code ↔ Paper reader above, with 3 matches between paragraphs and lines of code.

usmanrafics/LTFTNET

License: MIT
State: the link answers, verified on 28 September 2026
Evidence: files inventoried
Commit: de72ecc81c4be3bb15f7468cfb0d50aa766d7999, 10 August 2026
Languages: Jupyter (3)
Size: 5 files, 3 scripts
Software Heritage: not archived
Found in: “Data Availability”
Holds: README, license file, 3 notebooks
Not found: CITATION.cff, environment file, tests, continuous integration, documentation
Tools: Matplotlib (3 files), NumPy (3 files), OpenCV (3 files), pandas (3 files), scikit-learn (3 files), seaborn (3 files), Keras (2 files), TensorFlow (2 files), Pillow (1 file), PyTorch (1 file)
Availability: 1 check, the latest on 28 September 2026: the link answers
  • 28 September 2026: the link answers
5 files

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:

  • 1 repository 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;
  • 3 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

Datasets cited

Data Availability

All three datasets can be found at the following recommended repositories. Dataset1 - RFMiD 1: https://www.kaggle.com/datasets/andrewmvd/retinal-disease-classification Dataset2 - RFMiD 2.0: https://zenodo.org/records/7505822 Dataset3 - Eye Disease Dataset https://www.kaggle.com/datasets/linabennaa/eye-disease-image-dataset-mendeley The code developed for this study is made publicly available on GitHub. The code can be accessed at the following URL: https://github.com/usmanrafics/LTFTNET.

Reproduced under the paper's license (CC BY), from the paper cited above.

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, 28 September 2026: the first record

Recorded: type, language, journal, volume, issue, pages, dates, 4 authors, 7 MeSH terms, 47 references.

Cite

This paper

Rafi, U., Nawaz, Q., Latif, M. A., & Khatoon, A. (2026). LiteFeatNet: A parameter-efficient and performance-centric deep learning model for multi-ocular disease identification using intermediate feature reduction from fundus images. PloS one, 21(5), e0347867. https://doi.org/10.1371/journal.pone.0347867

BibTeX

@article{rafi2026litefeatnet,
author = {Rafi, Usman and Nawaz, Qamar and Latif, Muhammad Ahsan and Khatoon, Aisha},
title = {{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},
year = {2026},
month = may,
volume = {21},
number = {5},
pages = {e0347867},
publisher = {PLOS},
issn = {1932-6203},
doi = {10.1371/journal.pone.0347867},
url = {https://doi.org/10.1371/journal.pone.0347867},
pmid = {42113782},
pmcid = {PMC13160359}
}

RIS

TY - JOUR
AU - Rafi, Usman
AU - Nawaz, Qamar
AU - Latif, Muhammad Ahsan
AU - Khatoon, Aisha
TI - LiteFeatNet: A parameter-efficient and performance-centric deep learning model for multi-ocular disease identification using intermediate feature reduction from fundus images
T2 - PloS one
J2 - PLoS One
PY - 2026
DA - 2026/05/11
VL - 21
IS - 5
SP - e0347867
SN - 1932-6203
PB - PLOS
DO - 10.1371/journal.pone.0347867
UR - https://doi.org/10.1371/journal.pone.0347867
LA - en
ER -

CSL-JSON

{
"id": "10.1371/journal.pone.0347867",
"type": "article-journal",
"title": "LiteFeatNet: A parameter-efficient and performance-centric deep learning model for multi-ocular disease identification using intermediate feature reduction from fundus images",
"container-title": "PloS one",
"author": [
{
"family": "Rafi",
"given": "Usman"
},
{
"family": "Nawaz",
"given": "Qamar"
},
{
"family": "Latif",
"given": "Muhammad Ahsan"
},
{
"family": "Khatoon",
"given": "Aisha"
}
],
"container-title-short": "PLoS One",
"volume": "21",
"issue": "5",
"page": "e0347867",
"DOI": "10.1371/journal.pone.0347867",
"PMID": "42113782",
"PMCID": "PMC13160359",
"ISSN": "1932-6203",
"publisher": "PLOS",
"URL": "https://doi.org/10.1371/journal.pone.0347867",
"language": "en",
"issued": {
"date-parts": [
[
2026,
5,
11
]
]
}
}

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.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, 7 other tools, methods / tools
[2] 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, 6 other tools, other, methods / tools
[3] doi:10.1038/s42003-026-10957-8 [code]
Brain defence by the extracellular matrix protein Cochlin.
Journal: Communications biology
In common: Keras, TensorFlow, OpenCV, 7 other tools
[4] 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, 7 other tools
[5] doi:10.1364/boe.605322 [code]
Generalized plaque digitization framework for multi-dimensional mesoscopic images.
Journal: Biomedical optics express
In common: Keras, TensorFlow, OpenCV, 7 other tools
[6] doi:10.1038/s41467-026-72057-9 [code]
Sex-specific behavioral feedback modulates sensorimotor processing and drives flexible social behavior.
Journal: Nature communications
In common: Keras, TensorFlow, OpenCV, 7 other tools
[7] doi:10.1038/s41598-026-48475-6 [code]
Optimized U-net model for precise retinal blood vessel segmentation from colour fundus images.
Journal: Scientific reports
In common: Keras, TensorFlow, OpenCV, 5 other tools, other, methods / tools
[8] doi:10.1038/s41592-026-03057-2 [code]
CREsted: modeling genomic and synthetic cell-type-specific enhancers across tissues and species.
Journal: Nature methods
In common: Keras, TensorFlow, Pillow, 6 other tools, methods / 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, 6 other tools
[10] doi:10.1093/jnen/nlaf152 [code]
Clinical and pathologic correlations of machine learning quantification of Aβ deposits across 3 brain regions of decedents with Alzheimer disease.
Journal: Journal of neuropathology and experimental neurology
In common: Keras, TensorFlow, OpenCV, 6 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.