参考文献
#加载需要的包
#https://blog.csdn.net/weixin_42347070/article/details/106455763
#https://lime-ml.readthedocs.io/en/latest/lime.html?highlight=explanation.get_image_and_mask#lime.lime_image.ImageExplanation.get_image_and_mask
#https://github.com/marcotcr/lime/blob/master/doc/notebooks/Tutorial%20-%20Image%20Classification%20Keras.ipynb
#加载需要的包
import os import keras from keras.applications import inception_v3 as inc_net from keras.preprocessing import image from keras.applications.imagenet_utils import decode_predictions from skimage.io import imread import matplotlib.pyplot as plt import numpy as np print('Notebook run using keras:', keras.__version__) #下载Google Inception net-v3深度神经网络模型 inet_model = inc_net.InceptionV3() def transform_img_fn(path_list): out = [] for img_path in path_list: img = image.load_img(img_path, target_size=(299, 299)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = inc_net.preprocess_input(x) out.append(x) return np.vstack(out) images = transform_img_fn([os.path.join('./','1.png')])#图片可以下载一个猫,然后用电脑带的画图工具将像素变成299*299 plt.imshow(images[0] / 2 + 0.5) preds = inet_model.predict(images) for x in decode_predictions(preds)[0]: print(x)#输出预测结果 #加载lime包 import lime from lime import lime_image explainer = lime_image.LimeImageExplainer() x=images[0].astype(np.double) #lime要求numpy array #就是假设一共有1000类(1000个标签),我们只选择前5个概率大的进行分析,因此top lable=5,这个可以修改 explanation = explainer.explain_instance(x, inet_model.predict, top_labels=5, hide_color=0, num_samples=1000) from skimage.segmentation import mark_boundaries #找个不像很多教程说的那样,可以同时显示positive和negative的部分。其实,我发现一次要么只能显示negative模块,要么只能显示positive模块。 #什么绿色是positive,红色是negative应该是后期p或者拼接的。因为官网写的positive_only,negative_only不可用同时为true。 #positive_only,negative_only谁为true就显示谁。num_features为显示的模块个数。 #其实可以把num_features设置为1000,然后设定min_weight的一个阈值来筛选。 temp, mask = explanation.get_image_and_mask(explanation.top_labels[0], positive_only=False,negative_only=True,num_features=1, hide_rest=True,min_weight=0.0) plt.imshow(mark_boundaries(temp / 2 + 0.5, mask))
标签:img,keras,image,解释性,only,图像,import,LIME,lime From: https://www.cnblogs.com/nanhaijindiao/p/17145462.html