tensorflow estimator API小栗子
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:
- 120个样本的训练集(iris_training.csv)
- 30个样本的测试集(iris_test.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中的数据集被命名为元组;您可以通过data和target字段访问特征数据和目标值。这里,training_set.data和training_set.target分别包含训练集的特征数据和目标值,test_set.data和test_set.target包含测试集的特征数据和目标值。
稍后,在“将DNNClassifier安装到Iris训练数据”中,您将使用training_set.data和training_set.target来训练您的模型,在“Evaluate Model Accuracy”中,您将使用test_set.data和test_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.data和test_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小栗子的更多相关文章
- TensorFlow 1.4利用Keras+Estimator API进行训练和预测
Tensorflow 1.4中,Keras作为作为核心模块可以直接通过tf.keas进行调用,但是考虑到keras对tfrecords文件进行操作比较麻烦,而将keras模型转成tensorflow中 ...
- Javaweb统计在线人数的小栗子
最近在学习Javaweb相关的内容(不黑不吹之前对web开发零基础),下面通过一个统计在线人数的小栗子讲讲Servlet监听器吧 开发环境 eclipse tomcat 7 先说说这个小栗子的构思: ...
- cookie小栗子-实现简单的身份验证
关于Cookie Cookie是一种能够让网站Web服务器把少量数据储存到客户端的硬盘或内存里,或是从客户端的硬盘里读取数据的一种技术. 用来保存客户浏览器请求服务器页面的请求信息,可以在HTTP返回 ...
- 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 ...
- SpringBoot+Shiro+Redis共享Session入门小栗子
在单机版的Springboot+Shiro的基础上,这次实现共享Session. 这里没有自己写RedisManager.SessionDAO.用的 crazycake 写的开源插件 pom.xml ...
- SpringBoot+Shiro入门小栗子
写一个不花里胡哨的纯粹的Springboot+Shiro的入门小栗子 效果如图: 首页:有登录注册 先注册一个,然后登陆 登录,成功自动跳转到home页 home页:通过认证之后才可以进 代码部分: ...
- 一个小栗子聊聊JAVA泛型基础
背景 周五本该是愉快的,可是今天花了一个早上查问题,为什么要花一个早上?我把原因总结为两点: 日志信息严重丢失,茫茫代码毫无头绪. 对泛型的认识不够,导致代码出现了BUG. 第一个原因可以通过以后编码 ...
- TensorFlow dataset API 使用
# TensorFlow dataset API 使用 由于本人感兴趣的是自然语言处理,所以下面有关dataset API 的使用偏向于变长数据的处理. 1. 从迭代器中引入数据 import num ...
- java网络爬虫爬虫小栗子
简要介绍: 使用java开发的爬虫小栗子,存储到由zookeeper协调的hbase中 主要过程是模拟Post请求和get请求,html解析,hbase存储 源码:https://github.com ...
随机推荐
- Android组件系列----Intent详解(转载笔记)
[正文] Intent组件虽然不是四大组件,但却是连接四大组件的桥梁,学习好这个知识,也非常的重要. 一.什么是Intent 1.Intent的概念: Android中提供了Intent机制来协助应用 ...
- 面试小记---java基础知识
**static 和 final 的理解** static:是静态变量修饰符,修饰的是全局变量,所以对象是共享的,在开始类设计的初期就分配空间. final:声明式属性,方法,类.分别表示属 ...
- 浅谈装饰器(Python)
先来了解函数和执行函数在python的区别 我再重新定义一个函数,在函数前面加上@set_func 执行结果如下: 函数前面没有加@set_fun 执行结果如下: 是不是可以不修改原来的函 ...
- pam密码策略
PAM 的使用历史 PAM 是关注如何为服务验证用户的 API.在使用 PAM 之前,诸如 login(和 rlogin.telnet.rsh)之类的应用程序在 /etc/passwd 中查找用户名, ...
- html2canvas文字重叠(手机端)
发现情况: 1.设置文字居中,文字自动换行后文字有重叠 text-align: center; 解决办法: text-align: left; text-align: justify;等 2.使用 ...
- poi 导入Excle
一,AOP 是什么 Apache POI 提供java 程序对Microsoft Office格式文档的读写功能操作 二,所需要的jar包 三,实现代码 1, 读取Excle 返回Workbook格式 ...
- 【GO】【gdb】
1 安装homebrew 参考 https://www.cnblogs.com/suren2017/p/9249803.html ([Ruby][环境搭建]macOS Sierra 10.12.6 + ...
- libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)
In Xcode 9 and Swift 4: Print exception stack to know the reason of the exception: Go to show break ...
- day2——两数相加
// 小白一名,0算法基础,艰难尝试算法题中,若您发现本文中错误, 或有其他见解,往不吝赐教,感激不尽,拜谢. 领扣 第2题 今日算法题干//给定两个非空链表来表示两个非负整数.位数按照逆序方式存储, ...
- loadrunner场景之集合点设置技巧
在loadrunner的虚拟用户中,术语concurrent(并发)和simultaneous(同时)存在一些区别,concurrent 是指虚拟场景中参于运行的虚拟用户. 而simultaneous ...