Spaces:
Sleeping
Sleeping
File size: 7,859 Bytes
f07f08e 9197c75 f07f08e 9197c75 f07f08e 77136fb f07f08e 9197c75 f07f08e 9197c75 f07f08e 9197c75 f07f08e 3f233f0 77136fb 3f233f0 a1beaad 3f233f0 a1beaad 3f233f0 a1beaad 3f233f0 a1beaad 3f233f0 9197c75 46b57cc 3f233f0 46b57cc f07f08e 2f109e0 f07f08e 22bca70 f07f08e 9197c75 f07f08e 46b57cc 3f233f0 eed38cb 77136fb | 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 | # -*- coding: utf-8 -*-
"""lung cancerdetection.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1f7VybSnYLPbUVLRLMNQboxQkCYaBCXMs
"""
# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
# Input data files are available in the read-only "../input/" directory
# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory
import os
# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using "Save & Run All"
# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session
# importing libraries
import tensorflow as tf
from tensorflow.keras.layers import Input, Lambda, Dense, Flatten
from tensorflow.keras.models import Model
from tensorflow.keras.applications.resnet50 import ResNet50
from tensorflow.keras.applications.resnet50 import preprocess_input
from tensorflow.keras.preprocessing import image
from tensorflow.keras.preprocessing.image import ImageDataGenerator,load_img
from tensorflow.keras.models import Sequential
import numpy as np
from glob import glob
import matplotlib.pyplot as plt
image_set = "./lung_image_sets"
SIZE_X = SIZE_Y = 224
datagen = tf.keras.preprocessing.image.ImageDataGenerator(validation_split = 0.2)
train_set = datagen.flow_from_directory(image_set,
class_mode = "categorical",
target_size = (SIZE_X,SIZE_Y),
color_mode="rgb",
batch_size = 128,
shuffle = False,
subset='training',
seed = 42)
validate_set = datagen.flow_from_directory(image_set,
class_mode = "categorical",
target_size = (SIZE_X, SIZE_Y),
color_mode="rgb",
batch_size = 128,
shuffle = False,
subset='validation',
seed = 42)
IMAGE_SIZE = [224, 224]
resnet = ResNet50(input_shape=IMAGE_SIZE + [3], weights='imagenet', include_top=False)
# don't train existing weights
for layer in resnet.layers:
layer.trainable = False
flatten = Flatten()(resnet.output)
dense = Dense(256, activation = 'relu')(flatten)
dense = Dense(128, activation = 'relu')(dense)
prediction = Dense(3, activation = 'softmax')(dense)
#creating a model
model = Model(inputs = resnet.input, outputs = prediction )
model.summary()
model.compile(loss = 'categorical_crossentropy', optimizer = 'adam', metrics = ['accuracy'])
#executing the model
history = model.fit(train_set, validation_data = (validate_set), epochs = 8, verbose = 1)
# plotting the loss
plt.plot(history.history['loss'],label = 'train_loss')
plt.plot(history.history['val_loss'], label = 'testing_loss')
plt.title('loss')
plt.legend()
plt.show()
# Both Validation and Training accuracy is shown here
plt.plot(history.history['accuracy'], label='training_accuracy')
plt.plot(history.history['val_accuracy'], label='validation accuracy')
plt.title('Accuracy')
plt.legend()
plt.show()
# CHECKING THE CONFUSION MATRIX
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.metrics import f1_score
Y_pred = model.predict(validate_set)
y_pred = np.argmax(Y_pred ,axis =1)
print('Confusion Matrix')
confusion_matrix = confusion_matrix(validate_set.classes, y_pred)
print(confusion_matrix)
print('Classification Report')
target_names = ['aca','n', 'scc']
print(classification_report(validate_set.classes, y_pred, target_names=target_names))
result = model.evaluate(validate_set,batch_size=128)
print("test_loss, test accuracy",result)
import pickle
with open('model_pkl', 'wb') as files:
pickle.dump(model, files)
# img = tf.keras.utils.load_img('/content/lung_colon_image_set/lung_image_sets/lung_aca/lungaca1.jpeg', target_size=(224, 224))
# img_array = tf.keras.utils.img_to_array(img)
# img_array = tf.expand_dims(img_array, 0)
# # load saved model
# with open('model_pkl' , 'rb') as f:
# lr = pickle.load(f)
# predi=lr.predict(img_array)
# print(predi)
# image_output_class=target_names[np.argmax(predi)]
# print("The predicted class is", image_output_class)
import gradio as gd
from PIL import Image
css_class="""
body{ background-color:rgb(10, 30, 75)}
ul>li{
text-decoration: none;
list-style:none;
margin: 1px;
padding:.5px
}
h3{
color: rgb(24, 46, 98);
margin: 1px;
padding:.5px
text-align: center;
}
h4{
text-decoration: underline;
color: rgb(218, 57, 57);
text-align: center;
}
"""
def acaClassOutput():
return '''
<h3>You CT Scan Report:-</h3>
<hr>
<h4>You have Adenocarcinoma type cancer</h4>
<p>It is Non-small cell type cancer which has effected you 40% of lung cells.</p>
<ul>
<h4>You can try These cautions</h4>
<li>Try Radiation therapy, Chemotherapy, Targeted therapy, Immunotherapy</li>
<li>Try to stay away from Smokers and air pollution</li>
<li>Concern with your doctor for more details.</li>
</ul>
'''
def sccClassOutput():
return '''
<h3>You CT Scan Report:-</h3>
<hr>
<h4>You have Squamous type cancer</h4>
<p>It effects the broncial tube of lungs. You probably have smoke history as it effected your 30% lungs</p>
<ul>
<h4>You can try These cautions</h4>
<li>Try Radiation therapy, Chemotherapy, Targeted therapy, Immunotherapy</li>
<li>Try to stay away from Smokers and air pollution</li>
<li>Concern with your doctor for more details.</li>
'''
def nClassOutput():
return '''
<h3>You CT Scan Report:-</h3>
<hr>
<h4>You have Neuroendocrine type cancer</h4>
<p>This type of cancer effect neuroendocrine which are responsible for producing harmones. This is less common than other types</p>
<ul>
<h4>You can try These cautions</h4>
<li>Try regular screening if you have smoke history. Try surgeries</li>
<li>Try to stay away from Smokers and air pollution</li>
<li>Concern with your doctor for more details.</li>
'''
# target_names = ['aca','n', 'scc']
def predictOutPut(image_class):
output=''
if(image_class=='aca'):
output=acaClassOutput()
elif(image_class=='n'):
output=nClassOutput()
elif(image_class=='scc'):
output=sccClassOutput()
return output
def greet_user(CTScanImage):
image=gd.inputs.Image()
pil_image = Image.fromarray(CTScanImage.astype('uint8'), 'RGB')
pil_image_resized = pil_image.resize((224,224))
img_array = tf.keras.utils.img_to_array(pil_image_resized)
img_array = tf.expand_dims(img_array, 0)
with open('model_pkl' , 'rb') as f:
lr = pickle.load(f)
predi=lr.predict(img_array)
image_output_class=target_names[np.argmax(predi)]
return predictOutPut(image_output_class)
customInput=gd.inputs.Image(label="Upload You CT Scanned Image")
customOutput=gd.outputs.HTML(label="Your CT scan Report")
app = gd.Interface(fn = greet_user, inputs=customInput, outputs=customOutput,title="Lung Cancer Detection", description="Upload your CT Scan Image to know Whether You have cancer or not",css=css_class)
app.launch() |