Spaces:
Runtime error
Runtime error
Jamshaid89
commited on
Commit
•
ddf40f2
1
Parent(s):
110106a
Added heatmap
Browse files- app.py +116 -17
- cat_dog_recognition.h5 → model_weights.h5 +2 -2
- requirements.txt +2 -1
app.py
CHANGED
@@ -1,32 +1,131 @@
|
|
1 |
-
import
|
2 |
import tensorflow as tf
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
|
4 |
-
# def greet(name):
|
5 |
-
# return "Hello " + name + "!!"
|
6 |
|
7 |
-
|
8 |
-
|
9 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
10 |
|
11 |
-
|
|
|
|
|
|
|
|
|
|
|
12 |
|
13 |
-
#
|
14 |
-
|
|
|
|
|
|
|
15 |
|
16 |
-
|
17 |
-
|
18 |
-
# Return the predicted label
|
19 |
-
return predicted_label
|
20 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
|
|
|
|
|
|
|
22 |
|
23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
24 |
|
25 |
-
# iface = gr.Interface(fn=detect, inputs=input_image, outputs="text" , title="Cat vs Dog Detector")
|
26 |
-
# iface.launch()
|
27 |
|
28 |
image_input = gr.inputs.Image(shape=(160,160))
|
29 |
label_output = gr.outputs.Textbox()
|
|
|
|
|
30 |
|
31 |
# Create the Gradio interface
|
32 |
-
gr.Interface(fn=predict_image, inputs=image_input, outputs=label_output).launch()
|
|
|
1 |
+
import numpy as np
|
2 |
import tensorflow as tf
|
3 |
+
from tensorflow import keras
|
4 |
+
from keras.layers import Input , Lambda , Dense , Flatten , Rescaling
|
5 |
+
from keras.models import Model
|
6 |
+
# Display
|
7 |
+
from IPython.display import Image, display
|
8 |
+
import matplotlib.pyplot as plt
|
9 |
+
import matplotlib.cm as cm
|
10 |
|
|
|
|
|
11 |
|
12 |
+
##### Configureable variabels ###########
|
13 |
+
model_weights_path = "./model_weights.h5"
|
14 |
+
|
15 |
+
####################################################################
|
16 |
+
############ Creating new model #############################
|
17 |
+
####################################################################
|
18 |
+
base_model = keras.applications.Xception(input_shape=(160,160,3) , include_top=False)
|
19 |
+
base_model.trainable = False
|
20 |
+
|
21 |
+
def create_model():
|
22 |
+
input_layer = keras.Input(shape=(160,160,3))
|
23 |
+
if debug:
|
24 |
+
print(input_layer)
|
25 |
+
R1 = Rescaling(scale=1/255)(input_layer)
|
26 |
+
if debug:
|
27 |
+
print(R1)
|
28 |
+
B = base_model(R1 , training=False)
|
29 |
+
if debug:
|
30 |
+
print(B)
|
31 |
+
P1 = keras.layers.GlobalAveragePooling2D()(B)
|
32 |
+
if debug:
|
33 |
+
print(P1)
|
34 |
+
output_layer = Dense(1 , activation="sigmoid")(P1)
|
35 |
+
if debug:
|
36 |
+
print(f"output_layer: {output_layer}")
|
37 |
+
model = keras.Model(input_layer , output_layer)
|
38 |
+
model.compile(optimizer=keras.optimizers.Adam(0.001) , loss=keras.losses.BinaryCrossentropy() , metrics=["accuracy"])
|
39 |
+
return model , input_layer, R1 , B , P1 , output_layer
|
40 |
+
|
41 |
+
print("Creating new model ...")
|
42 |
+
model , input_layer , R1 , B , P1 , output_layer = create_model()
|
43 |
+
print("Loading weights ....")
|
44 |
+
model.load_weights(model_weights_path)
|
45 |
+
|
46 |
+
####################################################################
|
47 |
+
############ Creating gradcam model #########################
|
48 |
+
####################################################################
|
49 |
+
def make_gradcam_heatmap(img_array, model):
|
50 |
+
|
51 |
+
# we compute the gradient of the top predicted class for our input image
|
52 |
+
# with respect to the activations of the last conv layer
|
53 |
+
preds = None
|
54 |
+
with tf.GradientTape() as tape:
|
55 |
+
preds , last_conv_layer_output = grad_model(img_array)
|
56 |
+
|
57 |
+
# This is the gradient of the output neuron (top predicted or chosen)
|
58 |
+
# with regard to the output feature map of the last conv layer
|
59 |
+
grads = tape.gradient(preds, last_conv_layer_output)
|
60 |
+
|
61 |
+
# This is a vector where each entry is the mean intensity of the gradient
|
62 |
+
# over a specific feature map channel
|
63 |
+
pooled_grads = tf.reduce_mean(grads, axis=(0, 1, 2))
|
64 |
|
65 |
+
# We multiply each channel in the feature map array
|
66 |
+
# by "how important this channel is" with regard to the top predicted class
|
67 |
+
# then sum all the channels to obtain the heatmap class activation
|
68 |
+
last_conv_layer_output = last_conv_layer_output[0]
|
69 |
+
heatmap = last_conv_layer_output @ pooled_grads[..., tf.newaxis]
|
70 |
+
heatmap = tf.squeeze(heatmap)
|
71 |
|
72 |
+
# For visualization purpose, we will also normalize the heatmap between 0 & 1
|
73 |
+
heatmap = tf.maximum(heatmap, 0) / tf.math.reduce_max(heatmap)
|
74 |
+
return preds , heatmap.numpy()
|
75 |
+
|
76 |
+
def get_gradcam(img, heatmap , alpha=0.4):
|
77 |
|
78 |
+
# Rescale heatmap to a range 0-255
|
79 |
+
heatmap = np.uint8(255 * heatmap)
|
|
|
|
|
80 |
|
81 |
+
# Use jet colormap to colorize heatmap
|
82 |
+
jet = cm.get_cmap("jet")
|
83 |
+
|
84 |
+
# Use RGB values of the colormap
|
85 |
+
jet_colors = jet(np.arange(256))[:, :3]
|
86 |
+
jet_heatmap = jet_colors[heatmap]
|
87 |
+
|
88 |
+
# Create an image with RGB colorized heatmap
|
89 |
+
jet_heatmap = keras.utils.array_to_img(jet_heatmap)
|
90 |
+
jet_heatmap = jet_heatmap.resize((img.shape[1], img.shape[0]))
|
91 |
+
jet_heatmap = keras.utils.img_to_array(jet_heatmap)
|
92 |
+
|
93 |
+
# Superimpose the heatmap on original image
|
94 |
+
superimposed_img = jet_heatmap * alpha + img
|
95 |
+
superimposed_img = keras.utils.array_to_img(superimposed_img)
|
96 |
+
|
97 |
+
return superimposed_img
|
98 |
+
|
99 |
+
print("Creating Gradcam model ....")
|
100 |
+
grad_model = keras.Model(
|
101 |
+
input_layer , [output_layer , B]
|
102 |
+
)
|
103 |
+
grad_model.layers[-1].activation = None
|
104 |
+
grad_model.summary()
|
105 |
+
|
106 |
+
######################################################
|
107 |
+
def sigmoid(x):
|
108 |
+
return 1 / (1 + np.exp(-x))
|
109 |
+
#######################################################
|
110 |
+
def predict_image(image):
|
111 |
|
112 |
+
try:
|
113 |
+
pred , heatmap = make_gradcam_heatmap(image.reshape((1, 160, 160, 3)) , grad_model)
|
114 |
+
gradcam_image = get_gradcam(image , heatmap)
|
115 |
|
116 |
+
pred = sigmoid(pred)
|
117 |
+
predicted_label = f"{(1-pred[0][0])*100:.2f}% Dog \n{pred[0][0]*100:.2f}% Cat \nFinal Prediction : {'Dog' if pred[0][0] < 0.5 else 'Cat'}"
|
118 |
+
|
119 |
+
# Return the predicted label
|
120 |
+
return predicted_label , gradcam_image
|
121 |
+
except Exception as error:
|
122 |
+
return str(error)
|
123 |
|
|
|
|
|
124 |
|
125 |
image_input = gr.inputs.Image(shape=(160,160))
|
126 |
label_output = gr.outputs.Textbox()
|
127 |
+
label_output2 = gr.outputs.Textbox()
|
128 |
+
image_output = gr.outputs.Image(type="pil")
|
129 |
|
130 |
# Create the Gradio interface
|
131 |
+
gr.Interface(fn=predict_image, inputs=image_input, outputs=[label_output , image_output]).launch()
|
cat_dog_recognition.h5 → model_weights.h5
RENAMED
@@ -1,3 +1,3 @@
|
|
1 |
version https://git-lfs.github.com/spec/v1
|
2 |
-
oid sha256:
|
3 |
-
size
|
|
|
1 |
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:62588259941457684f5e9b3794b5198063ff0a8759a9415bde67715ca23e950f
|
3 |
+
size 83643024
|
requirements.txt
CHANGED
@@ -1,2 +1,3 @@
|
|
1 |
tensorflow
|
2 |
-
numpy
|
|
|
|
1 |
tensorflow
|
2 |
+
numpy
|
3 |
+
matplotlib
|