tf.estimator

转载:https://blog.csdn.net/qq_17550379/article/details/78743343

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()
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87

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

将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"
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

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

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)
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

接下来,使用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)
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

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")
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

上面的代码首先定义模型的特征列,它指定数据集中特征的数据类型。所有的特征数据都是连续的,所以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)
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

将DNNClassifier安装到Iris训练数据

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

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

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

classifier.train(input_fn=train_input_fn, steps=1000)
classifier.train(input_fn=train_input_fn, steps=1000)
   
   
  • 1
  • 2

但是,如果您希望在训练时跟踪模型,则可能需要使用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))
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

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

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

Test Accuracy: 0.966667
   
   
  • 1

您的准确性结果可能会有所不同,但应该高于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))
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

你的结果应该如下所示:

New Samples, Class Predictions:    [1 2]
   
   
  • 1

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

猜你喜欢

转载自blog.csdn.net/a1111h/article/details/82053484