Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
X_train, X_test, y_train, y_test = train_test_split(X_vec, y_vec,
train_size=0.55)
simple_rf_pipeline.fit(X_train, y_train)
#%%
import os,sys
try:
import lime
except:
sys.path.append(os.path.join('..', '..')) # add the current directory
import lime
#%%
from lime import lime_image
from lime.wrappers.scikit_image import SegmentationAlgorithm
explainer = lime_image.LimeImageExplainer(verbose = False)
segmenter = SegmentationAlgorithm('quickshift', kernel_size=1, max_dist=200, ratio=0.2)
#%%
explanation = explainer.explain_instance(X_test[0],
classifier_fn = simple_rf_pipeline.predict_proba,
top_labels=10, hide_color=0, num_samples=10000, segmentation_fn=segmenter)
#%%
temp, mask = explanation.get_image_and_mask(y_test[0], positive_only=True, num_features=10, hide_rest=False, min_weight = 0.01)
fig, (ax1, ax2) = plt.subplots(1,2, figsize = (8, 4))
ax1.imshow(label2rgb(mask,temp, bg_label = 0), interpolation = 'nearest')
ax1.set_title('Positive Regions for {}'.format(y_test[0]))
temp, mask = explanation.get_image_and_mask(y_test[0], positive_only=False, num_features=10, hide_rest=False, min_weight = 0.01)
ax2.imshow(label2rgb(3-mask,temp, bg_label = 0), interpolation = 'nearest')
ax2.set_title('Positive/Negative Regions for {}'.format(y_test[0]))
def explain_multiple(model, img, topLabels, numSamples, numFeatures, hideRest, hideColor, positiveOnly):
img, oldImg = transform_img_fn(img)
img = img*(1./255)
prediction = model.predict(img)
explainer = lime_image.LimeImageExplainer()
img = np.squeeze(img)
explanation = explainer.explain_instance(img, model.predict, top_labels=topLabels, hide_color=hideColor, num_samples=numSamples)
topClasses = getTopXpredictions(prediction, topLabels)
explanations = []
for cl in topClasses:
temp, mask = explanation.get_image_and_mask(cl[0], positive_only=positiveOnly, num_features=numFeatures, hide_rest=hideRest)
imgExplained = mark_boundaries(temp, mask)
img = Image.fromarray(np.uint8(imgExplained*255))
imgByteArr = io.BytesIO()
img.save(imgByteArr, format='JPEG')
imgByteArr = imgByteArr.getvalue()
hide_rest = str(request.args.get("hiderest"))
# read the image in PIL format
image64 = flask.request.form.get("image")
image = base64.b64decode(image64)
image = Image.open(io.BytesIO(image))
with graph.as_default():
model_path = flask.request.form.get("model_path")
model = load_model(model_path)
img = prepare_image(image, (224, 224))
img = img*(1./255)
prediction = model.predict(img)
explainer = lime_image.LimeImageExplainer()
img = np.squeeze(img)
explanation = explainer.explain_instance(img, model.predict, top_labels=top_labels, hide_color=hide_color=="True", num_samples=num_samples)
top_classes = getTopXpredictions(prediction, top_labels)
explanations = []
for cl in top_classes:
temp, mask = explanation.get_image_and_mask(cl[0], positive_only=positive_only=="True", num_features=num_features, hide_rest=hide_rest=="True")
img_explained = mark_boundaries(temp, mask)
img = Image.fromarray(np.uint8(img_explained*255))
img_byteArr = io.BytesIO()
img.save(img_byteArr, format='JPEG')
img_byteArr = img_byteArr.getvalue()
img64 = base64.b64encode(img_byteArr)
def explain(modelPath, img):
modelPath = "C:/Users/Alex Heimerl/Desktop/test/vgg16_pokemon_100.h5"
model = load_model(modelPath)
img = img/255
prediction = model.predict(img)
explainer = lime_image.LimeImageExplainer()
explanation = explainer.explain_instance(np.squeeze(img), model.predict, top_labels=2, hide_color=0, num_samples=1000)
temp, mask = explanation.get_image_and_mask(getTopPrediction(prediction[0]), positive_only=True, num_features=50, hide_rest=True)
imgExplained = mark_boundaries(temp, mask)
img = Image.fromarray(np.uint8(imgExplained*255))
imgByteArr = io.BytesIO()
img.save(imgByteArr, format='JPEG')
imgByteArr = imgByteArr.getvalue()
return imgByteArr
hide_rest = str(request.args.get("hiderest"))
# read the image in PIL format
image64 = flask.request.form.get("image")
image = base64.b64decode(image64)
image = Image.open(io.BytesIO(image))
with graph.as_default():
model_path = flask.request.form.get("model_path")
model = load_model(model_path)
img = prepare_image(image, (224, 224))
img = img*(1./255)
prediction = model.predict(img)
explainer = lime_image.LimeImageExplainer()
img = np.squeeze(img)
explanation = explainer.explain_instance(img, model.predict, top_labels=top_labels, hide_color=hide_color=="True", num_samples=num_samples)
top_classes = getTopXpredictions(prediction, top_labels)
explanations = []
for cl in top_classes:
temp, mask = explanation.get_image_and_mask(cl[0], positive_only=positive_only=="True", num_features=num_features, hide_rest=hide_rest=="True")
img_explained = mark_boundaries(temp, mask)
img = Image.fromarray(np.uint8(img_explained*255))
img_byteArr = io.BytesIO()
img.save(img_byteArr, format='JPEG')
img_byteArr = img_byteArr.getvalue()
img64 = base64.b64encode(img_byteArr)
def explain(model, img, topLabels, numSamples, numFeatures, hideRest, hideColor, positiveOnly):
img, oldImg = transform_img_fn(img)
img = img*(1./255)
prediction = model.predict(img)
explainer = lime_image.LimeImageExplainer()
img = np.squeeze(img)
explanation = explainer.explain_instance(img, model.predict, top_labels=topLabels, hide_color=hideColor, num_samples=numSamples)
temp, mask = explanation.get_image_and_mask(getTopPrediction(prediction[0]), positive_only=positiveOnly, num_features=numFeatures, hide_rest=hideRest)
tempMask = mask * 255
temp = Image.fromarray(np.uint8(tempMask))
temp = temp.resize((oldImg.width, oldImg.height))
temp = image.img_to_array(temp)
temp = temp * 1./255
temp = temp.astype(np.int64)
temp = np.squeeze(temp)
oldImgArr = image.img_to_array(oldImg)
oldImgArr = oldImgArr * (1./255)
oldImgArr = oldImgArr.astype(np.float64)
imgExplained = mark_boundaries(oldImgArr, temp)
imgFinal = np.uint8(imgExplained*255)
img = Image.fromarray(imgFinal)
lime_BATCH = 500
try:
imgFile = cStringIO.StringIO(urllib.urlopen(image_url).read()) ## Download image.
except Exception as error:
print "--LOG--%s"%(str(datetime.datetime.now())), error
return np.zeros((224, 224, 3))
xImg = self.preprocess_image(imgFile) ## Load, pre-process image.
self.str_caption, self.caption = self.preprocess_caption(caption_string) ## Pre-process caption.
print "\n\t\tRunning LIME\n"
_st = time.time()
explainer = lime_image.LimeImageExplainer() ## LIME explainer.
explanation = explainer.explain_instance(
xImg,
self.predict,
top_labels=1, hide_color=0, batch_size=lime_BATCH, num_samples=5000, num_features=100
)
print "\n\t\tDONE. Took", (time.time() - _st)/60.0, "minutes.\n"
tmpImg, tmpMask = explanation.get_image_and_mask(
label=lime_BATCH-1, positive_only=True, num_features=10, hide_rest=True
)
return tmpMask
def __init__(self, *argv, **kwargs):
"""
Initialize lime Image explainer object
"""
super(LimeImageExplainer, self).__init__(*argv, **kwargs)
self.explainer = lime_image.LimeImageExplainer(*argv, **kwargs)
def explain_multiple(model, img, topLabels, numSamples, numFeatures, hideRest, hideColor, positiveOnly):
img, oldImg = transform_img_fn(img)
img = img*(1./255)
prediction = model.predict(img)
explainer = lime_image.LimeImageExplainer()
img = np.squeeze(img)
explanation = explainer.explain_instance(img, model.predict, top_labels=topLabels, hide_color=hideColor, num_samples=numSamples)
topClasses = getTopXpredictions(prediction, topLabels)
explanations = []
for cl in topClasses:
temp, mask = explanation.get_image_and_mask(cl[0], positive_only=positiveOnly, num_features=numFeatures, hide_rest=hideRest)
imgExplained = mark_boundaries(temp, mask)
img = Image.fromarray(np.uint8(imgExplained*255))
imgByteArr = io.BytesIO()
img.save(imgByteArr, format='JPEG')
imgByteArr = imgByteArr.getvalue()
def explain(model, img, topLabels, numSamples, numFeatures, hideRest, hideColor, positiveOnly):
img, oldImg = transform_img_fn(img)
img = img*(1./255)
prediction = model.predict(img)
explainer = lime_image.LimeImageExplainer()
img = np.squeeze(img)
explanation = explainer.explain_instance(img, model.predict, top_labels=topLabels, hide_color=hideColor, num_samples=numSamples)
temp, mask = explanation.get_image_and_mask(getTopPrediction(prediction[0]), positive_only=positiveOnly, num_features=numFeatures, hide_rest=hideRest)
tempMask = mask * 255
temp = Image.fromarray(np.uint8(tempMask))
temp = temp.resize((oldImg.width, oldImg.height))
temp = image.img_to_array(temp)
temp = temp * 1./255
temp = temp.astype(np.int64)
temp = np.squeeze(temp)
oldImgArr = image.img_to_array(oldImg)
oldImgArr = oldImgArr * (1./255)
oldImgArr = oldImgArr.astype(np.float64)
imgExplained = mark_boundaries(oldImgArr, temp)
imgFinal = np.uint8(imgExplained*255)
img = Image.fromarray(imgFinal)