如何使用Python利用Tensorflow评估测试数据上的模型?

如何使用Python利用Tensorflow评估测试数据上的模型?

随着机器学习技术的发展,越来越多的实践者将模型训练的评估作为机器学习模型研究的重要一环。其中评估模型的性能需要用到很多指标,例如准确率、召回率和F1值等等。本文将介绍如何使用Python利用Tensorflow评估测试数据上的模型。

更多Python文章,请阅读:Python 教程

数据准备

在进行模型的评估之前,首先需要准备好数据集。在这里,我们使用的是著名的手写数字分类的数据集MNIST。我们可以使用Tensorflow库自带的方法minist来加载数据集。

以下是将数据集加载为训练和测试数据的代码示例:

from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("./mnist/data/", one_hot=True)

X_train = mnist.train.images
Y_train = mnist.train.labels
X_test = mnist.test.images
Y_test = mnist.test.labels

在这里,read_data_sets()方法可以传入用于存放MNIST数据的本地文件夹路径,one_hot参数用于对数据进行一位有效编码(one-hot-encoding),使得分类器可以更好地处理数据集并提高效率。train.images/train.labelstest.images/test.labels分别代表训练和测试数据集中的图像和标签数据。

模型建立与加载

在准备好数据集后,需要建立要评估的模型。这里我们使用Tensorflow的官方模型代码库中的一个经典模型Lenet-5。

以下是建立Lenet-5模型的示例代码:

import tensorflow as tf

def weight_variable(shape):
    initial = tf.truncated_normal(shape, stddev=0.1)
    return tf.Variable(initial)

def bias_variable(shape):
    initial = tf.constant(0.1, shape=shape)
    return tf.Variable(initial)

def conv2d(x, W):
    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

def max_pool_2x2(x):
    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')

x_input = tf.placeholder(tf.float32, [None, 784])
x_image = tf.reshape(x_input, [-1,28,28,1])
y_true = tf.placeholder(tf.float32, [None, 10])

W_conv1 = weight_variable([5, 5, 1, 6])
b_conv1 = bias_variable([6])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)

W_conv2 = weight_variable([5, 5, 6, 16])
b_conv2 = bias_variable([16])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)

W_fc1 = weight_variable([7 * 7 * 16, 120])
b_fc1 = bias_variable([120])
h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*16])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)

W_fc2 = weight_variable([120, 84])
b_fc2 = bias_variable([84])
h_fc2 = tf.nn.relu(tf.matmul(h_fc1, W_fc2) + b_fc2)

W_fc3 = weight_variable([84, 10])
b_fc3 = bias_variable([10])
y_pred = tf.nn.softmax(tf.matmul(h_fc2, W_fc3) + b_fc3)

correct_prediction = tf.equal(tf.argmax(y_pred,1), tf.argmax(y_true,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

该模型包含两个卷积层和两个全连通层。通过weight_variable()bias_variable()方法创建权重和偏差变量。接下来,我们按照卷积神经网络的基本操作,对数据进行卷积和池化。使用tf.nn.conv2d()方法进行卷积操作,tf.nn.max_pool()方法实现池化操作。最后通过全连通层得到预测结果并计算准确率。

接下来需要将之前训练的模型加载进来,对其进行评估。这里我们可以使用Tensorflow提供的tf.saved_model.loader.load()加载模型。

以下是从已保存路径加载模型的代码示例:

model_path = './model/lenet-5/'
with tf.Session() as sess:
    saver = tf.train.Saver(tf.global_variables())
    saver.restore(sess, tf.train.latest_checkpoint(model_path))
    graph = tf.get_default_graph()

    x_input_tensor = graph.get_tensor_by_name('Placeholder:0')
    y_predict_tensor = graph.get_tensor_by_name('add_5:0')

    accuracy_tensor = graph.get_tensor_by_name('Mean_1:0')

    acc = sess.run(accuracy_tensor, feed_dict={x_input_tensor: X_test, y_true: Y_test})
    print('Test accuracy:', acc)

在这里,tf.Session()方法生成一个会话对象。由于我们的之前保存的模型在指定的文件夹下,所以需要使用saver.restore()方法来加载模型。接着,我们通过graph.get_tensor_by_name()方法获取需要评估的节点,也就是输入数据的占位符和预测结果的张量。最后,我们利用sess.run()在会话中进行运行,传入测试数据和标签来计算测试数据上的模型准确率。

结论

本文介绍了如何使用Python利用Tensorflow评估测试数据上的模型。我们通过加载MNIST手写数字数据集,利用Lenet-5模型进行训练和测试,并通过Tensorflow提供的方法加载已训练好的模型进行评估。希望本文能够帮助更多的人更好地评估自己的机器学习模型。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程