tf.estimator Quickstart

setosa--versicolor--virginica

文章类型:翻译
文章内容:

  • 1、完整的神经网络源代码
  • 2、加载 Iris CSV数据到Tensorflow
  • 3、构建深度神经网络分类器
  • 4、数据输入管道
  • 5、利用 Iris data拟合神经网络分类器
  • 6、评估神经网络分类器的准确性
  • 7、对新样本进行分类
  • 8、其他资源

前沿


Tensorflow的高级机器学习API(tf.estimator)使得配置、训练和评估各种机器学习模型更加的简单。在本教程中,你将使用tf.estimator构建一个神经网络分类器,用于训练 Iris data,构建一个预测 Iris flower的模型,并预测新的Iris flower。你将编写代码完成以下五个步骤:

  • 1、将包含训练集和测试集的CSV数据加载到Tensorflow Dataset
    2、构建神经网络模型分类器
    3、利用训练数据训练模型
    4、评估模型的精度
    5、分类新的样本
    

注意:在学习本教程之前,请在您的机器上安装Tensorflow。

一、完整的神经网络源代码


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

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import urllib

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 = urllib.urlopen(IRIS_TRAINING_URL).read()
    with open(IRIS_TRAINING, "w") as f:
      f.write(raw)

  if not os.path.exists(IRIS_TEST):
    raw = urllib.urlopen(IRIS_TEST_URL).read()
    with open(IRIS_TEST, "w") 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 数据被随机分成两部分:

部分数据集

开始,要加载必要的模块,然后定义在哪里去下载并保存数据集

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import urllib

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 = urllib.urlopen(IRIS_TRAINING_URL).read()
  with open(IRIS_TRAINING,'w') as f:
    f.write(raw)

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

接下来,使用模块learn.datasets.base中的load_csv_with_header()加载训练集和测试集到 Datasets,该模块包含三个必须的参数:

  •  1、filename,它将文件路径转化为CSV文件。
     2、target_dtype,获取数据集目标值的numpy datatype。
     3、feature_dtype,获取训练集特征值的numpy datatype。
    

此处,target表示花的种类,它是[0, 2]之间的整数,所以 target_dtypenp.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)

Datasets in tf.contrib.learn are named tuples;你可以通过data and target field 访问特征数据和目标数据。此处,training_set.datatraining_set.target包含了训练集的特征数据和目标数据;test_set.datatest_set.target包含测试集的特征数据和目标数据。
稍后,在利用 Iris data拟合神经网络分类器中看到training_set.datatraining_set.target训练你的模型。在评估神经网络分类器的准确性中,你将使用test_set.datatest_set.target。但是首先,在下一节中你要构建你的模型。

三、构建深度神经网络分类器


tf.estimator提供了很多各种预定义的模型,称之为“Estimator”,利用它你可以在数据集之上进行训练和评估。在此部分,你将配置深度神经网络分类器模型去拟合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(该函数返回一个实数列)是构建特征数据非常合适的函数。在数据集中总共有四个特征(sepal width,sepal height,petal width,petal height),所以形状必须被设置为 [4] 来保存所有的数据。
然后,创建DNNClassifier模型需要用到以下参数:

  •   1、feature_columns = feature_columns。设置特征列。
      2、hidden_units = [10, 20, 10]。设置隐含层。   
      3、n_classes = 3。表示三个目标分类
      4、model_dir = "/tmp/iris_model" ,存储checkpoint数据和TensorBoard summaries数据的目录   
    

四、数据输入管道


tf.estimator API使用input 函数,这个将创建一个Tensorflow操作用于为模型产生数据。我们使用 tf.estimator.inputs.numpy_input_fn 产生 input 的管道。

# 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)

五、利用 Iris data拟合神经网络分类器


现在你可以配置DNN 分类器的模型了,你可以把模型放在训练集上进行训练。训练的步数为2000次

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

模型的状态保存在分类器中,也就是说,如果你喜欢的话,你可以反复训练。例如,以下的训练方式是等效的。

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

不管怎么样,如果你想在训练过程中追踪模型,你可以需要使用TensorFlow SessionRunHook来执行日志操作。

六、评估神经网络分类器的准确性


以下代码表示在测试集上评估模型的精度。

# 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)

注意:这里的num_epochs = 1的参数非常重要。test_input_fn将迭代数据集一次,然后发送 OutOfRangeError。这个错误信号标志着分类器停止评估,所以它会对输入进行一次评估。
当你运行整个脚本的时候,会打印如下数据:

Test Accuracy: 0.966667

你的准确性可能会有所不同,但应该会高于90%。这对于一个较小的数据集而言并不坏。

七、对新样本进行分类


使用estimatorpredict() 方法可以分类新的样本。例如,以下有两个新样本。

带分类样本

使用predict()函数会返回一个dicts,它可以很简单的转化为list,下面的代码检索并打印出结果。

# 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 Preditions: {}\n".format(predicted_classes)

所得的结果如下:

New Samples, Class Predictions: [1 2]

因此该模型预测的第一个样本为Iris versicolor,第二个样本是Iris virginica

八、其他资源


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 222,000评论 6 515
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,745评论 3 399
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 168,561评论 0 360
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,782评论 1 298
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,798评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,394评论 1 310
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,952评论 3 421
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,852评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,409评论 1 318
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,483评论 3 341
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,615评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,303评论 5 350
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,979评论 3 334
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,470评论 0 24
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,571评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 49,041评论 3 377
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,630评论 2 359

推荐阅读更多精彩内容