Detección de neumonía mediante aprendizaje profundo

En este artículo, discutiremos cómo resolver un problema médico, es decir, la neumonía , que es una enfermedad peligrosa que puede ocurrir en uno o ambos pulmones, generalmente causada por virus, hongos o bacterias. Detectaremos esta enfermedad pulmonar en base a las radiografías que tenemos. El conjunto de datos de radiografías de tórax se toma de Kaggle y contiene varias imágenes de radiografías diferenciadas por dos categorías, «neumonía» y «normal» . Crearemos un modelo de aprendizaje profundo que realmente nos dirá si la persona tiene neumonía o no.

Herramientas y Tecnologías:

VGG16: es una arquitectura de red neuronal convolucional (CNN) fácil y ampliamente utilizada utilizada para ImageNet, que es una enorme misión de base de datos visible utilizada en la investigación de software de reconocimiento visual de objetos.

Python3

from keras.models import Model
from keras.layers import Flatten,Dense
from keras.applications.vgg16 import VGG16
import matplotlib.pyplot as plot
from glob import glob

Python3

IMAGESHAPE = [224, 224, 3] 
training_data = 'chest_xray/train'
testing_data = 'chest_xray/test'

Python3

vgg_model = VGG16(input_shape=IMAGESHAPE, weights='imagenet', include_top=False)

Python3

for each_layer in vgg_model.layers:
    each_layer.trainable = False

Python3

classes = glob('chest_xray/train/*') 

Python3

flatten_layer = Flatten()(vgg_model.output)
prediction = Dense(len(classes), activation='softmax')(flatten_layer)

Python3

final_model = Model(inputs=vgg_model.input, outputs=prediction) 
final_model.summary()

Python3

final_model.compile( 
  loss='categorical_crossentropy',
  optimizer='adam',
  metrics=['accuracy']
)

Python3

from keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(rescale = 1./255, 
                                   shear_range = 0.2,
                                   zoom_range = 0.2,
                                   horizontal_flip = True)
testing_datagen = ImageDataGenerator(rescale =1. / 255)

Python3

training_set = train_datagen.flow_from_directory('chest_xray/train', 
                                                 target_size = (224, 224),
                                                 batch_size = 4,
                                                 class_mode = 'categorical')

Python3

test_set = testing_datagen.flow_from_directory('chest_xray/test',
                                               target_size = (224, 224),
                                               batch_size = 4,
                                               class_mode = 'categorical')

Python3

fitted_model = final_model.fit_generator( 
  training_set,
  validation_data=test_set,
  epochs=5,
  steps_per_epoch=len(training_set),
  validation_steps=len(test_set)
)

Python3

final_model.save('our_model.h5')

Python3

from keras_preprocessing import image
from keras.models import load_model
from keras.applications.vgg16 import preprocess_input
import numpy as np
model=load_model('our_model.h5') #Loading our model
img=image.load_img('D:/Semester - 6/PneumoniaGFG/chest_xray/val/PNEUMONIA/person1954_bacteria_4886.jpeg',target_size=(224,224))
imagee=image.img_to_array(img) #Converting the X-Ray into pixels
imagee=np.expand_dims(imagee, axis=0)
img_data=preprocess_input(imagee)
prediction=model.predict(img_data)
if prediction[0][0]>prediction[0][1]:  #Printing the prediction of model.
    print('Person is safe.')
else:
    print('Person is affected with Pneumonia.')
print(f'Predictions: {prediction}')

Python3

from keras.models import Model
from keras.layers import Flatten,Dense
from keras.applications.vgg16 import VGG16  #Import all the necessary modules
import matplotlib.pyplot as plot
from glob import glob
  
IMAGESHAPE = [224, 224, 3] #Provide image size as 224 x 224 this is a fixed-size for VGG16 architecture
vgg_model = VGG16(input_shape=IMAGESHAPE, weights='imagenet', include_top=False)
#3 signifies that we are working with RGB type of images.
training_data = 'chest_xray/train'
testing_data = 'chest_xray/test' #Give our training and testing path
  
for each_layer in vgg_model.layers:
    each_layer.trainable = False #Set the trainable as False, So that all the layers would not be trained.
classes = glob('chest_xray/train/*') #Finding how many classes present in our train dataset.
flatten_layer = Flatten()(vgg_model.output)
prediction = Dense(len(classes), activation='softmax')(flatten_layer)
final_model = Model(inputs=vgg_model.input, outputs=prediction) #Combine the VGG output and prediction , this all together will create a model.
final_model.summary() #Displaying the summary
final_model.compile( #Compiling our model using adam optimizer and optimization metric as accuracy.
  loss='categorical_crossentropy',
  optimizer='adam',
  metrics=['accuracy']
)
from keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(rescale = 1./255, #importing our dataset to keras using ImageDataGenerator in keras.
                                   shear_range = 0.2,
                                   zoom_range = 0.2,
                                   horizontal_flip = True)
testing_datagen = ImageDataGenerator(rescale =1. / 255)
training_set = train_datagen.flow_from_directory('chest_xray/train', #inserting the images.
                                                 target_size = (224, 224),
                                                 batch_size = 4,
                                                 class_mode = 'categorical')
test_set = testing_datagen.flow_from_directory('chest_xray/test',
                                               target_size = (224, 224),
                                               batch_size = 4,
                                               class_mode = 'categorical')
fitted_model = final_model.fit_generator( #Fitting the model.
  training_set,
  validation_data=test_set,
  epochs=5,
  steps_per_epoch=len(training_set),
  validation_steps=len(test_set)
)
plot.plot(fitted_model.history['loss'], label='training loss') #Plotting the accuracies
plot.plot(fitted_model.history['val_loss'], label='validation loss')
plot.legend()
plot.show()
plot.savefig('LossVal_loss')
plot.plot(fitted_model.history['acc'], label='training accuracy')
plot.plot(fitted_model.history['val_acc'], label='validation accuracy')
plot.legend()
plot.show()
plot.savefig('AccVal_acc')
final_model.save('our_model.h5') #Saving the model file.

Python3

from keras_preprocessing import image
from keras.models import load_model
from keras.applications.vgg16 import preprocess_input
import numpy as np
model=load_model('our_model.h5') #Loading our model
img=image.load_img('D:/Semester - 6/PneumoniaGFG/chest_xray/val/PNEUMONIA/person1954_bacteria_4886.jpeg',target_size=(224,224))
imagee=image.img_to_array(img) #Converting the X-Ray into pixels
imagee=np.expand_dims(imagee, axis=0)
img_data=preprocess_input(imagee)
prediction=model.predict(img_data)
if prediction[0][0]>prediction[0][1]:  #Printing the prediction of model.
    print('Person is safe.')
else:
    print('Person is affected with Pneumonia.')
print(f'Predictions: {prediction}')

Publicación traducida automáticamente

Artículo escrito por vinayedula y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *