alok94 commited on
Commit
043af41
·
1 Parent(s): b3d94c7

skin classifer first

Browse files
app.py ADDED
@@ -0,0 +1,408 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # import system libs
2
+ import os
3
+ import time
4
+ import shutil
5
+ import itertools
6
+
7
+ # import data handling tools
8
+ import cv2
9
+ import numpy as np
10
+ import pandas as pd
11
+ import seaborn as sns
12
+ sns.set_style('darkgrid')
13
+ import matplotlib.pyplot as plt
14
+ import gradio as gr
15
+
16
+ # import Deep learning Libraries
17
+ import tensorflow as tf
18
+ from tensorflow import keras
19
+ from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Activation, Dropout, BatchNormalization
20
+ from tensorflow.keras.models import Model, load_model, Sequential
21
+ from tensorflow.keras.preprocessing.image import ImageDataGenerator
22
+ from sklearn.metrics import confusion_matrix, classification_report
23
+ from sklearn.model_selection import train_test_split
24
+ from tensorflow.keras.optimizers import Adam, Adamax
25
+ from tensorflow.keras import regularizers
26
+ from tensorflow.keras.metrics import categorical_crossentropy
27
+ from tensorflow.keras.utils import to_categorical
28
+ from PIL import Image
29
+ from sklearn.model_selection import train_test_split
30
+
31
+
32
+ # Ignore Warnings
33
+ import warnings
34
+ warnings.filterwarnings("ignore")
35
+ print ('modules loaded')
36
+ #---Training-----------------------------
37
+ # ! pip install -q kaggle
38
+ # from google.colab import files
39
+
40
+ # files.upload()
41
+ # ! mkdir ~/.kaggle
42
+
43
+ # ! cp kaggle.json ~/.kaggle/
44
+ # ! chmod 600 ~/.kaggle/kaggle.json
45
+ # ! kaggle datasets list
46
+ # !kaggle datasets download -d kmader/skin-cancer-mnist-ham10000
47
+ # ! mkdir kaggle
48
+ # ! unzip skin-cancer-mnist-ham10000.zip -d kaggle
49
+ # data_dir = '/content/kaggle/hmnist_28_28_RGB.csv'
50
+ # data = pd.read_csv(data_dir)
51
+ # print(data.shape)
52
+ # data.head()
53
+
54
+ # Label = data["label"]
55
+ # Data = data.drop(columns=["label"])
56
+ # print(data.shape)
57
+ # Data.head()
58
+
59
+ # from imblearn.over_sampling import RandomOverSampler
60
+
61
+ # oversample = RandomOverSampler()
62
+ # Data, Label = oversample.fit_resample(Data, Label)
63
+ # print(Data.shape)
64
+ # Data = np.array(Data).reshape(-1,28, 28,3)
65
+ # print('Shape of Data :', Data.shape)
66
+
67
+ # Label = np.array(Label)
68
+ # Label
69
+ # classes = {4: ('nv', ' melanocytic nevi'),
70
+ # 6: ('mel', 'melanoma'),
71
+ # 2 :('bkl', 'benign keratosis-like lesions'),
72
+ # 1:('bcc' , ' basal cell carcinoma'),
73
+ # 5: ('vasc', ' pyogenic granulomas and hemorrhage'),
74
+ # 0: ('akiec', 'Actinic keratoses and intraepithelial carcinomae'),
75
+ # 3: ('df', 'dermatofibroma')}
76
+
77
+
78
+
79
+ # X_train , X_test , y_train , y_test = train_test_split(Data , Label , test_size = 0.25 , random_state = 49)
80
+
81
+ # print(f'X_train shape: {X_train.shape}\nX_test shape: {X_test.shape}')
82
+ # print(f'y_train shape: {y_train.shape}\ny_test shape: {y_test.shape}')
83
+
84
+ # y_train = to_categorical(y_train)
85
+ # y_test = to_categorical(y_test)
86
+
87
+ # datagen = ImageDataGenerator(rescale=(1./255)
88
+ # ,rotation_range=10
89
+ # ,zoom_range = 0.1
90
+ # ,width_shift_range=0.1
91
+ # ,height_shift_range=0.1)
92
+
93
+ # testgen = ImageDataGenerator(rescale=(1./255))
94
+
95
+ # from keras.callbacks import ReduceLROnPlateau
96
+
97
+ # learning_rate_reduction = ReduceLROnPlateau(monitor='val_accuracy'
98
+ # , patience = 2
99
+ # , verbose=1
100
+ # ,factor=0.5
101
+ # , min_lr=0.00001)
102
+
103
+ # model = keras.models.Sequential()
104
+
105
+ # # Create Model Structure
106
+ # model.add(keras.layers.Input(shape=[28, 28, 3]))
107
+ # model.add(keras.layers.Conv2D(32, (3, 3), activation='relu', padding='same', kernel_initializer='he_normal'))
108
+ # model.add(keras.layers.MaxPooling2D())
109
+ # model.add(keras.layers.BatchNormalization())
110
+
111
+ # model.add(keras.layers.Conv2D(64, (3, 3), activation='relu', padding='same', kernel_initializer='he_normal'))
112
+ # model.add(keras.layers.Conv2D(64, (3, 3), activation='relu', padding='same', kernel_initializer='he_normal'))
113
+ # model.add(keras.layers.MaxPooling2D())
114
+ # model.add(keras.layers.BatchNormalization())
115
+
116
+ # model.add(keras.layers.Conv2D(128, (3, 3), activation='relu', padding='same', kernel_initializer='he_normal'))
117
+ # model.add(keras.layers.Conv2D(128, (3, 3), activation='relu', padding='same', kernel_initializer='he_normal'))
118
+ # model.add(keras.layers.MaxPooling2D())
119
+ # model.add(keras.layers.BatchNormalization())
120
+
121
+ # model.add(keras.layers.Conv2D(256, (3, 3), activation='relu', padding='same', kernel_initializer='he_normal'))
122
+ # model.add(keras.layers.Conv2D(256, (3, 3), activation='relu', padding='same', kernel_initializer='he_normal'))
123
+ # model.add(keras.layers.MaxPooling2D())
124
+
125
+ # model.add(keras.layers.Flatten())
126
+
127
+ # model.add(keras.layers.Dropout(rate=0.2))
128
+ # model.add(keras.layers.Dense(units=256, activation='relu', kernel_initializer='he_normal'))
129
+ # model.add(keras.layers.BatchNormalization())
130
+
131
+ # model.add(keras.layers.Dense(units=128, activation='relu', kernel_initializer='he_normal'))
132
+ # model.add(keras.layers.BatchNormalization())
133
+
134
+ # model.add(keras.layers.Dense(units=64, activation='relu', kernel_initializer='he_normal'))
135
+ # model.add(keras.layers.BatchNormalization())
136
+
137
+ # model.add(keras.layers.Dense(units=32, activation='relu', kernel_initializer='he_normal', kernel_regularizer=keras.regularizers.L1L2()))
138
+ # model.add(keras.layers.BatchNormalization())
139
+
140
+ # model.add(keras.layers.Dense(units=7, activation='softmax', kernel_initializer='glorot_uniform', name='classifier'))
141
+
142
+ # model.compile(Adamax(learning_rate= 0.001), loss= 'categorical_crossentropy', metrics= ['accuracy'])
143
+
144
+ # model.summary()
145
+
146
+ # history = model.fit(X_train ,
147
+ # y_train ,
148
+ # epochs=25 ,
149
+ # batch_size=128,
150
+ # validation_data=(X_test , y_test) ,
151
+ # callbacks=[learning_rate_reduction])
152
+
153
+ # def plot_training(hist):
154
+ # tr_acc = hist.history['accuracy']
155
+ # tr_loss = hist.history['loss']
156
+ # val_acc = hist.history['val_accuracy']
157
+ # val_loss = hist.history['val_loss']
158
+ # index_loss = np.argmin(val_loss)
159
+ # val_lowest = val_loss[index_loss]
160
+ # index_acc = np.argmax(val_acc)
161
+ # acc_highest = val_acc[index_acc]
162
+
163
+ # plt.figure(figsize= (20, 8))
164
+ # plt.style.use('fivethirtyeight')
165
+ # Epochs = [i+1 for i in range(len(tr_acc))]
166
+ # loss_label = f'best epoch= {str(index_loss + 1)}'
167
+ # acc_label = f'best epoch= {str(index_acc + 1)}'
168
+
169
+ # plt.subplot(1, 2, 1)
170
+ # plt.plot(Epochs, tr_loss, 'r', label= 'Training loss')
171
+ # plt.plot(Epochs, val_loss, 'g', label= 'Validation loss')
172
+ # plt.scatter(index_loss + 1, val_lowest, s= 150, c= 'blue', label= loss_label)
173
+ # plt.title('Training and Validation Loss')
174
+ # plt.xlabel('Epochs')
175
+ # plt.ylabel('Loss')
176
+ # plt.legend()
177
+
178
+ # plt.subplot(1, 2, 2)
179
+ # plt.plot(Epochs, tr_acc, 'r', label= 'Training Accuracy')
180
+ # plt.plot(Epochs, val_acc, 'g', label= 'Validation Accuracy')
181
+ # plt.scatter(index_acc + 1 , acc_highest, s= 150, c= 'blue', label= acc_label)
182
+ # plt.title('Training and Validation Accuracy')
183
+ # plt.xlabel('Epochs')
184
+ # plt.ylabel('Accuracy')
185
+ # plt.legend()
186
+
187
+ # plt.tight_layout
188
+ # plt.show()
189
+
190
+ # plot_training(history)
191
+
192
+ # train_score = model.evaluate(X_train, y_train, verbose= 1)
193
+ # test_score = model.evaluate(X_test, y_test, verbose= 1)
194
+
195
+ # print("Train Loss: ", train_score[0])
196
+ # print("Train Accuracy: ", train_score[1])
197
+ # print('-' * 20)
198
+ # print("Test Loss: ", test_score[0])
199
+ # print("Test Accuracy: ", test_score[1])
200
+
201
+ # y_true = np.array(y_test)
202
+ # y_pred = model.predict(X_test)
203
+
204
+ # y_pred = np.argmax(y_pred , axis=1)
205
+ # y_true = np.argmax(y_true , axis=1)
206
+
207
+ # classes_labels = []
208
+ # for key in classes.keys():
209
+ # classes_labels.append(key)
210
+
211
+ # print(classes_labels)
212
+
213
+ # # Confusion matrix
214
+ # cm = cm = confusion_matrix(y_true, y_pred, labels=classes_labels)
215
+
216
+ # plt.figure(figsize= (10, 10))
217
+ # plt.imshow(cm, interpolation= 'nearest', cmap= plt.cm.Blues)
218
+ # plt.title('Confusion Matrix')
219
+ # plt.colorbar()
220
+
221
+ # tick_marks = np.arange(len(classes))
222
+ # plt.xticks(tick_marks, classes, rotation= 45)
223
+ # plt.yticks(tick_marks, classes)
224
+
225
+
226
+ # thresh = cm.max() / 2.
227
+ # for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
228
+ # plt.text(j, i, cm[i, j], horizontalalignment= 'center', color= 'white' if cm[i, j] > thresh else 'black')
229
+
230
+ # plt.tight_layout()
231
+ # plt.ylabel('True Label')
232
+ # plt.xlabel('Predicted Label')
233
+
234
+ # plt.show()
235
+
236
+ # #Save the model
237
+ # model.save('skin_cancer_model.h5')
238
+
239
+ # converter = tf.lite.TFLiteConverter.from_keras_model(model)
240
+ # tflite_model = converter.convert()
241
+
242
+ # print("model converted")
243
+
244
+ # # Save the model.
245
+ # with open('skin_cancer_model.tflite', 'wb') as f:
246
+ # f.write(tflite_model)
247
+
248
+ #Training End------------------------------------------
249
+
250
+ skin_classes = {4: ('nv', ' melanocytic nevi'),
251
+ 6: ('mel', 'melanoma'),
252
+ 2 :('bkl', 'benign keratosis-like lesions'),
253
+ 1:('bcc' , ' basal cell carcinoma'),
254
+ 5: ('vasc', ' pyogenic granulomas and hemorrhage'),
255
+ 0: ('akiec', 'Actinic keratoses and intraepithelial carcinomae'),
256
+ 3: ('df', 'dermatofibroma')}
257
+
258
+ #Use saved model
259
+ loaded_model = tf.keras.models.load_model('skin_cancer_model.h5', compile=False)
260
+ loaded_model.compile(Adamax(learning_rate= 0.001), loss= 'categorical_crossentropy', metrics= ['accuracy'])
261
+
262
+ def predict_digit(image):
263
+ if image is not None:
264
+
265
+ #Use saved model
266
+ loaded_model = tf.keras.models.load_model('skin_cancer_model.h5', compile=False)
267
+ loaded_model.compile(Adamax(learning_rate= 0.001), loss= 'categorical_crossentropy', metrics= ['accuracy'])
268
+ img = image.resize((28, 28))
269
+ img_array = tf.keras.preprocessing.image.img_to_array(img)
270
+ img_array = tf.expand_dims(img_array, 0)
271
+ print(img_array)
272
+
273
+
274
+ predictions = loaded_model.predict(img_array)
275
+ print(predictions)
276
+ #class_labels = [] # data classes
277
+ score = tf.nn.softmax(predictions[0])*100
278
+
279
+
280
+ print(score)
281
+ print(skin_classes[np.argmax(score)])
282
+ simple = pd.DataFrame(
283
+ {
284
+ "skin condition": ["akiec", "bcc", "bkl", "df", "nv", "vasc", "mel"],
285
+ "probability": score,
286
+ "full skin condition": [ 'Actinic keratoses',
287
+ ' basal cell carcinoma',
288
+ 'benign keratosis-like lesions',
289
+ 'dermatofibroma',
290
+ ' melanocytic nevi',
291
+ ' pyogenic granulomas and hemorrhage',
292
+ 'melanoma'],
293
+ }
294
+ )
295
+
296
+
297
+
298
+
299
+ predicted_skin_condition=skin_classes[np.argmax(score)][1]+" ("+ skin_classes[np.argmax(score)][0]+")"
300
+ return predicted_skin_condition, gr.BarPlot(
301
+ simple,
302
+ x="skin condition",
303
+ y="probability",
304
+ x_title="Skin Condition",
305
+ y_title="Classification Probabilities",
306
+ title="Skin Cancer Classification Probability",
307
+ tooltip=["full skin condition", "probability"],
308
+ vertical=False,
309
+ y_lim=[0, 100],
310
+ color="full skin condition"
311
+ )
312
+
313
+ else:
314
+ simple_empty = pd.DataFrame(
315
+ {
316
+ "skin condition": ["akiec", "bcc", "bkl", "df", "nv", "vasc", "mel"],
317
+ "probability": [0,0,0,0,0,0,0],
318
+ "full skin condition": [ 'Actinic keratoses',
319
+ ' basal cell carcinoma',
320
+ 'benign keratosis-like lesions',
321
+ 'dermatofibroma',
322
+ ' melanocytic nevi',
323
+ ' pyogenic granulomas and hemorrhage',
324
+ 'melanoma'],
325
+ }
326
+ )
327
+
328
+ return " ", gr.BarPlot(
329
+ simple_empty,
330
+ x="skin condition",
331
+ y="probability",
332
+ x_title="Digits",
333
+ y_title="Identification Probabilities",
334
+ title="Identification Probability",
335
+ tooltip=["full skin condition", "probability"],
336
+ vertical=False,
337
+ y_lim=[0, 100],
338
+
339
+ )
340
+
341
+ skin_images = [
342
+ ("skin_image/mel.jpg",'mel'),
343
+ ("skin_image/nv3.jpg",'nv'),
344
+ ("skin_image/bkl.jpg",'bkl'),
345
+ ("skin_image/df.jpg",'df'),
346
+ ("skin_image/akiec.jpg",'akiec'),
347
+ ("skin_image/bcc.jpg",'bcc'),
348
+ ("skin_image/vasc.jpg",'vasc'),
349
+ ("skin_image/nv2.jpg",'nv'),
350
+ ("skin_image/akiec2.jpg",'akiec'),
351
+ ("skin_image/bkl2.jpg",'bkl'),
352
+ ("skin_image/nv.jpg",'nv'),
353
+
354
+ ]
355
+
356
+ def image_from_gallary(evt: gr.SelectData):
357
+ print(evt.index)
358
+ return skin_images[evt.index][0]
359
+
360
+
361
+
362
+ css='''
363
+ #title_head{
364
+ text-align: center;
365
+ text-weight: bold;
366
+ text-size:30px;
367
+ }
368
+ #name_head{
369
+ text-align: center;
370
+ }
371
+ '''
372
+
373
+ with gr.Blocks(css=css) as demo:
374
+
375
+ with gr.Row():
376
+ with gr.Column():
377
+ gr.Markdown("<h1>Skin Cancer Classifier</h1>", elem_id='title_head')
378
+ gr.Markdown("<h2>Cyperts Project</h2>", elem_id="name_head")
379
+ with gr.Row():
380
+ with gr.Column():
381
+ with gr.Row():
382
+ gr.Markdown("<h3>Browse or Select from given Image</h3>", elem_id='info')
383
+ img_upload=gr.Image(type="pil", height=200, width=300)
384
+ with gr.Row():
385
+ clear=gr.ClearButton(img_upload)
386
+ btn=gr.Button("Identify")
387
+
388
+ with gr.Column():
389
+ gry=gr.Gallery(value=skin_images, columns=5, show_label=False, allow_preview=False)
390
+ with gr.Row():
391
+ with gr.Column():
392
+ gr.Markdown("Most probable skin condition")
393
+ label=gr.Label("")
394
+ with gr.Row():
395
+ with gr.Column():
396
+ gr.Markdown("Other possible values")
397
+ bar = gr.BarPlot()
398
+
399
+
400
+
401
+ btn.click(predict_digit,inputs=[img_upload],outputs=[label,bar])
402
+ gry.select(image_from_gallary, outputs=img_upload)
403
+
404
+
405
+
406
+
407
+ demo.launch(debug=True)
408
+
requirements.txt ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ tensorflow
2
+ keras
3
+ opencv-python
4
+
5
+ scikit_learn<1.3.0
6
+ seaborn==0.12.2
7
+
8
+
9
+ gradio
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
skin_cancer_model.h5 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9679368b2f6da9e936c2b9306044d7b90e887189ee279d643c86aede2b844f75
3
+ size 15456152
skin_image/akiec.jpg ADDED
skin_image/akiec2.jpg ADDED
skin_image/bcc.jpg ADDED
skin_image/bkl.jpg ADDED
skin_image/bkl2.jpg ADDED
skin_image/df.jpg ADDED
skin_image/mel.jpg ADDED
skin_image/mel2.jpg ADDED
skin_image/nv.jpg ADDED
skin_image/nv2.jpg ADDED
skin_image/nv3.jpg ADDED
skin_image/test.png ADDED
skin_image/vasc.jpg ADDED