我正在尝试运行一些代码。代码可在此处获取:https://github.com/ankurtaly/Integrated-Gradients/blob/master/attributions.ipynb
import numpy as np
import PIL.Image
import tensorflow as tf
from io import StringIO
from IPython.display import Image, display, HTML
MODEL_LOC='./InceptionModel/tensorflow_inception_graph.pb'
LABELS_LOC='./InceptionModel/imagenet_comp_graph_label_strings.txt'
def load_model():
'''Loads the Inception (v1) model and creates a TensorFlow session
for it.
'''
graph = tf.Graph()
cfg = tf.ConfigProto(gpu_options={'allow_growth':True})
sess = tf.InteractiveSession(graph=graph, config=cfg)
graph_def = tf.GraphDef.FromString(open(MODEL_LOC).read())
tf.import_graph_def(graph_def)
return sess, graph
def T(layer):
'''Helper for getting layer output tensor'''
return graph.get_tensor_by_name("import/%s:0"%layer)
def run_network(sess, tensor, images):
'''Helper for evaluating a tensor on a bunch of images
within a session.
'''
imagenet_mean = 117.0
return sess.run(tensor, {'import/input:0': [img - imagenet_mean for img in images]})
def top_label_and_score(img):
'''Returns the label and score of the object class
that receives the highest SOFTMAX score.
The provided image must of shape (224, 224, 3)
'''
# Evaluate the SOFTMAX output layer for the image and
# determine the label for the highest-scoring class
t_softmax = tf.reduce_mean(T('softmax2'), reduction_indices=0)
scores = run_network(sess, t_softmax, [img])
id = np.argmax(scores)
return labels[id], scores[id]
def output_label_tensor(label):
'''Returns a tensor (shape: scalar) representing the SOFTMAX
for a given label.
'''
lab_index = np.where(np.in1d(labels, [label]))[0][0]
t_softmax = tf.reduce_sum(T('softmax2'), reduction_indices=0)
return t_softmax[lab_index]
def gradients(img, label):
'''Returns attributions for the prediction label based
on just the gradients at the image.
Specifically, the method returns the dot product of the image
and the gradients of the provided prediction label (w.r.t. the
image).
The provided image must of shape (224, 224, 3), which is
also the shape of the returned attributions tensor.
'''
t_output = output_label_tensor(label) # shape: scalar
t_grad = tf.gradients(t_output, T('input'))[0]
grads = run_network(sess, t_grad, [img])
return img*grads[0]
def integrated_gradients(img, label, steps=50):
'''Returns attributions for the prediction label based
on integrated gradients at the image.
Specifically, the method returns the dot product of the image
and the average of the gradients of the prediction label (w.r.t.
the image) at uniformly spaced scalings of the provided image.
The provided image must of shape (224, 224, 3), which is
also the shape of the returned attributions tensor.
'''
t_output = output_label_tensor(label) # shape: scalar
t_grad = tf.gradients(t_output, T('input'))[0]
scaled_images = [(float(i)/steps)*img for i in range(1, steps+1)]
# Compute the gradients of the scaled images
grads = run_network(sess, t_grad, scaled_images)
return img*np.average(grads, axis=0)
def pil_img(a):
'''Returns a PIL image created from the provided RGB array.
'''
a = np.uint8(a)
return PIL.Image.fromarray(a)
def show_img(img, fmt='jpeg'):
'''Displays the provided PIL image
'''
f = StringIO()
img.save(f, fmt)
display(Image(data=f.getvalue()))
def gray_scale(img):
'''Converts the provided RGB image to gray scale.
'''
img = np.average(img, axis=2)
return np.transpose([img, img, img], axes=[1,2,0])
def normalize(attrs, ptile=99):
'''Normalize the provided attributions so that they fall between
-1.0 and 1.0.
'''
h = np.percentile(attrs, ptile)
l = np.percentile(attrs, 100-ptile)
return np.clip(attrs/max(abs(h), abs(l)), -1.0, 1.0)
def visualize_attrs_windowing(img, attrs, ptile=99):
'''Visaualizes the provided attributions by first aggregating them
along the color channel to obtain per-pixel attributions and then
scaling the intensities of the pixels in the original image in
proportion to absolute value of these attributions.
The provided image and attributions must of shape (224, 224, 3).
'''
attrs = gray_scale(attrs)
attrs = abs(attrs)
attrs = np.clip(attrs/np.percentile(attrs, ptile), 0,1)
vis = img*attrs
show_img(pil_img(vis))
R=np.array([255,0,0])
G=np.array([0,255,0])
B=np.array([0,0,255])
def visualize_attrs_overlay(img, attrs, pos_ch=G, neg_ch=R, ptile=99):
'''Visaualizes the provided attributions by first aggregating them
along the color channel and then overlaying the positive attributions
along pos_ch, and negative attributions along neg_ch.
The provided image and attributions must of shape (224, 224, 3).
'''
attrs = gray_scale(attrs)
attrs = normalize(attrs, ptile)
pos_attrs = attrs * (attrs >= 0.0)
neg_attrs = -1.0 * attrs * (attrs < 0.0)
attrs_mask = pos_attrs*pos_ch + neg_attrs*neg_ch
vis = 0.3*gray_scale(img) + 0.7*attrs_mask
show_img(pil_img(vis))
# Load the Inception model.
sess, graph = load_model()
# Load the labels vocabulary.
labels = np.array(open(LABELS_LOC).read().split('\n'))
# Load the image.
with open('./Images/70bfca4555cca92e.jpg') as f:
img = f.read()
img = sess.run(tf.image.decode_jpeg(img))
show_img(pil_img(img))
我收到错误:
---------------------------------------------------------------------------
UnicodeDecodeError Traceback (most recent call last)
<ipython-input-4-c48fdf3979cf> in <module>()
1 # Load the Inception model.
----> 2 sess, graph = load_model()
3
4 # Load the labels vocabulary.
5 labels = np.array(open(LABELS_LOC).read().split('\n'))
<ipython-input-3-a6d3666d440b> in load_model()
8 cfg = tf.ConfigProto(gpu_options={'allow_growth':True})
9 sess = tf.InteractiveSession(graph=graph, config=cfg)
---> 10 graph_def = tf.GraphDef.FromString(open(MODEL_LOC).read())
11 tf.import_graph_def(graph_def)
12 return sess, graph
C:\Program Files\Anaconda3\envs\py35\lib\encodings\cp1252.py in decode(self, input, final)
21 class IncrementalDecoder(codecs.IncrementalDecoder):
22 def decode(self, input, final=False):
---> 23 return codecs.charmap_decode(input,self.errors,decoding_table)[0]
24
25 class StreamWriter(Codec,codecs.StreamWriter):
UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 175: character maps to <undefined>
我尝试了常用的修复方法,在打开文件时将编码设置为utf-8并在读取模式下打开,但没有任何工作。
如何修复错误?我正在使用Python 3.5。