tf.estimator Quickstart(tf.estimator快速入门)

tf.estimator快速入门

TensorFlow的高级机器学习API(tf.estimator)可以轻松配置,训练和评估各种机器学习模型。在本教程中,您将使用tf.estimator构建神经网络分类器,并在Iris数据集上对其进行训练,以根据萼片/花瓣几何图形预测花朵种类。您将编写代码来执行以下五个步骤:

1. 将包含IRIS训练/测试数据的CSV加载到TensorFlow的 Dataset

2. 构建一个神经网络分类器

3. 使用训练数据训练模型

4. 评估模型的准确性

5. 分类新样品

注意:在开始本教程之前,请记住在您的机器上安装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()

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

将鸢尾花CSV数据加载到TensorFlow

该鸢尾花数据集包含150行数据,包括50个样品来自三个相关鸢尾种类:山鸢尾虹膜锦葵,和变色鸢尾

从左到右,山鸢尾 (由 Radomil,CC BY-SA 3.0),变色鸢尾( Dlanglois,CC BY-SA 3.0)和 锦葵鸢尾(byFrank Mayfield, CC BY-SA 2.0).

每行包含每个花样的以下数据:萼片长度,萼片宽度,花瓣长度,花瓣宽度和花朵种类。花物种被表示为整数,其中0表示鸢尾花,1表示鸢尾花,2表示鸢尾花

Sepal LengthSepal WidthPetal LengthPetal WidthSpecies
5.13.51.40.20
4.93.01.40.20
4.73.21.30.20
7.03.24.71.41
6.43.24.51.51
6.93.14.91.51
6.53.05.22.02
6.23.45.42.32
5.93.05.11.82

在本教程中,鸢尾花数据已被随机分成两个独立的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()方法将训练和测试集加载到Datasets 中。该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)

Datasets 在 tf.contrib.learn中被命名为元组 ; 您可以通过datatarget字段访问功能数据和目标值。在这里,training_set.datatraining_set.target包含用于训练集,分别特征数据和目标值,test_set.datatest_set.target含有特征数据和目标值的测试集。

稍后,在“将DNNClassifier安装到虹膜培训数据”中,您将使用training_set.datatraining_set.target训练您的模型,并在“评估模型精度”中,您将使用test_set.datatest_set.target。但首先,您将在下一节中构建您的模型。

构建深度神经网络分类器

tf.estimator提供了多种预定义的模型,称为Estimators,您可以使用“开箱即用”对数据运行培训和评估操作。在这里,您将配置深度神经网络分类器模型以适应虹膜数据。使用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。三个目标类别,代表三个虹膜物种。

  • model_dir=/tmp/iris_model。TensorFlow将在模型训练期间保存检查点数据和TensorBoard摘要的目录。

描述训练输入流水线

tf.estimatorAPI使用输入功能,其创建用于生成模型数据中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安装到虹膜培训数据

现在您已经配置了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模型; 现在,您可以使用该evaluate方法检查虹膜测试数据的准确性。就像trainevaluate建立输入管道的输入函数。evaluatedict评估结果返回给s。以下代码传递Iris测试数据 - test_set.datatest_set.target- 去评估并从结果中打印出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))

注意:这里的num_epochs=1参数numpy_input_fn很重要。test_input_fn将迭代数据一次,然后提高OutOfRangeError。这个错误表示分类器停止评估,因此它将对输入进行一次评估。

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

Test Accuracy: 0.966667

您的准确性结果可能会有所不同,但应高于90%。一个相对较小的数据集不坏!

分类新样品

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

Sepal LengthSepal WidthPetal LengthPetal Width
6.43.24.51.5
5.83.15.01.7

您可以使用该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]

因此,模型预测第一个样本是变色鸢尾花,第二个样本是虹膜锦葵。

其他资源

  • 要了解有关使用tf.estimator创建线性模型的更多信息,请参阅使用TensorFlow的大规模线性模型。

  • 要使用tf.estimator API构建您自己的Estimator,请查看tf.estimator中的Creating Estimators。

  • 要在浏览器中尝试神经网络建模和可视化,请查看Deep Playground

  • 有关神经网络的更高级教程,请参阅卷积神经网络和递归神经网络。