TensorFlow的高级机器学习API(tf.estimator)可以轻松配置,训练和评估各种机器学习模型。 在本教程中,您将使用tf.estimator构建一个神经网络分类器,并在Iris数据集上对其进行训练,以基于萼片/花瓣几何学来预测花朵种类。 您将编写代码来执行以下五个步骤:

  • 将包含Iris训练/测试数据的CSV加载到TensorFlow数据集中
  • 构建一个神经网络分类器
  • 使用训练数据训练模型
  • 评估模型的准确性
  • 分类新样品

注:在开始本教程之前,请记住在您的机器上安装TensorFlow。

完整的神经网络源代码

以下是神经网络分类器的完整代码:

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function import os
from six.moves.urllib.request import urlopen import numpy as np
import tensorflow as tf # Data sets
IRIS_TRAINING = "iris_training.csv"
IRIS_TRAINING_URL = "http://download.tensorflow.org/data/iris_training.csv" IRIS_TEST = "iris_test.csv"
IRIS_TEST_URL = "http://download.tensorflow.org/data/iris_test.csv" def main():
# If the training and test sets aren't stored locally, download them.
if not os.path.exists(IRIS_TRAINING):
raw = urlopen(IRIS_TRAINING_URL).read()
with open(IRIS_TRAINING, "wb") as f:
f.write(raw) if not os.path.exists(IRIS_TEST):
raw = urlopen(IRIS_TEST_URL).read()
with open(IRIS_TEST, "wb") as f:
f.write(raw) # Load datasets.
training_set = tf.contrib.learn.datasets.base.load_csv_with_header(
filename=IRIS_TRAINING,
target_dtype=np.int,
features_dtype=np.float32)
test_set = tf.contrib.learn.datasets.base.load_csv_with_header(
filename=IRIS_TEST,
target_dtype=np.int,
features_dtype=np.float32) # Specify that all features have real-value data
feature_columns = [tf.feature_column.numeric_column("x", shape=[4])] # Build 3 layer DNN with 10, 20, 10 units respectively.
classifier = tf.estimator.DNNClassifier(feature_columns=feature_columns,
hidden_units=[10, 20, 10],
n_classes=3,
model_dir="/tmp/iris_model")
# Define the training inputs
train_input_fn = tf.estimator.inputs.numpy_input_fn(
x={"x": np.array(training_set.data)},
y=np.array(training_set.target),
num_epochs=None,
shuffle=True) # Train model.
classifier.train(input_fn=train_input_fn, steps=2000) # Define the test inputs
test_input_fn = tf.estimator.inputs.numpy_input_fn(
x={"x": np.array(test_set.data)},
y=np.array(test_set.target),
num_epochs=1,
shuffle=False) # Evaluate accuracy.
accuracy_score = classifier.evaluate(input_fn=test_input_fn)["accuracy"] print("\nTest Accuracy: {0:f}\n".format(accuracy_score)) # Classify two new flower samples.
new_samples = np.array(
[[6.4, 3.2, 4.5, 1.5],
[5.8, 3.1, 5.0, 1.7]], dtype=np.float32)
predict_input_fn = tf.estimator.inputs.numpy_input_fn(
x={"x": new_samples},
num_epochs=1,
shuffle=False) predictions = list(classifier.predict(input_fn=predict_input_fn))
predicted_classes = [p["classes"] for p in predictions] print(
"New Samples, Class Predictions: {}\n"
.format(predicted_classes)) if __name__ == "__main__":
main()

以下部分详细介绍了代码。

将Iris CSV数据加载到TensorFlow

Iris数据集包含150行数据,包括来自三个相关鸢尾属物种中的每一个的50个样品:Iris setosa,Iris virginica和Iris versicolor。

From left to right, Iris setosa (by Radomil, CC BY-SA 3.0), Iris versicolor (by Dlanglois, CC BY-SA 3.0), and Iris virginica(by Frank Mayfield, CC BY-SA 2.0).

每行包含每个花样的以下数据:萼片长度,萼片宽度,花瓣长度,花瓣宽度和花种。 花种以整数表示,其中0表示Iris setosa,1表示Iris virginica,2表示Iris versicolor。

对于本教程,Iris数据已被随机分成两个独立的CSV:

开始前,首先导入所有必要的模块,并定义下载和存储数据集的位置:

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function import os
from six.moves.urllib.request import urlopen import tensorflow as tf
import numpy as np IRIS_TRAINING = "iris_training.csv"
IRIS_TRAINING_URL = "http://download.tensorflow.org/data/iris_training.csv" IRIS_TEST = "iris_test.csv"
IRIS_TEST_URL = "http://download.tensorflow.org/data/iris_test.csv"

然后,如果训练和测试集尚未存储在本地,请下载它们。

if not os.path.exists(IRIS_TRAINING):
raw = urlopen(IRIS_TRAINING_URL).read()
with open(IRIS_TRAINING,'wb') as f:
f.write(raw) if not os.path.exists(IRIS_TEST):
raw = urlopen(IRIS_TEST_URL).read()
with open(IRIS_TEST,'wb') as f:
f.write(raw)

接下来,使用learn.datasets.base中的load_csv_with_header()方法将训练集和测试集加载到数据集中。 load_csv_with_header()方法需要三个必需的参数:

  • filename,它将文件路径转换为CSV文件
  • target_dtype,它采用数据集的目标值的numpy数据类型。
  • features_dtype,它采用数据集特征值的numpy数据类型。

在这里,目标(你正在训练模型来预测的值)是花的种类,它是一个从0到2的整数,所以合适的numpy数据类型是np.int:

# Load datasets.
training_set = tf.contrib.learn.datasets.base.load_csv_with_header(
filename=IRIS_TRAINING,
target_dtype=np.int,
features_dtype=np.float32)
test_set = tf.contrib.learn.datasets.base.load_csv_with_header(
filename=IRIS_TEST,
target_dtype=np.int,
features_dtype=np.float32)

tf.contrib.learn中的数据集被命名为元组;您可以通过datatarget字段访问特征数据和目标值。这里,training_set.datatraining_set.target分别包含训练集的特征数据和目标值,test_set.datatest_set.target包含测试集的特征数据和目标值。

稍后,在“将DNNClassifier安装到Iris训练数据”中,您将使用training_set.datatraining_set.target来训练您的模型,在“Evaluate Model Accuracy”中,您将使用test_set.datatest_set.target。但首先,您将在下一节中构建您的模型。

构建深度神经网络分类器

tf.estimator提供了各种预定义的模型,称为Estimators,您可以使用“开箱即用”对数据进行训练和评估操作。在这里,您将配置深度神经网络分类器模型以适应Iris数据。使用tf.estimator,你可以用几行代码实例化你的tf.estimator.DNNClassifier

# Specify that all features have real-value data
feature_columns = [tf.feature_column.numeric_column("x", shape=[4])] # Build 3 layer DNN with 10, 20, 10 units respectively.
classifier = tf.estimator.DNNClassifier(feature_columns=feature_columns,
hidden_units=[10, 20, 10],
n_classes=3,
model_dir="/tmp/iris_model")

上面的代码首先定义模型的特征列,它指定数据集中特征的数据类型。所有的特征数据都是连续的,所以tf.feature_column.numeric_column是用来构造特征列的适当函数。数据集中有四个特征(萼片宽度,萼片高度,花瓣宽度和花瓣高度),所以相应的形状必须设置为[4]来保存所有的数据。

然后,代码使用以下参数创建一个DNNClassifier模型:

  • feature_columns = feature_columns。上面定义的一组特征列。
  • hidden_units = [10,20,10]。三个隐藏层,分别包含10,20和10个神经元。
  • n_classes = 3。三个目标类,代表三个鸢尾属。
  • model_dir =/tmp/iris_model。 TensorFlow将在模型训练期间保存检查点数据和TensorBoard摘要的目录。

描述训练输入管道

tf.estimator API使用输入函数,这些输入函数创建了用于为模型生成数据的TensorFlow操作。我们可以使用tf.estimator.inputs.numpy_input_fn来产生输入管道:

# Define the training inputs
train_input_fn = tf.estimator.inputs.numpy_input_fn(
x={"x": np.array(training_set.data)},
y=np.array(training_set.target),
num_epochs=None,
shuffle=True)

将DNNClassifier安装到Iris训练数据

现在,您已经配置了DNN分类器模型,可以使用train方法将其适用于Iris训练数据。 将train_input_fn传递给input_fn,以及要训练的步数(这里是2000):

# Train model.
classifier.train(input_fn=train_input_fn, steps=2000)

模型的状态保存在分类器中,这意味着如果你喜欢,可以迭代地训练。 例如,上面的做法相当于以下内容:

classifier.train(input_fn=train_input_fn, steps=1000)
classifier.train(input_fn=train_input_fn, steps=1000)

但是,如果您希望在训练时跟踪模型,则可能需要使用TensorFlow SessionRunHook来执行日志记录操作。

评估模型的准确性

您已经在Iris训练数据上训练了您的DNNClassifier模型; 现在,您可以使用评估方法检查Iris测试数据的准确性。 像train一样,evaluate需要一个输入函数来建立它的输入流水线。 评估返回与评估结果的字典。 以下代码将通过Iris测试data-test_set.datatest_set.target来评估和打印结果的准确性:

# Define the test inputs
test_input_fn = tf.estimator.inputs.numpy_input_fn(
x={"x": np.array(test_set.data)},
y=np.array(test_set.target),
num_epochs=1,
shuffle=False) # Evaluate accuracy.
accuracy_score = classifier.evaluate(input_fn=test_input_fn)["accuracy"] print("\nTest Accuracy: {0:f}\n".format(accuracy_score))

注意:这里numpy_input_fn的num_epochs = 1参数很重要。 test_input_fn将迭代数据一次,然后引发OutOfRangeError。 这个错误表示分类器停止评估,所以它会在输入上评估一次。

当你运行完整的脚本时,它会打印出一些接近的内容:

Test Accuracy: 0.966667
您的准确性结果可能会有所不同,但应该高于90%。 对于相对较小的数据集来说很不错了!

分类新样品

使用估计器的predict()方法对新样本进行分类。 例如,假设你有这两个新的花样:

您可以使用predict()方法预测它们的物种。 预测返回一个字符串生成器,可以很容易地转换为列表。 以下代码检索并打印类预测:

# Classify two new flower samples.
new_samples = np.array(
[[6.4, 3.2, 4.5, 1.5],
[5.8, 3.1, 5.0, 1.7]], dtype=np.float32)
predict_input_fn = tf.estimator.inputs.numpy_input_fn(
x={"x": new_samples},
num_epochs=1,
shuffle=False) predictions = list(classifier.predict(input_fn=predict_input_fn))
predicted_classes = [p["classes"] for p in predictions] print(
"New Samples, Class Predictions: {}\n"
.format(predicted_classes))

你的结果应该如下所示:

New Samples, Class Predictions:    [1 2]

因此,模型预测第一个样品是Iris versicolor,第二个样品是Iris virginica

感谢并转自:https://blog.csdn.net/qq_17550379/article/details/78743343

参考:https://www.jianshu.com/p/5495f87107e7

tensorflow estimator API小栗子的更多相关文章

  1. TensorFlow 1.4利用Keras+Estimator API进行训练和预测

    Tensorflow 1.4中,Keras作为作为核心模块可以直接通过tf.keas进行调用,但是考虑到keras对tfrecords文件进行操作比较麻烦,而将keras模型转成tensorflow中 ...

  2. Javaweb统计在线人数的小栗子

    最近在学习Javaweb相关的内容(不黑不吹之前对web开发零基础),下面通过一个统计在线人数的小栗子讲讲Servlet监听器吧 开发环境 eclipse  tomcat 7 先说说这个小栗子的构思: ...

  3. cookie小栗子-实现简单的身份验证

    关于Cookie Cookie是一种能够让网站Web服务器把少量数据储存到客户端的硬盘或内存里,或是从客户端的硬盘里读取数据的一种技术. 用来保存客户浏览器请求服务器页面的请求信息,可以在HTTP返回 ...

  4. tensorflow models api:ValueError: Tensor conversion requested dtype string for Tensor with dtype float32: 'Tensor("arg0:0", shape=(), dtype=float32, device=/device:CPU:0)'

    tensorflow models api:ValueError: Tensor conversion requested dtype string for Tensor with dtype flo ...

  5. SpringBoot+Shiro+Redis共享Session入门小栗子

    在单机版的Springboot+Shiro的基础上,这次实现共享Session. 这里没有自己写RedisManager.SessionDAO.用的 crazycake 写的开源插件 pom.xml ...

  6. SpringBoot+Shiro入门小栗子

    写一个不花里胡哨的纯粹的Springboot+Shiro的入门小栗子 效果如图: 首页:有登录注册 先注册一个,然后登陆 登录,成功自动跳转到home页 home页:通过认证之后才可以进 代码部分: ...

  7. 一个小栗子聊聊JAVA泛型基础

    背景 周五本该是愉快的,可是今天花了一个早上查问题,为什么要花一个早上?我把原因总结为两点: 日志信息严重丢失,茫茫代码毫无头绪. 对泛型的认识不够,导致代码出现了BUG. 第一个原因可以通过以后编码 ...

  8. TensorFlow dataset API 使用

    # TensorFlow dataset API 使用 由于本人感兴趣的是自然语言处理,所以下面有关dataset API 的使用偏向于变长数据的处理. 1. 从迭代器中引入数据 import num ...

  9. java网络爬虫爬虫小栗子

    简要介绍: 使用java开发的爬虫小栗子,存储到由zookeeper协调的hbase中 主要过程是模拟Post请求和get请求,html解析,hbase存储 源码:https://github.com ...

随机推荐

  1. 自制操作系统Antz(11)——实现shell(下)命令响应

    我已经规范了系统代码风格,类似于按照linux分包,把各部分功能区分开了 Antz系统更新地址 Linux内核源码分析地址 Github项目地址 在之前的任务中,我们已经通过直接操作显卡驱动完成了简单 ...

  2. linux系统ansible一键完成三大服务器基础配置(剧本)

    ansible自动化管理剧本方式一键完成三大服务器基础配置 环境准备:五台服务器:管理机m01:172.16.1.61,两台web服务器172.16.1.7,172.16.1.8,nfs存储服务器17 ...

  3. Linux下复制文件

    命令: cp -Rf /文件名1/*               /文件名2 把文件夹1下的文件复制到文件2中(/* 表示复制文件夹1下的文件,不复制文件夹1)

  4. (void) (&_min1 == &_min2);【转】

    本文转载自:https://blog.csdn.net/xiaofeng_yan/article/details/5248693 偶然在<./linux/include/linux/kernel ...

  5. List集合流处理类型小结

    本文为博主原创,未经允许不得转载 对应实体类 import lombok.Getter; import lombok.Setter; @Getter @Setter public class Stud ...

  6. C++第二章复习与总结(思维导图分享)

    在完成了第二章的学习后,为了便于日后的复习整理,我制作了一张思维导图,有需要的可以自取. 基本数据类型 基础类型在cppreference网站上有非常完备的介绍,我一句话两句话也说不清,具体网址我会给 ...

  7. ABP EventBus(事件总线)

    事件总线就是订阅/发布模式的一种实现    事件总线就是为了降低耦合 1.比如在winform中  到处都是事件 触发事件的对象  sender 事件的数据    e 事件的处理逻辑  方法体 通过E ...

  8. spring环境搭建

    1.导入jar包: 2.配置文件 — applicationContext.xml:  添加schema约束,位置:spring-framework-3.2.0.RELEASE—>docs—&g ...

  9. 金蝶K3常用数据表

    金蝶K3WISE常用数据表 K3Wise 14.2 清空密码update t_User set FSID=') F ", ,P T #8 *P!D &D 80!N &@ &l ...

  10. JSP+MySQL最简单的登录和注册的实现 --Java Web温习

    一.开发环境 开发工具:eclipse 2018-09 操作系统:win10 二.实现 1.目录结构: 2.数据库(创建tmp数据库,新建user表,user表结构如下) 3.功能简介 功能比较简单, ...