После передачи изображения в модель в Tensorflow классификация не выполняется.

Я пытаюсь передать изображение модели, которую я создал, следуя заданию udacity 2_fullconnected.ipynb.

Код, в котором я создал модель, показан ниже.

# In[1]:

from __future__ import print_function
import numpy as np
import tensorflow as tf
from six.moves import cPickle as pickle
from six.moves import range


# First reload the data we generated in `1_notmnist.ipynb`.

# In[2]:

pickle_file = 'notMNIST.pickle'

with open(pickle_file, 'rb') as f:
  save = pickle.load(f)
  train_dataset = save['train_dataset']
  train_labels = save['train_labels']
  valid_dataset = save['valid_dataset']
  valid_labels = save['valid_labels']
  test_dataset = save['test_dataset']
  test_labels = save['test_labels']
  del save  # hint to help gc free up memory
  print('Training set', train_dataset.shape, train_labels.shape)
  print('Validation set', valid_dataset.shape, valid_labels.shape)
  print('Test set', test_dataset.shape, test_labels.shape)
  print(train_dataset[0])
  print(train_labels[0])


# Reformat into a shape that's more adapted to the models we're going to train:
# - data as a flat matrix,
# - labels as float 1-hot encodings.

# In[3]:

image_size = 28
num_labels = 10

def reformat(dataset, labels):
  print(type(dataset))
  #print(dataset[0])
  dataset = dataset.reshape((-1, image_size * image_size)).astype(np.float32)
  # Map 0 to [1.0, 0.0, 0.0 ...], 1 to [0.0, 1.0, 0.0 ...]
  labels = (np.arange(num_labels) == labels[:,None]).astype(np.float32)
  return dataset, labels
train_dataset, train_labels = reformat(train_dataset, train_labels)
valid_dataset, valid_labels = reformat(valid_dataset, valid_labels)
test_dataset, test_labels = reformat(test_dataset, test_labels)
print('Training set', train_dataset.shape, train_labels.shape)
print('Validation set', valid_dataset.shape, valid_labels.shape)
print('Test set', test_dataset.shape, test_labels.shape)


#stochastic gradient descent training

# In[7]:

batch_size = 128

graph = tf.Graph()
with graph.as_default():

  # Input data. For the training data, we use a placeholder that will be fed
  # at run time with a training minibatch.
  tf_train_dataset = tf.placeholder(tf.float32,
                                    shape=(batch_size, image_size * image_size))
  tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels))
  tf_valid_dataset = tf.constant(valid_dataset)
  tf_test_dataset = tf.constant(test_dataset)

  # Variables.
  weights = tf.Variable(
    tf.truncated_normal([image_size * image_size, num_labels]),name = "weights")
  biases = tf.Variable(tf.zeros([num_labels]),name ="biases")

  # Training computation.
  logits = tf.matmul(tf_train_dataset, weights) + biases
  loss = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels))

  # Optimizer.
  optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss)

  # Predictions for the training, validation, and test data.
  train_prediction = tf.nn.softmax(logits)
  valid_prediction = tf.nn.softmax(
    tf.matmul(tf_valid_dataset, weights) + biases)
  test_prediction = tf.nn.softmax(tf.matmul(tf_test_dataset, weights) + biases)


# In[9]:

def accuracy(predictions, labels):
  return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1))
          / predictions.shape[0])


# Let's run it:

# In[10]:

num_steps = 3001

with tf.Session(graph=graph) as session:
  tf.initialize_all_variables().run()
  print("Initialized")
  for step in range(num_steps):
    # Pick an offset within the training data, which has been randomized.
    # Note: we could use better randomization across epochs.
    offset = (step * batch_size) % (train_labels.shape[0] - batch_size)
    # Generate a minibatch.
    batch_data = train_dataset[offset:(offset + batch_size), :]
    batch_labels = train_labels[offset:(offset + batch_size), :]
    # Prepare a dictionary telling the session where to feed the minibatch.
    # The key of the dictionary is the placeholder node of the graph to be fed,
    # and the value is the numpy array to feed to it.
    feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels}
    _, l, predictions = session.run(
      [optimizer, loss, train_prediction], feed_dict=feed_dict)
    if (step % 500 == 0):
      print("Minibatch loss at step %d: %f" % (step, l))
      print("Minibatch accuracy: %.1f%%" % accuracy(predictions, batch_labels))
      print("Validation accuracy: %.1f%%" % accuracy(
        valid_prediction.eval(), valid_labels))
  print("Test accuracy: %.1f%%" % accuracy(test_prediction.eval(), test_labels))
  save_path = tf.train.Saver().save(session, "/tmp/important_model/model.ckpt")
  print("Model saved in file: %s" % save_path)

Модель сохраняется в /tmp/important_model/.

Древовидная структура этой папки выглядит следующим образом:

important_model/
|-- checkpoint
|-- model.ckpt
`-- model.ckpt.meta

Теперь я создаю новый файл, в котором пытаюсь восстановить свою модель, а затем передаю изображение в модель для классификации.

Я также создал график в новом файле python, который необходим для восстановления модели (думаю, я могу ошибаться. Пожалуйста, поправьте меня, если я ошибаюсь).

# In[16]:

# These are all the modules we'll be using later. Make sure you can import them
# before proceeding further.
from __future__ import print_function
import numpy as np
import tensorflow as tf
from six.moves import cPickle as pickle
from six.moves import range
from scipy import ndimage


# In[17]:

image_size = 28
num_labels = 10


# In[25]:

# With gradient descent training, even this much data is prohibitive.
# Subset the training data for faster turnaround.
#train_subset = 1000

batch_size = 1

graph = tf.Graph()
with graph.as_default():

  # Variables.
  # These are the parameters that we are going to be training. The weight
  # matrix will be initialized using random valued following a (truncated)
  # normal distribution. The biases get initialized to zero.
  # Variables.
  #saver = tf.train.Saver()
  weights = tf.Variable(
    tf.truncated_normal([image_size * image_size, num_labels]),name = "weights")
  biases = tf.Variable(tf.zeros([num_labels]),name ="biases")

  tf_valid_dataset = tf.placeholder(tf.float32,
                                    shape=(batch_size, image_size * image_size))
  valid_prediction = tf.nn.softmax(
    tf.matmul(tf_valid_dataset, weights) + biases)


# In[26]:

def accuracy(predictions, labels):
  return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1))
          / predictions.shape[0])


# In[34]:

pixel_depth = 255
image_data = (ndimage.imread('notMNIST_small/A/QXJyaWJhQXJyaWJhU3RkLm90Zg==.png').astype(float) - 
                    pixel_depth / 2) / pixel_depth
print(image_data.shape)
resized_data = image_data.reshape((-1,784))
print(resized_data.shape)

with tf.Session(graph=graph) as session:
  tf.train.Saver().restore(session, "/tmp/important_model/model.ckpt")
  print("Model restored.")
  session.run(valid_prediction,feed_dict={tf_valid_dataset:resized_data})

Когда я выполняю ln[34] в этом ноутбуке ipython, выводится следующее:

(28, 28)
(1, 784)
Model restored

Я хочу указать 5 вероятных меток, которым может принадлежать данное изображение, но не знаю, как это сделать. Вышеприведенная программа не показывает никаких ошибок, но и не показывает желаемый результат. Я думал, что получу вероятность того, что изображение будет во всех классах, поскольку я передал свое изображение в функцию tf.nn.softmax, но, к сожалению, ничего не получил.

Любая помощь будет оценена по достоинству.


person kkk    schedule 30.03.2016    source источник


Ответы (1)


Следующая строка в вашем коде вычисляет распределение вероятностей по возможным выходным меткам для каждого изображения в вашем наборе данных (в данном случае для одного изображения):

session.run(valid_prediction,feed_dict={tf_valid_dataset:resized_data})

Результатом этого метода является массив NumPy формы (1, 10). Чтобы увидеть вероятности, вы можете просто распечатать массив:

result = session.run(valid_prediction,feed_dict={tf_valid_dataset:resized_data})
print(result)

Есть много способов получить первые k подсказки для вашего изображения. Одним из самых простых является использование tf.nn.top_k() TensorFlow. оператор при определении вашего графика:

valid_prediction = tf.nn.softmax(tf.matmul(tf_valid_dataset, weights) + biases)
top_5_labels = tf.nn.top_k(valid_prediction, k=5)

# ...
result = session.run(top_5_labels, feed_dict={tf_valid_dataset: resized_data})
print(result)
person mrry    schedule 30.03.2016
comment
Спасибо за вашу помощь . Это работает сейчас. Почему нам нужно снова определить график в файле python, в котором мы восстанавливаем модель?? . Я все еще этого не понял. - person kkk; 31.03.2016
comment
Существует экспериментальная поддержка для автоматического выполнения этого с помощью tf.MetaGraphDef (который также генерируется кодом контрольных точек), но, вероятно, он еще не совсем готов для использования в прайм-тайм. Хотя дела постоянно улучшаются! - person mrry; 31.03.2016