Spaces:
Sleeping
Sleeping
File size: 8,492 Bytes
41e2b6d a4419b4 41e2b6d |
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 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 |
import keras
import numpy as np
import pandas as pd
import gradio as gr
import os
from keras.applications.densenet import DenseNet121
from keras.layers import Dense, GlobalAveragePooling2D
from keras.models import Model
med_labels = ['Cardiomegaly',
'Emphysema',
'Effusion',
'Hernia',
'Infiltration',
'Mass',
'Nodule',
'Atelectasis',
'Pneumothorax',
'Pleural_Thickening',
'Pneumonia',
'Fibrosis',
'Edema',
'Consolidation']
def get_weighted_loss(pos_weights, neg_weights, epsilon=1e-7):
"""
Return weighted loss function given negative weights and positive weights.
Args:
pos_weights (np.array): array of positive weights for each class, size (num_classes)
neg_weights (np.array): array of negative weights for each class, size (num_classes)
Returns:
weighted_loss (function): weighted loss function
"""
def weighted_loss(y_true, y_pred):
"""
Return weighted loss value.
Args:
y_true (Tensor): Tensor of true labels, size is (num_examples, num_classes)
y_pred (Tensor): Tensor of predicted labels, size is (num_examples, num_classes)
Returns:
loss (float): overall scalar loss summed across all classes
"""
# initialize loss to zero
loss = 0.0
for i in range(len(pos_weights)):
positive_term_loss = pos_weights[i] * tf.cast(y_true[:,i], tf.float32) * K.log(y_pred[:,i] + epsilon)
negative_term_loss = neg_weights[i] * tf.cast((1-y_true[:,i]), tf.float32) * K.log(1-y_pred[:,i] + epsilon)
loss += -K.mean(positive_term_loss + negative_term_loss)
return loss
return weighted_loss
freq_neg = np.loadtxt('freq_neg.txt')
freq_pos = np.loadtxt('freq_pos.txt')
pos_weights = freq_neg
neg_weights = freq_pos
# create the base pre-trained model
base_model = DenseNet121(weights='./nih/densenet.hdf5', include_top=False)
x = base_model.output
# add a global spatial average pooling layer
x = GlobalAveragePooling2D()(x)
# and a logistic layer
predictions = Dense(len(med_labels), activation="sigmoid")(x)
model = Model(inputs=base_model.input, outputs=predictions)
model.compile(optimizer='adam', loss=get_weighted_loss(pos_weights, neg_weights))
model.load_weights("./nih/pretrained_model.h5")
import os
import tensorflow as tf
from tensorflow import keras
from IPython.display import Image, display
import matplotlib.cm as cm
def convert_preds(preds):
q = dict(zip(med_labels, preds[0]))
return q
# The Grad-CAM algorithm
def make_gradcam_heatmap(img_array, model, last_conv_layer_name, pred_index=None):
# First, we create a model that maps the input image to the activations
# of the last conv layer as well as the output predictions
grad_model = keras.models.Model(
model.inputs, [model.get_layer(last_conv_layer_name).output, model.output]
)
# Then, we compute the gradient of the top predicted class for our input image
# with respect to the activations of the last conv layer
with tf.GradientTape() as tape:
last_conv_layer_output, preds = grad_model(img_array)
if pred_index is None:
pred_index = tf.argmax(preds[0])
class_channel = preds[:, pred_index]
# This is the gradient of the output neuron (top predicted or chosen)
# with regard to the output feature map of the last conv layer
grads = tape.gradient(class_channel, last_conv_layer_output)
# This is a vector where each entry is the mean intensity of the gradient
# over a specific feature map channel
pooled_grads = tf.reduce_mean(grads, axis=(0, 1, 2))
# We multiply each channel in the feature map array
# by "how important this channel is" with regard to the top predicted class
# then sum all the channels to obtain the heatmap class activation
last_conv_layer_output = last_conv_layer_output[0]
heatmap = last_conv_layer_output @ pooled_grads[..., tf.newaxis]
heatmap = tf.squeeze(heatmap)
# For visualization purpose, we will also normalize the heatmap between 0 & 1
heatmap = tf.maximum(heatmap, 0) / tf.math.reduce_max(heatmap)
return heatmap.numpy()
# Create a superimposed visualization
def superimpose_gradcam(img_path, heatmap, alpha=0.5):
# Load the original image
img = keras.utils.load_img(img_path)
img = keras.utils.img_to_array(img)
# Rescale heatmap to a range 0-255
heatmap = np.uint8(255 * heatmap)
# Use jet colormap to colorize heatmap
jet = cm.get_cmap("jet")
# Use RGB values of the colormap
jet_colors = jet(np.arange(256))[:, :3]
jet_heatmap = jet_colors[heatmap]
# Create an image with RGB colorized heatmap
jet_heatmap = keras.utils.array_to_img(jet_heatmap)
jet_heatmap = jet_heatmap.resize((img.shape[1], img.shape[0]))
jet_heatmap = keras.utils.img_to_array(jet_heatmap)
# Superimpose the heatmap on original image
superimposed_img = jet_heatmap * alpha + img * 0.4
superimposed_img = keras.utils.array_to_img(superimposed_img)
return superimposed_img
# Save the superimposed image
# superimposed_img.save(cam_path)
# # Display Grad CAM
# display(Image(cam_path,width=300))
def pil_to_np(pil):
a = np.array(pil)
return a
def np_to_pil(a):
from PIL import Image
im = Image.fromarray(a) #, mode="RGB"
return im
from keras.preprocessing import image
def load_image_to_array(image_path, H=320, W=320):
pil = image.load_img(
image_path,
target_size=(H, W),
color_mode = 'rgb',
interpolation = 'nearest',
)
a = pil_to_np(pil)
return a
def normalize_array(a):
pil = np_to_pil(a)
mean = np.mean(pil)
std = np.std(pil)
pil -= mean
pil /= std
a2 = pil_to_np(pil)
a2 = np.expand_dims(a2, axis=0)
return a2
selected_keys = ['Cardiomegaly','Mass','Pneumothorax','Edema']
# selected_keys.append('Infiltration')
def print_selected(preds):
for k in selected_keys:
print('{:15}\t{:6.3f}'.format(k, preds[k]))
IMAGE_DIR = "nih/images-small/"
last_conv_layer_name = 'bn'
def med_classify_image(inp):
inp = load_image_to_array(inp)
inp = normalize_array(inp)
preds = model.predict(inp,verbose=0)
preds = convert_preds(preds)
preds = {key:value.item() for key, value in preds.items()}
return preds
def gradcam(inp):
selected_labels = [
(idx, label)
for idx, label in enumerate(med_labels)
if label in selected_keys]
img_array = load_image_to_array(inp)
img_array = normalize_array(img_array)
images = []
for k, l in selected_labels:
heatmap = make_gradcam_heatmap(img_array, model, last_conv_layer_name, pred_index = k)
superimposed_img = superimpose_gradcam(inp, heatmap)
images.append((superimposed_img,l))
return images
with gr.Blocks(css="footer {visibility: hidden}") as demo:
gr.Markdown('# Chest X-Ray Medical Diagnosis with Deep Learning')
with gr.Row():
input_image = gr.Image(label='Chest X-Ray',type='filepath',image_mode='L')
with gr.Column():
gr.Examples(
examples=[
"nih/images-small/00008270_015.png",
"nih/images-small/00011355_002.png",
"nih/images-small/00029855_001.png",
"nih/images-small/00005410_000.png",
],
inputs=input_image,
label='Examples'
# fn=mirror,
# cache_examples=True,
)
with gr.Column():
b1 = gr.Button("Classify")
b2 = gr.Button("Compute GradCam")
with gr.Row():
label = gr.Label(label='Classification',num_top_classes=5)
gallery = gr.Gallery(
label="GradCam",
show_label=True,
elem_id="gallery",
object_fit="scale-down",
height=400)
gr.Markdown(
"""
[ChestX-ray8 dataset](https://arxiv.org/abs/1705.02315)
[Download the entire dataset](https://nihcc.app.box.com/v/ChestXray-NIHCC)
""")
b1.click(med_classify_image, inputs=input_image, outputs=label)
b2.click(gradcam, inputs=input_image, outputs=gallery)
if __name__ == "__main__":
demo.launch()
|