在Tensorflow中将图像传递给模型后没有进行分类

时间:2016-03-30 10:01:31

标签: tensorflow tensorflow-serving

我正在尝试通过遵循2_fullyconnected.ipynb udacity分配将图像传递给我创建的模型。

我创建模型的代码如下所示。

# 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})

当我在这个ipython笔记本中执行ln [34]时,即将出现的输出是:

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

我想告诉给定图像可能属于的5个可能标签,但不知道如何操作,上述程序没有显示任何错误,但都没有显示所需的输出。我想我会得到图像在所有类中的概率,因为我在tf.nn.softmax函数中传递了我的图像,但遗憾的是没有得到任何东西。

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:2)

代码中的以下行计算数据集中每个图像的可能输出标签的概率分布(在本例中为单个图像):

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

此方法的结果是形状为(1, 10)的NumPy数组。要查看概率,您只需打印数组:

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

您可以通过多种方式获取图片的顶级 k 预测。最简单的方法之一是在定义图表时使用TensorFlow的tf.nn.top_k()运算符:

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)