tf.estimator 快速入门

我是一个很懒的人,我想试试

希望我能坚持到最后,把tensorflow的官方教程全部翻译出来

提高自己,也帮助他人

我的博客:终身学习者

tf.estimator Quickstart

TensorFlow 的高层次机器学习 API(tf.estimator) 使得配置,训练,和评估各种各样的机器学习模型变得更加的容易。在本教程中,你将使用 tf.estimator 构造一个神经网络分类器,在 Iris 数据集 上训练,并通过花的萼片和花瓣的几何形状预测花的品种。你将编写代码来实现以下五个步骤:

  1. 读取包含 Iris 训练/测试数据的 CSVs 数据格式,到TensorFlow Dataset
  2. 构造一个 神经网络分类器
  3. 使用训练数据训练模型
  4. 评估模型的准确性
  5. 分类新的样本

注意:请在开始本教程前, 安装 TensorFlow 到你的机器上

Complete Neural Network Source Code

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

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

以下部分将详细介绍代码细节。

Load the Iris CSV data to TensorFlow

Iris 数据集 包含了 150 行数据,三种相关的 Iris 品种,每种 Iris 品种有 50 个样本: Iris setosaIris virginica,和Iris versicolor

tf.estimator 快速入门_第1张图片
Petal geometry compared for three iris species: Iris setosa, Iris virginica, and Iris versicolor
从左到右, Iris setosa (by Radomil, CC BY-SA 3.0),Iris versicolor (by Dlanglois, CC BY-SA 3.0),和 Iris virginica(by Frank Mayfield, CC BY-SA 2.0).

对于每个花朵样本,每一行都包含了以下数据:萼片长度,萼片宽度, 花瓣长度,花瓣宽度和花的品种。花的品种用整数型数字表示,0表示Iris setosa,1表示Iris versicolor

Sepal Length Sepal Width Petal Length Petal Width Species
5.1 3.5 1.4 0.2 0
4.9 3.0 1.4 0.2 0
4.7 3.2 1.3 0.2 0
7.0 3.2 4.7 1.4 1
6.4 3.2 4.5 1.5 1
6.9 3.1 4.9 1.5 1
6.5 3.0 5.2 2.0 2
6.2 3.4 5.4 2.3 2
5.9 3.0 5.1 1.8 2

本教程中,Iris 数据随机打乱并划分成两个独立的 CSV 数据集:

  • 包含 120 个样本的训练集 (iris_training.csv)
  • 包含 30 个样本的测试集 (iris_test.csv)

开始前,首先 import 进所有的需要的模块,并定义哪里下载数据和存储数据集:

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() 方法读取训练和测试数据集,加载到 Dataset 中。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)

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

稍后,在 "Fit the DNNClassifier to the Iris Training Data," 你将使用training_set.datatraining_set.target训练你的模型,在"Evaluate Model Accuracy," 你将使用 test_set.datatest_set.target。但首先,你将在下一节中构造你的模型。

Construct a Deep Neural Network Classifier

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 是用于构造特征列的适当函数。这里有四个特征在数据集中(萼片宽度,萼片长度,花瓣宽度和花瓣长度),于是shape 必须设置为[4]以适应所有的数据。

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

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

Describe the training input pipeline

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)

Fit the DNNClassifier to the Iris Training Data

现在,你已经配置了你的 DNN classifier 模型,你可以使用 train 方法将模型拟合 Iris 训练数据。将 train_input_fn 传递给input_fn,并设置训练的次数(这里是 2000):

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

模型的状态是保存在classifier,这意味着如果你喜欢你可以迭代训练模型。例如,以上代码等同于以下代码:

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

然而,如果你希望在训练的过程中跟踪模型,则你可能更需要使用TensorFlow 的 SessionRunHook 来执行日志操作记录。

Evaluate Model Accuracy

你已经在 Iris 训练数据上训练了你的DNNClassifier模型。现在你可以在 Iris 测试数据上使用 evaluate 方法来检测模型的准确性。像train那样,evaluate 使用输入函数构建它的输入管道。evaluate返回一个包含评估结果的dict。以下代码传递 Iris 测试数据——test_set.datatest_set.targetevaluate 并从结果中打印 accuracy

# 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%。对于一个相对较小的数据集来说这并不算太差!

Classify New Samples

使用 estimator 的 predict() 方法来分类新的样本。例如,假如你有这两个新的花的样本:

Sepal Length Sepal Width Petal Length Petal Width
6.4 3.2 4.5 1.5
5.8 3.1 5.0 1.7

你可以使用predict() 方法预测它们的品种。 predict返回一个dict,你可以简单的将其转为 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 Predictions:    {}\n"
    .format(predicted_classes))

你的结果看起来如下:

New Samples, Class Predictions:    [1 2]

因此你的模型预测了第一个样本是Iris versicolor,而第二个样本是 Iris virginica

Additional Resources

  • 欲了解更多有关使用 tf.estimator 创建线性模型,请查阅 Large-scale Linear Models with TensorFlow。
  • 要使用 tf.estimator APIs 构建你子集的 Estimator,请查阅Creating Estimators in tf.estimator 。
  • 为了在浏览器中实现神经网络建模并可视化,请查阅Deep Playground。
  • 有关神经网络更高级的教程,请查阅 Convolutional Neural Networks 和Recurrent Neural Networks。

你可能感兴趣的:(tf.estimator 快速入门)