【问题标题】:How to restore trained model and calculate test accuracy in Tensorflow如何在 Tensorflow 中恢复训练好的模型并计算测试准确度
【发布时间】:2018-03-26 09:18:21
【问题描述】:

我已经训练了我的 CNN 模型并将其存储在名为 model 的目录中,其中包含如下所示的文件

\model
|--- checkpoint
|--- model.data-00000-of-00001
|--- model.index
|--- model.meta

我想恢复模型并计算我正在使用以下代码的测试准确度

import tensorflow as tf
import numpy as np
import cv2
import os
import glob

images    = []
labels    = []
img_names = []
cls       = []

test_path = 'data\\cifar-10\\test'
image_size = 32
num_channels    = 3

# Prepare input data
with open('data\\cifar-10\\wnids.txt') as f:
    classes = f.readlines()
classes = [x.strip() for x in classes] 

num_classes = len(classes)

for fields in classes:   
    index = classes.index(fields)
    print('Read {} files (Index: {})'.format(fields, index))
    path = os.path.join(test_path, fields, '*g')
    files = glob.glob(path)
    for fl in files:
        image = cv2.imread(fl)
        image = cv2.resize(image, (image_size, image_size),0,0, cv2.INTER_LINEAR)
        image = image.astype(np.float32)
        image = np.multiply(image, 1.0 / 255.0)
        images.append(image)
        label = np.zeros(len(classes))
        label[index] = 1.0
        labels.append(label)
        flbase = os.path.basename(fl)
        img_names.append(flbase)
        cls.append(fields)

images    = np.array(images)
labels    = np.array(labels)
img_names = np.array(img_names)
cls       = np.array(cls)

session = tf.Session()
tf_saver = tf.train.import_meta_graph('model\\model.meta')
tf_saver.restore(session, tf.train.latest_checkpoint('model'))

x      = tf.placeholder(tf.float32, shape=[None, image_size, image_size, num_channels], name='x')
y_true = tf.placeholder(tf.float32, shape=[None, num_classes], name='y_true')
y_true_cls = tf.argmax(y_true, axis=1)

y_pred     = tf.nn.softmax(layer_fc2, name='y_pred')
y_pred_cls = tf.argmax(y_pred, axis=1)

correct_prediction = tf.equal(y_pred_cls, y_true_cls)
accuracy           = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

feed_dict_test  = {x: images, y_true: labels}

test_acc = session.run(accuracy, feed_dict=feed_dict_test)

msg     = "Test Accuracy: {1:>6.1%}"
print(msg.format(test_acc))

在运行上面的代码时出现错误

NameError:名称“layer_fc2”未定义

如何正确恢复模型并计算测试精度?

【问题讨论】:

  • fc层使用前不用创建吗?
  • 请不要在 Stack Overflow 上发布像 paste.ofcode.org 这样的临时内容。

标签: python python-3.x tensorflow conv-neural-network


【解决方案1】:

layer_fc2 是在您的训练脚本(您在其中定义图形)中定义的 Python 变量,此处不存在。你需要做的是找到这一层。不幸的是,你没有在火车时间命名它。将您的 create_fc_layer 代码更改为

def create_fc_layer(input, num_inputs, num_outputs, name, use_relu=True):
  weights = create_weights(shape=[num_inputs, num_outputs])
  biases = create_biases(num_outputs)
  layer = tf.matmul(input, weights) + biases
  if use_relu:
    layer = tf.nn.relu(layer)

  return tf.identity(layer, name=name)  # return a named layer

...

layer_fc2   = create_fc_layer(input=layer_fc1, num_inputs=fc_layer_size, num_outputs=num_classes, name='layer_fc2', use_relu=False)

在你的新脚本之后:

layer_fc2 = session.graph.get_operation_by_name('layer_fc2')

顺便说一句,您也不需要重新定义y_predy_pred_cls 等。给它们命名,然后从恢复的图形中简单地获取它。

【讨论】:

  • 感谢您的回复。但是按照您的建议进行更改后,我遇到了以下错误KeyError: "The name 'layer_fc2' refers to an Operation not in the graph."
  • 对。我想你没有重新训练模型。因此,您现在拥有的模型没有layer_fc2 的名称。它有一些内部名称,例如“Relu:0”。您可以尝试使用它,但它很容易出错。我建议你改变你的训练脚本,重新训练一个新模型,其中所需的操作被正确命名,并使用它
  • 按照您的建议进行更改后,我重新训练了模型。但仍然是同样的错误。
  • session.graph.get_operations() 告诉我们什么?也可以试试layer_fc2:0
  • 我尝试将layer_fc2 更改为layer_fc2:0。现在我收到此错误ValueError: Name 'layer_fc2:0' appears to refer to a Tensor, not a Operation.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-28
  • 2018-02-08
  • 2019-10-08
  • 2020-11-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多