Spaces:
Sleeping
Sleeping
| # -*- 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() |