每次我尝试在示例tf.layers中进行单个图像预测时,我得到相同的错误输出。我做错了什么?

时间:2018-02-27 17:07:35

标签: python tensorflow machine-learning mnist

我已经使用mnist训练数据和所有这些来复制Tensorflow教程中基于逐字逐句使用tf.layers的代码。培训和评估代码,预测字典和评估指标都保持不变。我遇到的问题是,我已经在我自己的所有图像上获得了非常不规则的输出,我试图将其输入网络并获得预测。到目前为止,我遇到了两个主要问题:

1)我单独提供给网络的每个图像(在修改它们之后,如第2点所示)不断给我一个输出:class [8]。这意味着网络将其识别为数字' 8'不是吗?我尝试输入4,7,0等等,但每次读取为8时。奇怪的是,经过培训,网络声称具有非常高的准确度等级,但它没有甚至为不同的输入数字提供不同的输出。我想知道我到底出了什么问题。

2)我正在使用opencv imread函数读取.jpg图像并首先将其转换为float 64(使用scikit-image),然后将我的图像转换为具有numpy astype的float 32图像。我这样做是为了让预测真正得以实现。出于某种原因,网络拒绝预测我的常规uint8图像,该图像最初由opencv读取。错误消息表明它只会将float16,bfloat16或float32类型的图像作为输入。

无论如何,这就是为什么我试图尽可能地调整原始图像,并在视觉上验证图像与原始输入图像相比似乎没有变化。因此,使用float32图像输入,程序给了我输出,但它们都是相同的(都是类[8]),我认为我在代码中的某个地方犯了一个错误。

这是源代码,我自己的tf.estimator.predict()。我在Windows 10上使用的是Python 3.6.3,如果相关则为64位。

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np
import tensorflow as tf
import cv2
import skimage


tf.logging.set_verbosity(tf.logging.INFO)


image1=cv2.imread("E:\Predict_images\image (5).jpg")
image2=skimage.util.img_as_float(image1)
image3=image2.astype(np.float32)
cv2.imshow('image1',image1)
cv2.imshow('image2',image2)
cv2.imshow('image 3',image3)

def cnn_model_fn(features, labels, mode):
  """Model function for CNN."""
  # Input Layer
  # Reshape X to 4-D tensor: [batch_size, width, height, channels]
  # MNIST images are 28x28 pixels, and have one color channel
  input_layer = tf.reshape(features["x"], [-1, 28, 28, 1])

  # Convolutional Layer #1
  # Computes 32 features using a 5x5 filter with ReLU activation.
  # Padding is added to preserve width and height.
  # Input Tensor Shape: [batch_size, 28, 28, 1]
  # Output Tensor Shape: [batch_size, 28, 28, 32]
  conv1 = tf.layers.conv2d(
      inputs=input_layer,
      filters=32,
      kernel_size=[5, 5],
      padding="same",
      activation=tf.nn.relu)

  # Pooling Layer #1
  # First max pooling layer with a 2x2 filter and stride of 2
  # Input Tensor Shape: [batch_size, 28, 28, 32]
  # Output Tensor Shape: [batch_size, 14, 14, 32]
  pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2)

  # Convolutional Layer #2
  # Computes 64 features using a 5x5 filter.
  # Padding is added to preserve width and height.
  # Input Tensor Shape: [batch_size, 14, 14, 32]
  # Output Tensor Shape: [batch_size, 14, 14, 64]
  conv2 = tf.layers.conv2d(
      inputs=pool1,
      filters=64,
      kernel_size=[5, 5],
      padding="same",
      activation=tf.nn.relu)

  # Pooling Layer #2
  # Second max pooling layer with a 2x2 filter and stride of 2
  # Input Tensor Shape: [batch_size, 14, 14, 64]
  # Output Tensor Shape: [batch_size, 7, 7, 64]
  pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2)

  # Flatten tensor into a batch of vectors
  # Input Tensor Shape: [batch_size, 7, 7, 64]
  # Output Tensor Shape: [batch_size, 7 * 7 * 64]
  pool2_flat = tf.reshape(pool2, [-1, 7 * 7 * 64])

  # Dense Layer
  # Densely connected layer with 1024 neurons
  # Input Tensor Shape: [batch_size, 7 * 7 * 64]
  # Output Tensor Shape: [batch_size, 1024]
  dense = tf.layers.dense(inputs=pool2_flat, units=1024, activation=tf.nn.relu)

  # Add dropout operation; 0.6 probability that element will be kept
  dropout = tf.layers.dropout(
      inputs=dense, rate=0.4, training=mode == tf.estimator.ModeKeys.TRAIN)

  # Logits layer
  # Input Tensor Shape: [batch_size, 1024]
  # Output Tensor Shape: [batch_size, 10]
  logits = tf.layers.dense(inputs=dropout, units=10)

  predictions = {
      # Generate predictions (for PREDICT and EVAL mode)
      "classes": tf.argmax(input=logits, axis=1),
      # Add `softmax_tensor` to the graph. It is used for PREDICT and by the
      # `logging_hook`.
      "probabilities": tf.nn.softmax(logits, name="softmax_tensor")
  }
  if mode == tf.estimator.ModeKeys.PREDICT:
    return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)

  # Calculate Loss (for both TRAIN and EVAL modes)
  loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits)

  # Configure the Training Op (for TRAIN mode)
  if mode == tf.estimator.ModeKeys.TRAIN:
    optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001)
    train_op = optimizer.minimize(
        loss=loss,
        global_step=tf.train.get_global_step())
    return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op)

  # Add evaluation metrics (for EVAL mode)
  eval_metric_ops = {
      "accuracy": tf.metrics.accuracy(
          labels=labels, predictions=predictions["classes"])}
  return tf.estimator.EstimatorSpec(
      mode=mode, loss=loss, eval_metric_ops=eval_metric_ops)


def main(unused_argv):
  # Load training and eval data
  mnist = tf.contrib.learn.datasets.load_dataset("mnist")
  train_data = mnist.train.images  # Returns np.array
  train_labels = np.asarray(mnist.train.labels, dtype=np.int32)
  eval_data = mnist.test.images  # Returns np.array
  eval_labels = np.asarray(mnist.test.labels, dtype=np.int32)

  # Create the Estimator
  mnist_classifier = tf.estimator.Estimator(
      model_fn=cnn_model_fn, model_dir="/tmp/mnist_convnet_model")

  # Set up logging for predictions
  # Log the values in the "Softmax" tensor with label "probabilities"
  tensors_to_log = {"probabilities": "softmax_tensor"}
  logging_hook = tf.train.LoggingTensorHook(
      tensors=tensors_to_log, every_n_iter=50)

  # Train the model
  train_input_fn = tf.estimator.inputs.numpy_input_fn(
      x={"x": train_data},
      y=train_labels,
      batch_size=100,
      num_epochs=None,
      shuffle=True)
  mnist_classifier.train(
      input_fn=train_input_fn,
      steps=20000,
      hooks=[logging_hook])

  # Evaluate the model and print results
  eval_input_fn = tf.estimator.inputs.numpy_input_fn(
      x={"x": eval_data},
      y=eval_labels,
      num_epochs=1,
      shuffle=False)
  eval_results = mnist_classifier.evaluate(input_fn=eval_input_fn)
  print(eval_results)

  #Predict the result for new images
  pred_input_fn=tf.estimator.inputs.numpy_input_fn(
    x={"x": image3},
    shuffle=False)
  pred = mnist_classifier.predict(input_fn=pred_input_fn)
  print (list(pred))

if __name__ == "__main__":
  tf.app.run()

当我通过它运行这个It's an image of '1' float 32图像时,这是shell中给出的输出:

INFO:tensorflow:Saving checkpoints for 20000 into /tmp/mnist_convnet_model\model.ckpt.
INFO:tensorflow:Loss for final step: 0.040543813.
INFO:tensorflow:Starting evaluation at 2018-02-25-19:40:57
INFO:tensorflow:Restoring parameters from /tmp/mnist_convnet_model\model.ckpt-20000
INFO:tensorflow:Finished evaluation at 2018-02-25-19:40:59
INFO:tensorflow:Saving dict for global step 20000: accuracy = 0.9717, global_step = 20000, loss = 0.09776818
{'accuracy': 0.9717, 'loss': 0.09776818, 'global_step': 20000}
INFO:tensorflow:Restoring parameters from /tmp/mnist_convnet_model\model.ckpt-20000
[{'classes': 8, 'probabilities': array([4.6938831e-07, 3.4720117e-07, 5.8355248e-03, 7.6848278e-03,
   1.0895459e-06, 2.9385969e-06, 1.8598693e-06, 1.2013125e-09,
   9.8647296e-01, 5.2439987e-08], dtype=float32)}, {'classes': 8, 'probabilities': array([4.8870197e-07, 3.7765903e-07, 6.4324187e-03, 8.6945957e-03,
   6.3728720e-07, 3.2801559e-06, 1.5783016e-06, 1.3214099e-09,
   9.8486656e-01, 5.1528065e-08], dtype=float32)}, {'classes': 8, 'probabilities': array([5.9954516e-07, 3.2683863e-07, 7.1799601e-03, 8.4864357e-03,
   8.9206560e-07, 2.3296870e-06, 1.4247992e-06, 9.8779152e-10,
   9.8432791e-01, 7.0583980e-08], dtype=float32)}]

编辑:我只是留下了一些我用来尝试做出预测的样本图片。所有这些都显示为8级。

Two Six Three Four

1 个答案:

答案 0 :(得分:0)

我确实遇到了你所描述的问题。我也希望有人能分享他/她的想法。训练的测试图像是黑色底色,图形是白色。但是一旦我用我的数据预测模型,它总是显示错误的数字。我试图改变背景颜色,但它预测不对。训练后即使准确度也相当不错。图像是从网络资源中收集并由我自己绘制的,它清晰可读且符合条件。我在这里粘贴了我的预测代码:

import tensorflow as tf
import pandas as pd
from cnn_mnist import cnn_model_fn
import numpy as np
import cv2

# Predict the image
#mnist = tf.contrib.learn.datasets.load_dataset("mnist")
#train_labels = np.asarray(mnist.train.labels, dtype=np.int32)
#eval_data = mnist.test.images
model = cnn_model_fn
mnist_classifier = tf.estimator.Estimator(
     model_fn=model, model_dir="/tmp/mnist_convnet_model")

im = cv2.imread("D:\\tf_exe_2\\img_9.jpg")
#im2 = np.reshape(im, [-1, 28, 28, 1])
pred_input_fn = tf.estimator.inputs.numpy_input_fn(
    x={"x": np.float32(im)}, 
    shuffle=False)
pred = list(mnist_classifier.predict(input_fn=pred_input_fn))
for el in pred:
    print(el)
#print(next(pred))

结果是错误的。它应该在图像内容中为零。

==================== RESTART: D:\tf_exe_2\cnn_predict.py ====================
INFO:tensorflow:Using default config.
INFO:tensorflow:Using config: {'_keep_checkpoint_every_n_hours': 10000, '_service': None, '_task_id': 0, '_session_config': None, '_log_step_count_steps': 100, '_save_checkpoints_steps': None, '_save_summary_steps': 100, '_keep_checkpoint_max': 5, '_tf_random_seed': None, '_num_worker_replicas': 1, '_model_dir': '/tmp/mnist_convnet_model', '_num_ps_replicas': 0, '_task_type': 'worker', '_is_chief': True, '_save_checkpoints_secs': 600, '_cluster_spec': <tensorflow.python.training.server_lib.ClusterSpec object at 0x000001B2CD51E588>, '_master': ''}
INFO:tensorflow:Restoring parameters from /tmp/mnist_convnet_model\model.ckpt-21020
{'probabilities': array([0., 0., 1., 0., 0., 0., 0., 0., 0., 0.], dtype=float32), 'classes': 2}
{'probabilities': array([0., 0., 0., 0., 0., 0., 0., 0., 1., 0.], dtype=float32), 'classes': 8}
{'probabilities': array([0., 0., 0., 0., 0., 0., 0., 0., 1., 0.], dtype=float32), 'classes': 8}
>>> 

所有培训步骤和配置都遵循Tensorflow教程。也许它会尝试继续修改训练参数,例如shuffle或其他配置?

这是cnn_mnist.py,与TensorFlow教程完全相同:

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

#imports
import numpy as np
import tensorflow as tf

tf.logging.set_verbosity(tf.logging.INFO)

def cnn_model_fn(features, labels, mode):
    """Model function for CNN"""
    #Input Layer
    input_layer = tf.reshape(features["x"], [-1,28,28,1])
    #Convolutional Layer #1
    conv1 = tf.layers.conv2d(
        inputs = input_layer,
        filters = 32,
        kernel_size=[5,5],
        padding = "same",
        activation=tf.nn.relu)

    #Pooling Layer #1
    pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2,2], strides=2)

    #Convolutional Layer #2 and Pooling Layer #2
    conv2 = tf.layers.conv2d(
        inputs=pool1,
        filters=64,
        kernel_size=[5,5],
        padding="same",
        activation=tf.nn.relu)
    pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2,2], strides=2)

    #Dense Layer
    pool2_flat = tf.reshape(pool2, [-1,7*7*64])
    dense = tf.layers.dense(inputs=pool2_flat, units=1024, activation=tf.nn.relu)
    dropout = tf.layers.dropout(
        inputs=dense, rate=0.4, training=mode == tf.estimator.ModeKeys.TRAIN)

    #Logits Layer
    logits = tf.layers.dense(inputs=dropout, units=10)

    predictions = {
        #Generate predictions (for PREDICT and EVAL mode)
        "classes": tf.argmax(input=logits, axis=1),
        #Add 'softmax_tensor' to the graph. It is used for PREDICT and by the
        #'logging_hook'
        "probabilities": tf.nn.softmax(logits, name="softmax_tensor")
    }

    if mode == tf.estimator.ModeKeys.PREDICT:
        return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)

    # Calculate Loss (for both TRAIN and EVAL modes
    loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits)


# Configure the Training Op (for TRAIN mode)
    if mode == tf.estimator.ModeKeys.TRAIN:
        optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001)
        train_op = optimizer.minimize(
            loss=loss,
            global_step=tf.train.get_global_step())
        return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op)

    # Add evaluation metrics (for EVAL mode)
    eval_metric_ops = {
        "accuracy": tf.metrics.accuracy(
            labels=labels, predictions=predictions["classes"])}
    return tf.estimator.EstimatorSpec(
        mode=mode, loss=loss,eval_metric_ops=eval_metric_ops)

def main(unused_argv):
    #Load training and eval data
    mnist = tf.contrib.learn.datasets.load_dataset("mnist")
    train_data = mnist.train.images
    train_labels = np.asarray(mnist.train.labels, dtype=np.int32)
    eval_data = mnist.test.images
    eval_labels = np.asarray(mnist.test.labels, dtype=np.int32)
    #Create the Estimator
    mnist_classifier = tf.estimator.Estimator(
        model_fn=cnn_model_fn, model_dir="/tmp/mnist_convnet_model")
    # Set up logging for predictions
    tensor_to_log = {"probabilities": "softmax_tensor"}
    logging_hook = tf.train.LoggingTensorHook(
        tensors=tensor_to_log, every_n_iter=50)
    # Train the model
    train_input_fn = tf.estimator.inputs.numpy_input_fn(
        x={"x": train_data},
        y=train_labels,
        batch_size=100,
        num_epochs=None,
        shuffle=True)
    mnist_classifier.train(
        input_fn=train_input_fn,
        #original steps are 20000
        steps=20000, 
        hooks=[logging_hook])
    # Evaluate the model and print results
    eval_input_fn = tf.estimator.inputs.numpy_input_fn(
        x={"x": eval_data},
        y=eval_labels,
        num_epochs=1,
        shuffle=False)
    eval_results = mnist_classifier.evaluate(input_fn=eval_input_fn)
    print(eval_results)

if __name__ == "__main__":
    tf.app.run()