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 ...
随机推荐
- 【MySQL】redo log --- 刷入磁盘过程
1.redo log基本概念 redo log的相关概念这里就不再过多阐述,网上有非常多的好的资料,可以看下缥缈大神的文章:https://www.cnblogs.com/cuisi/p/652507 ...
- 使用proces explorer查看系统gdi
用mfc开发,使用双缓冲刷新屏幕时,可能会造成GDI的增长,当增长到一定数量[10000]时,软件会崩,可以通过 proces explorer来监测GDI,调试代码 打开proces explore ...
- npm 是node.js下带的一个包管理工具
npm 是node.js下带的一个包管理工具 npm install -g webpack webpack是一个打包工具 gulp是一个基于流的构建工具,相对其他构件工具来说,更简洁 ...
- HDU 2665 Kth number(主席树静态区间第K大)题解
题意:问你区间第k大是谁 思路:主席树就是可持久化线段树,他是由多个历史版本的权值线段树(不是普通线段树)组成的. 具体可以看q学姐的B站视频 代码: #include<cmath> #i ...
- 【做题】ECFinal2018 J - Philosophical … Balance——dp
原文链接 https://www.cnblogs.com/cly-none/p/ECFINAL2018J.html 题意:给出一个长度为\(n\)的字符串\(s\),要求给\(s\)的每个后缀\(s[ ...
- Codeforces Global Round 1 解题报告
A 我的方法是: #include<bits/stdc++.h> using namespace std; #define int long long typedef long long ...
- c语言程序操作
- 使用教育邮箱激活JetBrains全家桶
如果你还有在校时的邮箱,比如your_name@xxx.edu或者your_name@xxx.edu.cn的邮箱,那么你可以免费激活JetBrains全家桶. JetBrains Toolbox 专业 ...
- 全景拍摄,全景视频拍摄,全景VR拍摄,VR全景拍摄,360全景图片拍摄
北京动软专业提供基于手机.VR设备.PC浏览器的全景拍摄和项目展示服务. 承接服务内容包括720°全景拍摄展示.VR虚拟现实全景.全景漫游.全景视频.物体全景.环物全景等. 全景展示主要应用于展览 ...
- vue 组件复用不刷新
情景: 两个路由"/a", "/b"公用一个页面组件, 在"/a"路由中, 第一列是序号, 在"/b"路由中, 第一列是 ...