CoolFace
Apppublic

DHEIVER/LungImageAnalyzer

sourceHugging Faceopenrailupdated 3y agoView on Hugging Face
0likes
app.py228 linesDownload Raw Back to root
1# -*- coding: utf-8 -*-2"""lung cancerdetection.ipynb3 4Automatically generated by Colaboratory.5 6Original file is located at7    https://colab.research.google.com/drive/1f7VybSnYLPbUVLRLMNQboxQkCYaBCXMs8"""9 10 11# This Python 3 environment comes with many helpful analytics libraries installed12# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python13# For example, here's several helpful packages to load14 15import numpy as np # linear algebra16import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)17 18# Input data files are available in the read-only "../input/" directory19# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory20 21import os22 23 24# 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" 25# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session26 27# importing libraries28 29import tensorflow as tf30from tensorflow.keras.layers import Input, Lambda, Dense, Flatten31from tensorflow.keras.models import Model32from tensorflow.keras.applications.resnet50 import ResNet5033from tensorflow.keras.applications.resnet50 import preprocess_input34from tensorflow.keras.preprocessing import image35from tensorflow.keras.preprocessing.image import ImageDataGenerator,load_img36from tensorflow.keras.models import Sequential37import numpy as np38from glob import glob39import matplotlib.pyplot as plt40 41image_set =  "./lung_image_sets"42 43SIZE_X = SIZE_Y = 22444 45datagen = tf.keras.preprocessing.image.ImageDataGenerator(validation_split = 0.2)46 47train_set = datagen.flow_from_directory(image_set,48                                       class_mode = "categorical",49                                       target_size = (SIZE_X,SIZE_Y),50                                       color_mode="rgb",51                                       batch_size = 128, 52                                       shuffle = False,53                                       subset='training',54                                       seed = 42)55 56validate_set = datagen.flow_from_directory(image_set,57                                       class_mode = "categorical",58                                       target_size = (SIZE_X, SIZE_Y),59                                       color_mode="rgb",60                                       batch_size = 128, 61                                       shuffle = False,62                                       subset='validation',63                                       seed = 42)64 65 66IMAGE_SIZE = [224, 224]67 68resnet = ResNet50(input_shape=IMAGE_SIZE + [3], weights='imagenet', include_top=False)69 70# don't train existing weights71for layer in resnet.layers:72    layer.trainable = False73 74flatten = Flatten()(resnet.output)75dense = Dense(256, activation = 'relu')(flatten)76dense = Dense(128, activation = 'relu')(dense)77prediction = Dense(3, activation = 'softmax')(dense)78 79#creating a model80model = Model(inputs = resnet.input, outputs = prediction )81 82model.summary()83 84model.compile(loss = 'categorical_crossentropy', optimizer = 'adam', metrics = ['accuracy'])85 86#executing the model87history = model.fit(train_set, validation_data = (validate_set), epochs = 8, verbose = 1)88 89# plotting the loss90plt.plot(history.history['loss'],label = 'train_loss')91plt.plot(history.history['val_loss'], label = 'testing_loss')92plt.title('loss')93plt.legend()94plt.show()95 96# Both Validation and Training accuracy is shown here97 98plt.plot(history.history['accuracy'], label='training_accuracy')99plt.plot(history.history['val_accuracy'], label='validation accuracy')100plt.title('Accuracy')101plt.legend()102plt.show()103 104# CHECKING THE CONFUSION MATRIX105 106from sklearn.metrics import classification_report107from sklearn.metrics import confusion_matrix108from sklearn.metrics import f1_score109Y_pred = model.predict(validate_set)110y_pred = np.argmax(Y_pred ,axis =1)111print('Confusion Matrix')112confusion_matrix = confusion_matrix(validate_set.classes, y_pred)113print(confusion_matrix)114print('Classification Report')115target_names = ['aca','n', 'scc']116print(classification_report(validate_set.classes, y_pred, target_names=target_names))117 118result = model.evaluate(validate_set,batch_size=128)119print("test_loss, test accuracy",result)120 121import pickle122 123with open('model_pkl', 'wb') as files:124    pickle.dump(model, files)125 126# img = tf.keras.utils.load_img('/content/lung_colon_image_set/lung_image_sets/lung_aca/lungaca1.jpeg', target_size=(224, 224))127# img_array = tf.keras.utils.img_to_array(img)128# img_array = tf.expand_dims(img_array, 0)129 130# # load saved model131# with open('model_pkl' , 'rb') as f:132#     lr = pickle.load(f)133#     predi=lr.predict(img_array)134#     print(predi)135#     image_output_class=target_names[np.argmax(predi)]136 137# print("The predicted class is", image_output_class)138 139import gradio as gd140from PIL import Image141 142css_class="""143body{ background-color:rgb(10, 30, 75)}144ul>li{145    text-decoration: none;146    list-style:none;147    margin: 1px;148    padding:.5px149}150h3{151    color: rgb(24, 46, 98);152    margin: 1px;153    padding:.5px154    text-align: center;155}156h4{157    text-decoration: underline;158    color: rgb(218, 57, 57);159    text-align: center;160}161 162"""163def acaClassOutput():164    return '''165    <h3>You CT Scan Report:-</h3>166    <hr>167    <h4>You have Adenocarcinoma type cancer</h4>168    <p>It is Non-small cell type cancer which has effected you 40% of lung cells.</p>169    <ul>170    <h4>You can try These cautions</h4>171    <li>Try Radiation therapy, Chemotherapy, Targeted therapy, Immunotherapy</li>172    <li>Try to stay away from Smokers and air pollution</li>173    <li>Concern with your doctor for more details.</li>174    </ul>175    '''176 177def sccClassOutput():178    return '''179    <h3>You CT Scan Report:-</h3>180    <hr>181    <h4>You have Squamous type cancer</h4>182    <p>It effects the broncial tube of lungs. You probably have smoke history as it effected your 30% lungs</p>183    <ul>184    <h4>You can try These cautions</h4>185    <li>Try Radiation therapy, Chemotherapy, Targeted therapy, Immunotherapy</li>186    <li>Try to stay away from Smokers and air pollution</li>187    <li>Concern with your doctor for more details.</li>188    '''189 190def nClassOutput():191    return '''192    <h3>You CT Scan Report:-</h3>193    <hr>194    <h4>You have Neuroendocrine type cancer</h4>195    <p>This type of cancer effect neuroendocrine which are responsible for producing harmones. This is less common than other types</p>196    <ul>197    <h4>You can try These cautions</h4>198    <li>Try regular screening if you have smoke history. Try surgeries</li>199    <li>Try to stay away from Smokers and air pollution</li>200    <li>Concern with your doctor for more details.</li>201    '''202# target_names = ['aca','n', 'scc']203def predictOutPut(image_class):204    output=''205    if(image_class=='aca'):206        output=acaClassOutput()207    elif(image_class=='n'):208        output=nClassOutput()209    elif(image_class=='scc'):210        output=sccClassOutput()211    return output212 213def greet_user(CTScanImage):214    image=gd.inputs.Image()215    pil_image = Image.fromarray(CTScanImage.astype('uint8'), 'RGB')216    pil_image_resized = pil_image.resize((224,224))217    img_array = tf.keras.utils.img_to_array(pil_image_resized)218    img_array = tf.expand_dims(img_array, 0)219    with open('model_pkl' , 'rb') as f:220        lr = pickle.load(f)221        predi=lr.predict(img_array)222        image_output_class=target_names[np.argmax(predi)]223    return  predictOutPut(image_output_class)224 225customInput=gd.inputs.Image(label="Upload You CT Scanned Image")226customOutput=gd.outputs.HTML(label="Your CT scan Report")227app =  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)228app.launch()