Skip to main content
 首页 » 编程设计

python之Tensorflow:我在准确性上出错了

2024年10月01日40xing901022

我只是运行一个简单的代码,想在训练后获得准确率。我加载了我保存的模型,但是当我想要获得准确性时,我出错了。为什么?

# coding=utf-8 
from  color_1 import read_and_decode, get_batch, get_test_batch 
import AlexNet 
import cv2 
import os 
import time 
import numpy as np 
import tensorflow as tf 
import AlexNet_train 
import math 
 
batch_size=128 
num_examples = 1000 
crop_size=56 
 
def evaluate(test_x, test_y): 
    image_holder = tf.placeholder(tf.float32, [batch_size, 56, 56, 3], name='x-input') 
    label_holder = tf.placeholder(tf.int32, [batch_size], name='y-input') 
 
    y = AlexNet.inference(image_holder,evaluate,None) 
 
    correct_prediction=tf.equal(tf.argmax(y,1),tf.argmax(label_holder,1)) 
    accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32)) 
    saver = tf.train.Saver() 
    with tf.Session() as sess: 
        init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer()) 
        coord = tf.train.Coordinator() 
        sess.run(init_op) 
        threads = tf.train.start_queue_runners(sess=sess, coord=coord) 
        ckpt=tf.train.get_checkpoint_state(AlexNet_train.MODEL_SAVE_PATH) 
        if ckpt and ckpt.model_checkpoint_path: 
            ckpt_name = os.path.basename(ckpt.model_checkpoint_path) 
            global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1] 
            saver.restore(sess, os.path.join(AlexNet_train.MODEL_SAVE_PATH, ckpt_name)) 
            print('Loading success, global_step is %s' % global_step) 
            step=0 
 
            image_batch, label_batch = sess.run([test_x, test_y]) 
            accuracy_score=sess.run(accuracy,feed_dict={image_holder: image_batch, 
                                                              label_holder: label_batch}) 
            print("After %s training step(s),validation " 
                  "precision=%g" % (global_step, accuracy_score)) 
        coord.request_stop()   
        coord.join(threads) 
 
def main(argv=None): 
    test_image, test_label = read_and_decode('val.tfrecords') 
 
    test_images, test_labels = get_test_batch(test_image, test_label, batch_size, crop_size) 
 
    evaluate(test_images, test_labels) 
 
 
if __name__=='__main__': 
    tf.app.run() 

这里是错误,它说我代码中的这一行是错误的:“correct_prediction=tf.equal(tf.argmax(y,1),tf.argmax(label_holder,1))”

Traceback (most recent call last): 
  File "/home/vrview/tensorflow/example/char/tfrecords/AlexNet/Alex_save/AlexNet_test.py", line 80, in <module> 
    tf.app.run() 
  File "/home/vrview/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/platform/app.py", line 44, in run 
    _sys.exit(main(_sys.argv[:1] + flags_passthrough)) 
  File "/home/vrview/tensorflow/example/char/tfrecords/AlexNet/Alex_save/AlexNet_test.py", line 76, in main 
    evaluate(test_images, test_labels) 
  File "/home/vrview/tensorflow/example/char/tfrecords/AlexNet/Alex_save/AlexNet_test.py", line 45, in evaluate 
    label_holder: label_batch}) 
  File "/home/vrview/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 767, in run 
    run_metadata_ptr) 
  File "/home/vrview/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 965, in _run 
    feed_dict_string, options, run_metadata) 
  File "/home/vrview/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1015, in _do_run 
    target_list, options, run_metadata) 
  File "/home/vrview/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1035, in _do_call 
    raise type(e)(node_def, op, message) 
tensorflow.python.framework.errors_impl.InvalidArgumentError: Expected dimension in the range [-1, 1), but got 1 
     [[Node: ArgMax_1 = ArgMax[T=DT_INT32, Tidx=DT_INT32, _device="/job:localhost/replica:0/task:0/cpu:0"](_recv_y-input_0, ArgMax_1/dimension)]] 
 
Caused by op u'ArgMax_1', defined at: 
  File "/home/vrview/tensorflow/example/char/tfrecords/AlexNet/Alex_save/AlexNet_test.py", line 80, in <module> 
    tf.app.run() 
  File "/home/vrview/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/platform/app.py", line 44, in run 
    _sys.exit(main(_sys.argv[:1] + flags_passthrough)) 
  File "/home/vrview/tensorflow/example/char/tfrecords/AlexNet/Alex_save/AlexNet_test.py", line 76, in main 
    evaluate(test_images, test_labels) 
  File "/home/vrview/tensorflow/example/char/tfrecords/AlexNet/Alex_save/AlexNet_test.py", line 22, in evaluate 
    correct_prediction=tf.equal(tf.argmax(y,1),tf.argmax(label_holder,1)) 
  File "/home/vrview/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/ops/math_ops.py", line 263, in argmax 
    return gen_math_ops.arg_max(input, axis, name) 
  File "/home/vrview/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/ops/gen_math_ops.py", line 168, in arg_max 
    name=name) 
  File "/home/vrview/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/framework/op_def_library.py", line 763, in apply_op 
    op_def=op_def) 
  File "/home/vrview/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 2395, in create_op 
    original_op=self._default_original_op, op_def=op_def) 
  File "/home/vrview/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1264, in __init__ 
    self._traceback = _extract_stack() 
 
InvalidArgumentError (see above for traceback): Expected dimension in the range [-1, 1), but got 1 
     [[Node: ArgMax_1 = ArgMax[T=DT_INT32, Tidx=DT_INT32, _device="/job:localhost/replica:0/task:0/cpu:0"](_recv_y-input_0, ArgMax_1/dimension)]] 

如何解决?

请您参考如下方法:

参与this answer与这里的问题相关:

tf.argmax's definition状态:

axis: A Tensor. Must be one of the following types: int32, int64. int32, 0 <= axis < rank(input). Describes which axis of the input Tensor to reduce across.

看来,在张量的最后一个轴上运行 argmax 的唯一方法是给它 axis=-1,因为“严格小于”在函数定义中签名。