Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Example code doesn't work #5

Closed
ghost opened this issue Sep 26, 2017 · 5 comments
Closed

Example code doesn't work #5

ghost opened this issue Sep 26, 2017 · 5 comments

Comments

@ghost
Copy link

ghost commented Sep 26, 2017

Hi. I tried to play with the same code, inception model graph and test image (doberman.png) which you provided in examples section as iPython notebook. But I got an error during making the prediction:

ValueError: Cannot feed value of shape (1, 252, 261, 4) for Tensor 'Placeholder:0', which has shape '(?, 299, 299, 3)'

Do you have any idea how to force example code to work?
Thanks.

# Boilerplate imports.
import tensorflow as tf
import numpy as np
import PIL.Image
from matplotlib import pylab as P
import pickle
import os
from subprocess import call
from tensorflow.contrib.slim.python.slim.nets import inception_v3
import saliency

slim = tf.contrib.slim

if not os.path.exists('models/research/slim'):
  call(["git", "clone", "https://github.com/tensorflow/models/"])
old_cwd = os.getcwd()
os.chdir('models/research/slim')
os.chdir(old_cwd)

# Boilerplate methods.
def ShowImage(im, title='', ax=None):
  if ax is None:
    P.figure()
  P.axis('off')
  im = ((im + 1) * 127.5).astype(np.uint8)
  P.imshow(im)
  P.title(title)

def ShowGrayscaleImage(im, title='', ax=None):
  if ax is None:
    P.figure()
  P.axis('off')

  P.imshow(im, cmap=P.cm.gray, vmin=0, vmax=1)
  P.title(title)

def ShowDivergingImage(grad, title='', percentile=99, ax=None):
  if ax is None:
    fig, ax = P.subplots()
  else:
    fig = ax.figure

  P.axis('off')
  divider = make_axes_locatable(ax)
  cax = divider.append_axes('right', size='5%', pad=0.05)
  im = ax.imshow(grad, cmap=P.cm.coolwarm, vmin=-1, vmax=1)
  fig.colorbar(im, cax=cax, orientation='vertical')
  P.title(title)

def LoadImage(file_path):
  im = PIL.Image.open(file_path)
  im = np.asarray(im)
  return im / 127.5 - 1.0

if not os.path.exists('inception_v3.ckpt'):
  call(["curl", "-O", "http://download.tensorflow.org/models/inception_v3_2016_08_28.tar.gz"])
  call(["tar", "-xvzf", "inception_v3_2016_08_28.tar.gz"])

ckpt_file = './inception_v3.ckpt'

graph = tf.Graph()

with graph.as_default():
  images = tf.placeholder(tf.float32, shape=(None, 299, 299, 3))

  with slim.arg_scope(inception_v3.inception_v3_arg_scope()):
    _, end_points = inception_v3.inception_v3(images, is_training=False, num_classes=1001)

    # Restore the checkpoint
    sess = tf.Session(graph=graph)
    saver = tf.train.Saver()
    saver.restore(sess, ckpt_file)

  # Construct the scalar neuron tensor.
  logits = graph.get_tensor_by_name('InceptionV3/Logits/SpatialSqueeze:0')
  neuron_selector = tf.placeholder(tf.int32)
  y = logits[0][neuron_selector]

  # Construct tensor for predictions.
  prediction = tf.argmax(logits, 1)

  # Load the image
im = LoadImage('./doberman.png')

# Show the image
ShowImage(im)

# Make a prediction.
prediction_class = sess.run(prediction, feed_dict = {images: [im]})[0]

print("Prediction class: " + str(prediction_class))  # Should be a doberman, class idx = 237
@joabim
Copy link

joabim commented Oct 6, 2017

What if you replace im = LoadImage('./doberman.png') with

im = PIL.Image.open('./doberman.png')
im = np.expand_dims(im, 0) # instate missing batch dimension
# im.shape == (1, 299, 299, 3)

# optional imshow
plt.imshow(im[0,:,:,:])
plt.show()

@aish-where-ya
Copy link

I am using tensorflow 2.x and the example code simple does not work. Anybody else facing the same issue?

@giangnguyen2412
Copy link

You can resize your image to (229,229) when testing.

@tolga-b
Copy link
Collaborator

tolga-b commented Jul 27, 2020

We unfortunately haven't had the chance to update this library to TF 2 and there are some internal calls that depend on TF 1 sessions. You should be able to use it with TF 1 still. One way I can imagine generalizing this library is to separate gradient computation code from saliency computation code (pass a gradient function separately) to make the library work with any python model.

@bwedin
Copy link
Collaborator

bwedin commented Jul 28, 2021

Examples/code overhauled in #49, issue is now obsolete.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants