demo5.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. #!/usr/bin/env python
  2. # -*- encoding: utf-8 -*-
  3. """
  4. @Contact : liuyuqi.gov@msn.cn
  5. @Time : 2024/06/04
  6. @License : Copyright © 2017-2022 liuyuqi. All Rights Reserved.
  7. @Desc :
  8. """
  9. import numpy as np
  10. import tensorflow as tf
  11. from deepexplain.tensorflow import DeepExplain
  12. from tensorflow.keras import backend as K
  13. from tensorflow.keras.models import Sequential, Model
  14. import gradio as gr
  15. model = tf.keras.applications.MobileNet()
  16. def saliency(model, x, y):
  17. y = y.reshape(1, 1, 1, 1000)
  18. with DeepExplain(session=K.get_session()) as de:
  19. input_tensor = model.layers[0].input
  20. fModel = Model(inputs=input_tensor, outputs = model.layers[-3].output)
  21. target_tensor = fModel(input_tensor)
  22. attributions_gradin = de.explain('grad*input', target_tensor, input_tensor, x, ys=y)
  23. sal = np.sum(np.abs(attributions_gradin.squeeze()), axis=-1)
  24. sal = (sal - sal.min()) / (sal.max() - sal.min())
  25. return sal
  26. inp = gr.inputs.ImageUpload()
  27. out = gr.outputs.Label(label_names='imagenet1000', max_label_words=1, word_delimiter=",")
  28. io = gr.Interface(inputs=inp,
  29. outputs=out,
  30. model=model,
  31. model_type='keras',
  32. saliency=saliency)
  33. io.launch();