TensorFlow实现模型评估

我们需要评估模型预测值来评估训练的好坏。

模型评估是非常重要的,随后的每个模型都有模型评估方式。使用TensorFlow时,需要把模型评估加入到计算图中,然后在模型训练完后调用模型评估。

在训练模型过程中,模型评估能洞察模型算法,给出提示信息来调试、提高或者改变整个模型。但是在模型训练中并不是总需要模型评估,我们将展示如何在回归算法和分类算法中使用它。

训练模型之后,需要定量评估模型的性能如何。在理想情况下,评估模型需要一个训练数据集和测试数据集,有时甚至需要一个验证数据集。

想评估一个模型时就得使用大批量数据点。如果完成批量训练,我们可以重用模型来预测批量数据点。但是如果要完成随机训练,就不得不创建单独的评估器来处理批量数据点。

分类算法模型基于数值型输入预测分类值,实际目标是1和0的序列。我们需要度量预测值与真实值之间的距离。分类算法模型的损失函数一般不容易解释模型好坏,所以通常情况是看下准确预测分类的结果的百分比。

不管算法模型预测的如何,我们都需要测试算法模型,这点相当重要。在训练数据和测试数据上都进行模型评估,以搞清楚模型是否过拟合。

# TensorFlowm模型评估
#
# This code will implement two models. The first
# is a simple regression model, we will show how to
# call the loss function, MSE during training, and
# output it after for test and training sets.
#
# The second model will be a simple classification
# model. We will also show how to print percent
# classified correctly during training and after
# for both the test and training sets.

import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from tensorflow.python.framework import ops
ops.reset_default_graph()

# 创建计算图
sess = tf.Session()

# 回归例子:
# We will create sample data as follows:
# x-data: 100 random samples from a normal ~ N(1, 0.1)
# target: 100 values of the value 10.
# We will fit the model:
# x-data * A = target
# 理论上, A = 10.

# 声明批量大小
batch_size = 25

# 创建数据集
x_vals = np.random.normal(1, 0.1, 100)
y_vals = np.repeat(10., 100)
x_data = tf.placeholder(shape=[None, 1], dtype=tf.float32)
y_target = tf.placeholder(shape=[None, 1], dtype=tf.float32)

# 八二分训练/测试数据 train/test = 80%/20%
train_indices = np.random.choice(len(x_vals), round(len(x_vals)*0.8), replace=False)
test_indices = np.array(list(set(range(len(x_vals))) - set(train_indices)))
x_vals_train = x_vals[train_indices]
x_vals_test = x_vals[test_indices]
y_vals_train = y_vals[train_indices]
y_vals_test = y_vals[test_indices]

# 创建变量 (one model parameter = A)
A = tf.Variable(tf.random_normal(shape=[1,1]))

# 增加操作到计算图
my_output = tf.matmul(x_data, A)

# 增加L2损失函数到计算图
loss = tf.reduce_mean(tf.square(my_output - y_target))

# 创建优化器
my_opt = tf.train.GradientDescentOptimizer(0.02)
train_step = my_opt.minimize(loss)

# 初始化变量
init = tf.global_variables_initializer()
sess.run(init)

# 迭代运行
# 如果在损失函数中使用的模型输出结果经过转换操作,例如,sigmoid_cross_entropy_with_logits()函数,
# 为了精确计算预测结果,别忘了在模型评估中也要进行转换操作。
for i in range(100):
  rand_index = np.random.choice(len(x_vals_train), size=batch_size)
  rand_x = np.transpose([x_vals_train[rand_index]])
  rand_y = np.transpose([y_vals_train[rand_index]])
  sess.run(train_step, feed_dict={x_data: rand_x, y_target: rand_y})
  if (i+1)%25==0:
    print('Step #' + str(i+1) + ' A = ' + str(sess.run(A)))
    print('Loss = ' + str(sess.run(loss, feed_dict={x_data: rand_x, y_target: rand_y})))

# 评估准确率(loss)
mse_test = sess.run(loss, feed_dict={x_data: np.transpose([x_vals_test]), y_target: np.transpose([y_vals_test])})
mse_train = sess.run(loss, feed_dict={x_data: np.transpose([x_vals_train]), y_target: np.transpose([y_vals_train])})
print('MSE on test:' + str(np.round(mse_test, 2)))
print('MSE on train:' + str(np.round(mse_train, 2)))

# 分类算法案例
# We will create sample data as follows:
# x-data: sample 50 random values from a normal = N(-1, 1)
#     + sample 50 random values from a normal = N(1, 1)
# target: 50 values of 0 + 50 values of 1.
#     These are essentially 100 values of the corresponding output index
# We will fit the binary classification model:
# If sigmoid(x+A) < 0.5 -> 0 else 1
# Theoretically, A should be -(mean1 + mean2)/2

# 重置计算图
ops.reset_default_graph()

# 加载计算图
sess = tf.Session()

# 声明批量大小
batch_size = 25

# 创建数据集
x_vals = np.concatenate((np.random.normal(-1, 1, 50), np.random.normal(2, 1, 50)))
y_vals = np.concatenate((np.repeat(0., 50), np.repeat(1., 50)))
x_data = tf.placeholder(shape=[1, None], dtype=tf.float32)
y_target = tf.placeholder(shape=[1, None], dtype=tf.float32)

# 分割数据集 train/test = 80%/20%
train_indices = np.random.choice(len(x_vals), round(len(x_vals)*0.8), replace=False)
test_indices = np.array(list(set(range(len(x_vals))) - set(train_indices)))
x_vals_train = x_vals[train_indices]
x_vals_test = x_vals[test_indices]
y_vals_train = y_vals[train_indices]
y_vals_test = y_vals[test_indices]

# 创建变量 (one model parameter = A)
A = tf.Variable(tf.random_normal(mean=10, shape=[1]))

# Add operation to graph
# Want to create the operstion sigmoid(x + A)
# Note, the sigmoid() part is in the loss function
my_output = tf.add(x_data, A)

# 增加分类损失函数 (cross entropy)
xentropy = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=my_output, labels=y_target))

# Create Optimizer
my_opt = tf.train.GradientDescentOptimizer(0.05)
train_step = my_opt.minimize(xentropy)

# Initialize variables
init = tf.global_variables_initializer()
sess.run(init)

# 运行迭代
for i in range(1800):
  rand_index = np.random.choice(len(x_vals_train), size=batch_size)
  rand_x = [x_vals_train[rand_index]]
  rand_y = [y_vals_train[rand_index]]
  sess.run(train_step, feed_dict={x_data: rand_x, y_target: rand_y})
  if (i+1)%200==0:
    print('Step #' + str(i+1) + ' A = ' + str(sess.run(A)))
    print('Loss = ' + str(sess.run(xentropy, feed_dict={x_data: rand_x, y_target: rand_y})))

# 评估预测
# 用squeeze()函数封装预测操作,使得预测值和目标值有相同的维度。
y_prediction = tf.squeeze(tf.round(tf.nn.sigmoid(tf.add(x_data, A))))
# 用equal()函数检测是否相等,
# 把得到的true或false的boolean型张量转化成float32型,
# 再对其取平均值,得到一个准确度值。
correct_prediction = tf.equal(y_prediction, y_target)
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
acc_value_test = sess.run(accuracy, feed_dict={x_data: [x_vals_test], y_target: [y_vals_test]})
acc_value_train = sess.run(accuracy, feed_dict={x_data: [x_vals_train], y_target: [y_vals_train]})
print('Accuracy on train set: ' + str(acc_value_train))
print('Accuracy on test set: ' + str(acc_value_test))

# 绘制分类结果
A_result = -sess.run(A)
bins = np.linspace(-5, 5, 50)
plt.hist(x_vals[0:50], bins, alpha=0.5, label='N(-1,1)', color='white')
plt.hist(x_vals[50:100], bins[0:50], alpha=0.5, label='N(2,1)', color='red')
plt.plot((A_result, A_result), (0, 8), 'k--', linewidth=3, label='A = '+ str(np.round(A_result, 2)))
plt.legend(loc='upper right')
plt.title('Binary Classifier, Accuracy=' + str(np.round(acc_value_test, 2)))
plt.show()

输出:

Step #25 A = [[ 5.79096079]]
Loss = 16.8725
Step #50 A = [[ 8.36085415]]
Loss = 3.60671
Step #75 A = [[ 9.26366138]]
Loss = 1.05438
Step #100 A = [[ 9.58914948]]
Loss = 1.39841
MSE on test:1.04
MSE on train:1.13
Step #200 A = [ 5.83126402]
Loss = 1.9799
Step #400 A = [ 1.64923656]
Loss = 0.678205
Step #600 A = [ 0.12520729]
Loss = 0.218827
Step #800 A = [-0.21780498]
Loss = 0.223919
Step #1000 A = [-0.31613481]
Loss = 0.234474
Step #1200 A = [-0.33259964]
Loss = 0.237227
Step #1400 A = [-0.28847221]
Loss = 0.345202
Step #1600 A = [-0.30949864]
Loss = 0.312794
Step #1800 A = [-0.33211425]
Loss = 0.277342
Accuracy on train set: 0.9625
Accuracy on test set: 1.0

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • TensorFlow Session使用的两种方法小结

    TensorFlow Session 在TensorFlow中是通过session进行交互的,使用session有两种方法.下面通过一个简单的例子(两个矩阵相乘)说一下 {[3,1] 与{[5,2] 相乘 [1,2]} [2,4]} 代码 #encoding=utf-8 import tensorflow as tf matrix1 = tf.constant([[3,1],[1,2]]) matrix2 = tf.constant([[5,2],[2,4]]) product = tf.mat

  • C++调用tensorflow教程

    目前深度学习越来越火,学习.使用tensorflow的相关工作者也越来越多.但是目前绝大部分的python都是拥有着丰富的python的API,而c++的API不够完善.这就导致绝大多是使用tensorflow的项目都是基于python. 如果项目是由c++编写,想调用python下的tensorflow?可参考本教程(tensorflow模型是CNN卷积神经网络) 具体步骤: 1.python环境 首先安装python,可以在Anaconda官网直接下载.记住python一定选择64bit,目

  • TensorFlow实现iris数据集线性回归

    本文将遍历批量数据点并让TensorFlow更新斜率和y截距.这次将使用Scikit Learn的内建iris数据集.特别地,我们将用数据点(x值代表花瓣宽度,y值代表花瓣长度)找到最优直线.选择这两种特征是因为它们具有线性关系,在后续结果中将会看到.本文将使用L2正则损失函数. # 用TensorFlow实现线性回归算法 #---------------------------------- # # This function shows how to use TensorFlow to #

  • tensorflow实现简单逻辑回归

    逻辑回归是机器学习中很简答的一个栗子,这篇文章就是要介绍如何使用tensorflow实现一个简单的逻辑回归算法. 逻辑回归可以看作只有一层网络的前向神经网络,并且参数连接的权重只是一个值,而非矩阵.公式为:y_predict=logistic(X*W+b),其中X为输入,W为输入与隐含层之间的权重,b为隐含层神经元的偏置,而logistic为激活函数,一般为sigmoid或者tanh, y_predict为最终预测结果. 逻辑回归是一种分类器模型,需要木便函数不断的优化参数,这里目标函数为y_p

  • 使用TensorFlow实现SVM

    较基础的SVM,后续会加上多分类以及高斯核,供大家参考. Talk is cheap, show me the code import tensorflow as tf from sklearn.base import BaseEstimator, ClassifierMixin import numpy as np class TFSVM(BaseEstimator, ClassifierMixin): def __init__(self, C = 1, kernel = 'linear',

  • python3.6.3安装图文教程 TensorFlow安装配置方法

    本文主要介绍Python3.6及TensorFlow的安装和配置流程. 一.Python官网下载自己电脑和系统对应的Python安装包. 网址:下载地址 一直往下拉到Files,这里我下载的是Windows x86-64 executable installer (注意:要装TensorFlow必须安装64位的Python,TensorFlow不支持32位)< 二.下载python-3.6.3-amd64.exe应用程序 下载完成后得到一个python-3.6.3-amd64.exe应用程序,右

  • win10下tensorflow和matplotlib安装教程

    本文介绍了一系列安装教程,具体如下 1.安装Python 版本选择是3.5.1,因为网上有些深度学习实例用的就是这个版本,跟他们一样的话可以避免版本带来的语句规范问题 python的下载官网 2.安装easy_install 在Python的官网下载easy_install的安装包,下载地址 下载完成后解压zip,解压后双击setup.py,会跳出一个黑框闪一下,这时python目录下的scripts文件夹中有了easy_install的应用程序文件. 接下来配置环境变量:计算机→系统属性→高级

  • Tensorflow使用支持向量机拟合线性回归

    支持向量机可以用来拟合线性回归. 相同的最大间隔(maximum margin)的概念应用到线性回归拟合.代替最大化分割两类目标是,最大化分割包含大部分的数据点(x,y).我们将用相同的iris数据集,展示用刚才的概念来进行花萼长度与花瓣宽度之间的线性拟合. 相关的损失函数类似于max(0,|yi-(Axi+b)|-ε).ε这里,是间隔宽度的一半,这意味着如果一个数据点在该区域,则损失等于0. # SVM Regression #---------------------------------

  • 使用tensorflow实现线性svm

    本文实例为大家分享了tensorflow实现线性svm的具体代码,供大家参考,具体内容如下 简单方法: import tensorflow as tf import numpy as np from matplotlib import pyplot as plt def placeholder_input(): x=tf.placeholder('float',shape=[None,2],name='x_batch') y=tf.placeholder('float',shape=[None,

  • win10下python3.5.2和tensorflow安装环境搭建教程

    在win10环境下搭建python3.5.2和tensorflow平台,供大家参考,具体内容如下 操作步骤如下: 1.官网(https://www.python.org/ )下载python3.5.2  选择Downloads-Windows 选择64位executable installer 2.安装过程,双击.exe可执行文件(此步可参考安装教程:win10环境下python3.5安装步骤图文教程) 一路默认下去! 3.安装成功后打开cmd命令窗口 print("Hello World!&q

随机推荐