我已經訓練我的CNN模型,並將其存儲在一個名爲model
它包含文件的目錄如下圖所示如何恢復訓練模型和計算測試精度Tensorflow
\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: name 'layer_fc2' is not defined
如何正確恢復模型並計算測試精度。
其中包含的代碼用於訓練模型原始文件train.py
在使用它之前,你不需要創建fc層嗎? – jdv