Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

train_active_learning.py 29 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
  1. import keras
  2. import tensorflow as tf
  3. from tensorflow.keras.preprocessing.image import random_rotation,random_shift,random_brightness
  4. from tensorflow.keras import layers
  5. from tensorflow.keras.models import Model
  6. from tensorflow.keras.models import Sequential
  7. from tensorflow.keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense, GlobalMaxPooling2D,Dropout,GlobalAveragePooling2D, BatchNormalization
  8. from tensorflow.keras.callbacks import LearningRateScheduler, EarlyStopping, Callback
  9. from tensorflow.keras.models import Sequential, load_model
  10. from tensorflow.keras.callbacks import ModelCheckpoint
  11. from tensorflow.keras.optimizers import Adam
  12. from sklearn.metrics import confusion_matrix, classification_report,precision_score,recall_score,accuracy_score
  13. import cv2 as cv
  14. from dagshub.streaming import DagsHubFilesystem
  15. import mlflow
  16. from dagshub_config import *
  17. from config import *
  18. import json
  19. import numpy as np
  20. import pandas as pd
  21. import os
  22. import sys
  23. import git
  24. import pathlib
  25. import math
  26. import random
  27. from scipy.stats import entropy
  28. random.seed(20)
  29. from operator import itemgetter
  30. from dagshub.upload import Repo
  31. import argparse
  32. INITIAL_TRAINING_SAMPLES=400
  33. NUM_SAMPLES_LABELLED_PER_ITERATION=100
  34. MAX_SAMPLES_LABELLED=6000
  35. POOL_SIZE=4000
  36. mlflow.set_tracking_uri(MLFLOW_TRACKING_URI)
  37. os.environ['MLFLOW_TRACKING_URI']=MLFLOW_TRACKING_URI
  38. os.environ["MLFLOW_TRACKING_USERNAME"] = MLFLOW_TRACKING_USERNAME
  39. os.environ["MLFLOW_TRACKING_PASSWORD"] = MLFLOW_TRACKING_PASSWORD
  40. print(mlflow.get_tracking_uri())
  41. def create_train_data_frame(train_ok_data_path,train_defect_data_path):
  42. fs=create_streaming_client()
  43. train_data=pd.DataFrame()
  44. ok_images=fs.listdir(train_ok_data_path)
  45. defect_images=fs.listdir(train_defect_data_path)
  46. images_path=ok_images+defect_images
  47. train_data['file_name']=images_path
  48. train_data['labelled']=False
  49. return train_data
  50. def label_image(file_name,is_to_be_labelled):
  51. if is_to_be_labelled==True:
  52. if "ok" in file_name:
  53. return "ok"
  54. else:
  55. return "defect"
  56. return ""
  57. def predict(classifier,image):
  58. image_dim=image.shape
  59. #print(image_dim)
  60. X = np.empty((1,*image_dim))
  61. X[0,]=image
  62. #print(X.shape)
  63. return classifier.predict(X)[0]
  64. def generate_clean_images(folder_path,image_dim,n_channels):
  65. '''
  66. This function reads the images in the folder_path and cleans them
  67. The output is the file_path and the cleaned numpy array of the image
  68. '''
  69. fs=create_streaming_client()
  70. files=fs.listdir(folder_path)
  71. file_paths=[os.path.join(folder_path,__file__) for __file__ in files]
  72. images={file_path:clean_image(fs,file_path,image_dim,n_channels) for file_path in file_paths}
  73. return images
  74. def predict_test_data(unlabelled_images,cleaned_images,classifier):
  75. predicted_probability={file_path:predict(classifier,image_array) for file_path,image_array in cleaned_images.items() if os.path.basename(file_path) in unlabelled_images}
  76. print("Predicted Prob Dictionary Length ",len(predicted_probability))
  77. return predicted_probability
  78. def random_query_strategy(unlabelled_images,query_size):
  79. '''
  80. In random strategy, we will pick random samples from the unlabelled data and label them.
  81. We will then add this to the pool of training data and retrain the model
  82. '''
  83. images_to_label=random.sample(unlabelled_images,query_size)
  84. return images_to_label
  85. def entropy_query_strategy(unlabelled_images,query_size,classifier,cleaned_images=None):
  86. '''
  87. This function,gets the predicted probability of unlabelled images and returns the images with the highest entropy for training
  88. '''
  89. image_pred_prob=predict_test_data(unlabelled_images,cleaned_images,classifier)
  90. #print(image_pred_prob)
  91. image_pred_entropy={os.path.basename(file_path):entropy([prob,1-prob]) for file_path,prob in image_pred_prob.items()}
  92. #print(image_pred_entropy)
  93. ### Get the top N images with the highest entropy
  94. top_entropy = dict(sorted(image_pred_entropy.items(), key = itemgetter(1), reverse = True)[:query_size])
  95. print("Images to Label ",top_entropy.keys())
  96. return list(top_entropy.keys())
  97. def create_streaming_client():
  98. fs = DagsHubFilesystem(project_root=DAGSHUB_REPO_NAME,username=DAGSHUB_USERNAME,password=DAGSHUB_TOKEN)
  99. return fs
  100. def convert_to_grayscale(image):
  101. converted=tf.image.hsv_to_rgb(image)
  102. converted=tf.image.rgb_to_grayscale(converted)
  103. return converted
  104. def read_images_streaming(fs,img_path):
  105. fs.open(img_path) ## This does smart caching
  106. return cv.imread(img_path)
  107. def get_experiment_id(name):
  108. exp = mlflow.get_experiment_by_name(name)
  109. if exp is None:
  110. exp_id = mlflow.create_experiment(name)
  111. return exp_id
  112. return exp.experiment_id
  113. '''
  114. This data generator reads the data from a given path and generates batches of data. This is the generator used for Generating Batches of Test Data
  115. '''
  116. class DataGenerator(keras.utils.Sequence):
  117. 'Generates data for Keras'
  118. def __init__(self,data_directory,mode='train', image_cls={'ok_front':0,'def_front':1},
  119. batch_size=32, dim=(150, 150), n_channels=3, shuffle=True,train_test_split=0.8,
  120. rotation_range=None, width_shift_range=None, height_shift_range=None,horizontal_flip=False,brightness_range=None):
  121. """
  122. Initialise the data generator
  123. """
  124. self.dim = dim
  125. self.batch_size = batch_size
  126. self.labels = {}
  127. self.list_IDs = []
  128. self.rotation_range=rotation_range
  129. self.horizontal_flip=horizontal_flip
  130. self.brightness_range=brightness_range
  131. self.height_shift_range=height_shift_range
  132. self.width_shift_range=width_shift_range
  133. self.fs=create_streaming_client()
  134. # glob through directory of each class
  135. label_class=[key for key,val in image_cls.items()]
  136. for i, class_name in enumerate(label_class):
  137. ### Get the number of images in both classes and split the data into training and validation
  138. num_images=len(self.fs.listdir(os.path.join(data_directory,class_name+"/")))
  139. print("number of images in "+class_name+" is "+str(num_images))
  140. #paths = glob.glob(os.path.join(TRAIN_DATASET_PATH, cls, '*'))
  141. brk_point = int(num_images*train_test_split) #Divide the data into 80:20 - training and validation set
  142. file_paths=self.fs.listdir(os.path.join(data_directory,class_name+"/"))
  143. folder_path=os.path.join(data_directory,class_name+"/")
  144. if mode in ['train',"test"]:
  145. file_paths = file_paths[:brk_point]
  146. else:
  147. file_paths = file_paths[brk_point:]
  148. file_paths=[os.path.join(folder_path,file_path) for file_path in file_paths]
  149. self.list_IDs += file_paths
  150. self.labels.update({p:image_cls[class_name] for p in file_paths})
  151. print("Number of Files For "+mode+"for class "+class_name+" is "+str(len(file_paths)))
  152. self.n_channels = n_channels
  153. self.n_classes = len(label_class)
  154. self.sample_size=len(self.list_IDs)
  155. self.shuffle = shuffle
  156. self.on_epoch_end()
  157. self.on_epoch_end()
  158. def __len__(self):
  159. 'Denotes the number of batches per epoch'
  160. return int(np.floor(len(self.list_IDs) / self.batch_size))
  161. def __getitem__(self, index):
  162. 'Generate one batch of data'
  163. # Generate indexes of the batch
  164. indexes = self.indexes[index*self.batch_size:(index+1)*self.batch_size]
  165. # Find list of IDs
  166. #list_IDs_temp = [self.list_IDs[k] for k in indexes]
  167. # Generate data
  168. X, y = self.__data_generation(indexes)
  169. return X, y
  170. def on_epoch_end(self):
  171. 'Updates indexes after each epoch. If shuffle is true, this will shuffle the dataset'
  172. print("In On_EPOCH_END")
  173. self.indexes = np.arange(len(self.list_IDs))
  174. if self.shuffle == True:
  175. np.random.shuffle(self.indexes)
  176. def __data_generation(self, indexes):
  177. 'Generates data containing batch_size samples' # X : (n_samples, *dim, n_channels)
  178. # Initialization
  179. X = np.empty((self.batch_size, *self.dim, self.n_channels))
  180. y = np.empty((self.batch_size), dtype=int)
  181. ### Generate data based on the indexes.
  182. for i,idx in enumerate(indexes):
  183. img_path=self.list_IDs[idx]
  184. ### Read the Images using Streaming Client
  185. img=read_images_streaming(self.fs,img_path)
  186. img=img/255
  187. img=cv.resize(img,self.dim)
  188. ### Convert the image to grayscale
  189. if self.n_channels==1:
  190. img=convert_to_grayscale(img)
  191. ### Apply other transformation whenever required
  192. if self.rotation_range!=None:
  193. img=random_rotation(img,self.rotation_range)
  194. if self.width_shift_range!=None:
  195. img=random_shift(img,wrg=self.width_shift_range,hrg=0)
  196. if self.height_shift_range!=None:
  197. img=random_shift(img,hrg=self.height_shift_range,wrg=0)
  198. if self.brightness_range!=None:
  199. img=random_brightness(img,brightness_range=self.brightness_range)
  200. if self.horizontal_flip==True:
  201. img=cv.flip(img, 1)
  202. X[i,]=img
  203. ### Store the labels
  204. y[i]=self.labels[img_path]
  205. return X,y
  206. def create_model(img_size):
  207. cnn_model = Sequential([
  208. # First block
  209. Conv2D(32, 3, activation='relu', padding='same', strides=2,
  210. input_shape=img_size),
  211. MaxPooling2D(pool_size=2, strides=2),
  212. # Second block
  213. Conv2D(64, 3, activation='relu', padding='same', strides=2),
  214. MaxPooling2D(pool_size=2, strides=2),
  215. # Flatenning
  216. Flatten(),
  217. # Fully connected layers
  218. Dense(128, activation='relu'),
  219. Dense(1, activation='sigmoid') # Only 1 output
  220. ])
  221. cnn_model.compile(
  222. optimizer=Adam(learning_rate=0.001), # Default lr
  223. loss='binary_crossentropy',
  224. metrics=['accuracy',tf.keras.metrics.Precision(name='precision'), tf.keras.metrics.Recall(name='recall')])
  225. return cnn_model
  226. def get_experiment_id(name):
  227. exp = mlflow.get_experiment_by_name(name)
  228. if exp is None:
  229. exp_id = mlflow.create_experiment(name)
  230. return exp_id
  231. return exp.experiment_id
  232. def train_model(experiment_name,train_data_gen,test_data_gen,input_image_dim,epochs=20):
  233. #mlflow.create_experiment(RUN_NAME)
  234. tf.keras.backend.clear_session()
  235. experiment_id=get_experiment_id(experiment_name)
  236. mlflow.tensorflow.autolog()
  237. with mlflow.start_run(experiment_id=experiment_id) as run:
  238. print("Run ID ",run.info.run_id)
  239. cnn_model=create_model(input_image_dim)
  240. # Display summary of model architecture
  241. cnn_model.summary()
  242. num_training_samples=train_data_gen.sample_size
  243. #num_validation_samples=validation_data_gen.sample_size
  244. mlflow.log_param("training_sample_size", num_training_samples)
  245. #mlflow.log_param("validation_sample_size",num_validation_samples)
  246. n_epochs = epochs
  247. early_stopping=EarlyStopping(monitor='loss', patience=4,restore_best_weights=True)
  248. history=cnn_model.fit(
  249. train_data_gen,
  250. epochs=n_epochs,
  251. verbose=1,callbacks=[early_stopping])
  252. y_pred_prob = cnn_model.predict(test_data_gen, verbose=1)
  253. y_pred = (y_pred_prob >= 0.5).reshape(-1,)
  254. y_true = list(test_data_gen.labels.values())
  255. test_metrics={'precision_score':precision_score(y_true,y_pred),"recall_score":recall_score(y_true,y_pred),"accuracy_score":accuracy_score(y_true,y_pred)}
  256. mlflow.log_metric("test_precision",test_metrics['precision_score'])
  257. mlflow.log_metric("test_recall",test_metrics['recall_score'])
  258. mlflow.log_metric("test_accuracy",test_metrics['accuracy_score'])
  259. mlflow.log_param("test_sample_size",test_data_gen.sample_size)
  260. mlflow.end_run()
  261. run_id=run.info.run_id
  262. return cnn_model,run_id,history,test_metrics
  263. def building_model(query_data,experiment_name,batch_size=16,n_channels=1,train_test_split=1,dim=(300,300),n_epochs=20):
  264. train_data_generator=ActiveLearningDataGenerator(query_data,data_directory=TRAIN_DATA_PATH,mode="train",batch_size=batch_size,n_channels=n_channels,train_test_split=train_test_split,dim=dim,shuffle=True)
  265. #validation_data_generator=ActiveLearningDataGenerator(query_data,data_directory=TRAIN_DATA_PATH,mode="validation",batch_size=batch_size,n_channels=n_channels,train_test_split=train_test_split,dim=dim,shuffle=True)
  266. img_size=dim+(n_channels,)
  267. print("Image Size",img_size)
  268. test_data_generator=DataGenerator(data_directory=TEST_DATA_PATH,mode="test",batch_size=1,n_channels=1,train_test_split=1,dim=(300,300),shuffle=False)
  269. cnn_model,run_id,history,test_metrics=train_model(experiment_name,train_data_generator,test_data_generator,img_size,epochs=n_epochs)
  270. return cnn_model,run_id,history,test_metrics
  271. ITERATION_COUNT = 0
  272. CLEANED_IMAGES_ARRAY=None
  273. def query_the_oracle(data,initial_pool_size=INITIAL_TRAINING_SAMPLES,query_size=NUM_SAMPLES_LABELLED_PER_ITERATION,folder_paths=None,query_strategy="random",classifier_model=None,image_dim=(300,300),n_channels=1,use_cleaned_array=False):
  274. '''
  275. This method will extract data points for the oracle or the human to label.
  276. '''
  277. global ITERATION_COUNT
  278. global CLEANED_IMAGES_ARRAY
  279. unlabelled_data=data[data['labelled']==False]
  280. unlabelled_images=unlabelled_data['file_name'].tolist()
  281. #labelled_data=data[data['labelled']==True]
  282. #num_samples_unlabelled=unlabelled_data.shape[0]
  283. if data[data['labelled']==True].shape[0]==0:
  284. ### If this is the first round of iteration , that is there is no labelled data - choose data points randomly to label by oracle
  285. ## Here, I am using the name of the image file to label, but we can also ask the user to label.
  286. print("In First Iteration - so default using Random Query Strategy")
  287. images_to_label=random_query_strategy(unlabelled_images,initial_pool_size)
  288. #images_to_label=random.sample(unlabelled_images,num_samples_to_label)
  289. else:
  290. if query_strategy=="random":
  291. print("Choosing for the Unlabelled data random samples")
  292. images_to_label=random_query_strategy(unlabelled_images,query_size)
  293. if query_strategy=="entropy":
  294. print("Choosing samples from the unlabelled data where the model is not confident about")
  295. if ITERATION_COUNT==1 and use_cleaned_array==False:
  296. ### Clean the Images and save it as a numpy array. We will also upload the Numpy array to Dagshub
  297. cleaned_images={}
  298. print("Cleaning The Images")
  299. for folder_path in folder_paths:
  300. cleaned_images.update(generate_clean_images(folder_path,image_dim,n_channels))
  301. print("Number of Images in the Cleaned Data ",len(cleaned_images))
  302. print('Done Cleaning')
  303. np.save('cleaned_images_numpy_array.npy',cleaned_images)
  304. print("Saved Cleaned Images Numpy Array")
  305. repo = Repo(DAGSHUB_USERNAME,DAGSHUB_REPO_NAME,branch="main",username=DAGSHUB_USERNAME,token=DAGSHUB_TOKEN)
  306. repo.upload(file="cleaned_images_numpy_array.npy",path="cleaned_images_numpy_array.npy",commit_message="Updating Cleaned Images Numpy Array",versioning="dvc")
  307. print("Loading the Cleaned Images Numpy Array")
  308. ## If it is the first iteration and we need to use the cleaned_array,load it from Dagshub
  309. if ITERATION_COUNT==1 and use_cleaned_array==True:
  310. ### Pull the file from the Repo and calculate the entropy
  311. fs=create_streaming_client()
  312. numpy_file_path=os.path.join(DAGSHUB_REPO_NAME,"cleaned_images_numpy_array.npy")
  313. fs.open(numpy_file_path)
  314. cleaned_images=np.load(numpy_file_path,allow_pickle=True)
  315. cleaned_images=cleaned_images[()]
  316. CLEANED_IMAGES_ARRAY=cleaned_images
  317. ### Run the Prediction on the data and choose the unlabelled samples to label
  318. images_to_label=entropy_query_strategy(unlabelled_images,query_size,classifier_model,cleaned_images=CLEANED_IMAGES_ARRAY)
  319. data.loc[data['file_name'].isin(images_to_label),'labelled']=True
  320. data['class_assigned']=data.apply(lambda row:label_image(row['file_name'],row['labelled']),axis=1)
  321. print(ITERATION_COUNT)
  322. ITERATION_COUNT=ITERATION_COUNT+1
  323. return data
  324. '''
  325. This data generator reads the data from a given path and generates batches of data.
  326. This is used to generate training and validation data for Active Learning
  327. '''
  328. class ActiveLearningDataGenerator(keras.utils.Sequence):
  329. 'Generates data for Keras'
  330. def __init__(self,dataframe,data_directory,mode='train', image_cls={'ok':0,'defect':1},
  331. batch_size=32, dim=(150, 150), n_channels=3, shuffle=True,train_test_split=0.8,
  332. rotation_range=None, width_shift_range=None, height_shift_range=None,horizontal_flip=False,brightness_range=None):
  333. """
  334. Initialise the data generator
  335. """
  336. self.dim = dim
  337. self.batch_size = batch_size
  338. self.labels = {}
  339. self.list_IDs = []
  340. self.rotation_range=rotation_range
  341. self.horizontal_flip=horizontal_flip
  342. self.brightness_range=brightness_range
  343. self.height_shift_range=height_shift_range
  344. self.width_shift_range=width_shift_range
  345. self.fs=create_streaming_client()
  346. # glob through directory of each class
  347. ### Filter the dataframe only for labelled data
  348. dataframe=dataframe[dataframe['labelled']==True]
  349. print("Number of Labelled Data for This Iteration is ",dataframe.shape[0])
  350. label_class=[key for key,val in image_cls.items()]
  351. for i, class_name in enumerate(label_class):
  352. ### Get the number of images in both classes and split the data into training and validation
  353. num_images=dataframe[dataframe['class_assigned']==class_name].shape[0]
  354. print("number of images in "+class_name+" is "+str(num_images))
  355. brk_point = int(num_images*train_test_split) #Divide the data into 80:20 - training and validation set
  356. file_paths=dataframe.loc[dataframe['class_assigned']==class_name,'file_name'].tolist()
  357. #file_paths=os.listdir(os.path.join(data_directory,class_name+"/"))
  358. if class_name=="ok":
  359. cls_name="ok"
  360. if class_name=="defect":
  361. cls_name="def"
  362. folder_path=os.path.join(data_directory,cls_name+"_front/")
  363. print(folder_path)
  364. if mode == 'train':
  365. file_paths = file_paths[:brk_point]
  366. else:
  367. file_paths = file_paths[brk_point:]
  368. file_paths=[os.path.join(folder_path,file_path) for file_path in file_paths]
  369. self.list_IDs += file_paths
  370. self.labels.update({p:image_cls[class_name] for p in file_paths})
  371. print("Number of Files For "+mode+"for class "+class_name+" is "+str(len(file_paths)))
  372. self.n_channels = n_channels
  373. self.n_classes = len(label_class)
  374. self.shuffle = shuffle
  375. self.sample_size=len(self.list_IDs)
  376. self.on_epoch_end()
  377. self.on_epoch_end()
  378. def __len__(self):
  379. 'Denotes the number of batches per epoch'
  380. return int(np.floor(len(self.list_IDs) / self.batch_size))
  381. def __getitem__(self, index):
  382. 'Generate one batch of data'
  383. # Generate indexes of the batch
  384. indexes = self.indexes[index*self.batch_size:(index+1)*self.batch_size]
  385. # Find list of IDs
  386. #list_IDs_temp = [self.list_IDs[k] for k in indexes]
  387. # Generate data
  388. X, y = self.__data_generation(indexes)
  389. return X, y
  390. def on_epoch_end(self):
  391. 'Updates indexes after each epoch. If shuffle is true, this will shuffle the dataset'
  392. print("In On_EPOCH_END")
  393. self.indexes = np.arange(len(self.list_IDs))
  394. if self.shuffle == True:
  395. np.random.shuffle(self.indexes)
  396. def __data_generation(self, indexes):
  397. 'Generates data containing batch_size samples' # X : (n_samples, *dim, n_channels)
  398. # Initialization
  399. X = np.empty((self.batch_size, *self.dim, self.n_channels))
  400. y = np.empty((self.batch_size), dtype=int)
  401. ### Generate data based on the indexes.
  402. for i,idx in enumerate(indexes):
  403. #image_id=self.images[idx]
  404. img_path=self.list_IDs[idx]
  405. #print(img_path)
  406. ### Read the Images using Streaming Client
  407. img=read_images_streaming(self.fs,img_path)
  408. img=img/255
  409. img=cv.resize(img,self.dim)
  410. ### Convert the image to grayscale
  411. if self.n_channels==1:
  412. img=convert_to_grayscale(img)
  413. ### Apply other transformation whenever required
  414. if self.rotation_range!=None:
  415. img=random_rotation(img,self.rotation_range)
  416. if self.width_shift_range!=None:
  417. img=random_shift(img,wrg=self.width_shift_range,hrg=0)
  418. if self.height_shift_range!=None:
  419. img=random_shift(img,hrg=self.height_shift_range,wrg=0)
  420. if self.brightness_range!=None:
  421. img=random_brightness(img,brightness_range=self.brightness_range)
  422. if self.horizontal_flip==True:
  423. img=cv.flip(img, 1)
  424. X[i,]=img
  425. ### Store the labels
  426. y[i]=self.labels[img_path]
  427. #print("Data Shape Printing")
  428. #print(X.shape)
  429. #print(y.shape)
  430. return X,y
  431. def set_end_flag(num_labelled_samples,threshold_sampling):
  432. if num_labelled_samples>=threshold_sampling:
  433. return False
  434. return True
  435. def get_num_unlabelled(train_data):
  436. return train_data[train_data['labelled']==False].shape[0]
  437. def get_num_labelled(train_data):
  438. return train_data[train_data['labelled']==True].shape[0]
  439. def clean_image(fs,file_path,image_dim,n_channels):
  440. img=read_images_streaming(fs,file_path)
  441. img=img/255
  442. img=cv.resize(img,image_dim)
  443. if n_channels==1:
  444. img=convert_to_grayscale(img)
  445. return img
  446. def get_iteration_labelled(is_labelled,current_iter_count,iteration_count):
  447. if is_labelled==False:
  448. return -1
  449. else:
  450. if current_iter_count!=-1:
  451. return current_iter_count
  452. else:
  453. return iteration_count
  454. #### We will use MLFLOW To track our experiments - and the results we will store it on Dagshub
  455. if __name__ == "__main__":
  456. '''
  457. This should take the following parameters as arguments
  458. 1. num_epochs -- done, optional. dafult is 20
  459. 2. initial_pool_size -- done, optional
  460. 3. query_size -- done,optional
  461. 4. thresholding samples size. done, optiona. default value is NUM_SAMPLES_LABELLED_PER_ITERATION
  462. 5. experiment_name -- done,mandatory
  463. 6. query_strategy -- done,optional.default is "random". Takes value either random or entropy
  464. 7. batch_size -- done, optional. default is 16
  465. 8. image_dim -- done, optional. default is (300,300)
  466. 9. num_channels -- done, optional default is 1
  467. '''
  468. parser = argparse.ArgumentParser()
  469. parser.add_argument('--initial_query_size', type=int, required=False)
  470. parser.add_argument('--pool_size', type=int, required=False)
  471. parser.add_argument('--query_size',type=int,required=False)
  472. parser.add_argument('--query_strategy',type=str,required=False,choices=['random', 'entropy'])
  473. parser.add_argument('--experiment_name',type=str,required=True)
  474. parser.add_argument('--n_epochs',type=int,required=False)
  475. parser.add_argument('--batch_size',type=int,required=False)
  476. parser.add_argument('--image_dim',type=int, nargs=2,required=False)
  477. parser.add_argument('--n_channels',type=int,required=False)
  478. parser.add_argument("--threshold_sampling",type=int,required=False)
  479. parser.add_argument("--use_cleaned_array",type=int,required=False)
  480. args = parser.parse_args()
  481. if args.initial_query_size:
  482. INITIAL_TRAINING_SAMPLES=args.initial_query_size
  483. if args.query_size:
  484. NUM_SAMPLES_LABELLED_PER_ITERATION=args.query_size
  485. if args.query_strategy:
  486. query_strategy=args.query_strategy
  487. else:
  488. query_strategy="random"
  489. if args.pool_size:
  490. POOL_SIZE=args.pool_size
  491. if args.use_cleaned_array:
  492. if args.use_cleaned_array==0:
  493. CLEANED_ARRAY=False
  494. else:
  495. CLEANED_ARRAY=True
  496. else:
  497. CLEANED_ARRAY=False
  498. if args.n_epochs:
  499. n_epochs=args.n_epochs
  500. else:
  501. n_epochs=20
  502. if args.batch_size:
  503. batch_size=args.batch_size
  504. else:
  505. batch_size=16
  506. if args.image_dim:
  507. dim=tuple(args.image_dim)
  508. else:
  509. dim=(300,300)
  510. if args.n_channels:
  511. n_channels=args.n_channels
  512. else:
  513. n_channels=1
  514. if args.threshold_sampling:
  515. threshold_sampling=args.threshold_sampling
  516. else:
  517. threshold_sampling=MAX_SAMPLES_LABELLED
  518. experiment_name=args.experiment_name
  519. ### Create the TRain DataFrame with the list of images, initially all of them are unlaballed
  520. TRAIN_OK_DATA_PATH=os.path.join(TRAIN_DATA_PATH,OK_DATA_FOLDER)
  521. TRAIN_DEFECT_DATA_PATH=os.path.join(TRAIN_DATA_PATH,DEFECT_DATA_FOLDER)
  522. if query_strategy=="entropy":
  523. FOLDER_PATHS=[TRAIN_OK_DATA_PATH,TRAIN_DEFECT_DATA_PATH]
  524. else:
  525. FOLDER_PATHS=None
  526. train_data=create_train_data_frame(TRAIN_OK_DATA_PATH,TRAIN_DEFECT_DATA_PATH)
  527. train_data['iteration_labelled']=-1
  528. ### We will run Active Learning Loop till there is very less change in the test accuracy or till all the training samples have been labelled
  529. current_accuracy=0
  530. num_labelled_samples=get_num_labelled(train_data)
  531. print(num_labelled_samples,threshold_sampling)
  532. COUNT_ITER=0
  533. query_data=train_data.copy()
  534. #experiment_name="active-learning-random"
  535. count=0
  536. classifier_model=None
  537. while set_end_flag(num_labelled_samples,threshold_sampling):
  538. ## Query the oracle and get the Data Samples Labelled
  539. if classifier_model!=None:
  540. print("Classifier Model Not None")
  541. else:
  542. print("Classifier Model None")
  543. query_data=query_the_oracle(query_data,initial_pool_size=INITIAL_TRAINING_SAMPLES,query_size=NUM_SAMPLES_LABELLED_PER_ITERATION,folder_paths=FOLDER_PATHS,query_strategy=query_strategy,classifier_model=classifier_model,image_dim=dim,n_channels=n_channels,use_cleaned_array=CLEANED_ARRAY)
  544. ### For the labelled data - set the iteration_number to count
  545. query_data['iteration_labelled']=query_data.apply(lambda row:get_iteration_labelled(row['labelled'],row['iteration_labelled'],count),axis=1)
  546. query_data.to_excel("Query_Data_Labelling_"+query_strategy+".xlsx",index=False)
  547. #repo = Repo(DAGSHUB_USERNAME,DAGSHUB_REPO_NAME,branch="main",username=DAGSHUB_USERNAME,token=DAGSHUB_TOKEN)
  548. #repo.upload(file="Query_Data_Labelling_"+query_strategy+".xlsx",path="query_data_label_"+query_strategy+"/Query_Data_Labelling_"+query_strategy+".xlsx",commit_message="Updating Query Data for "+query_strategy+" after iteration "+str(count))
  549. print("Number of Samples Labelled ",get_num_labelled(query_data))
  550. print("Number of Samples Unlabelled ",get_num_unlabelled(query_data))
  551. cnn_model,run_id,history,test_metrics=building_model(query_data,experiment_name=experiment_name,n_epochs=n_epochs,batch_size=batch_size,dim=dim,n_channels=n_channels)
  552. prev_accuracy=current_accuracy
  553. current_accuracy=test_metrics['accuracy_score']
  554. print("Prev Accuracy ",prev_accuracy)
  555. print("Test Accuracy For Iteration "+str(COUNT_ITER)+" is "+str(current_accuracy))
  556. #print("Train Accuracy For Iteration "+str(COUNT_ITER)+" is "+str(history.history['acc']))
  557. print("Change is Test Accuracy ",str(current_accuracy-prev_accuracy))
  558. num_unlabelled_samples=get_num_unlabelled(query_data)
  559. num_labelled_samples=get_num_labelled(query_data)
  560. classifier_model=cnn_model
  561. count=count+1
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...