tf.contrib.learn Quickstart

翻译自https://www.tensorflow.org/get_started/tflearn
tf的高级API能够更简单的配置、训练和评估多种机器学习模型,本文将介绍如何构建神经网络分类器,并在iris数据集上训练,用花萼和花瓣的集合结构来预测花的种类。有以下几个步骤:

  1. 载入包含iris训练测试数据的 CSVs 到 tf 的Dataset

  2. 构建神经网络分类器

  3. 用训练数据 Fit 模型

  4. 评估模型精度

  5. 分类新样本

iris数据被分为两部分

A training set of 120 samples (iris_training.csv)

A test set of 30 samples (iris_test.csv).

  • 导入所有的库
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"
Then, if the training and test sets aren't already 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)
  • 载入训练数据和测试数据到 Dataset ,使用load_csv_with_header()。由于最后的分类是整形数,所以合适的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)

training_set.data and training_set.target,test_set.dataandtest_set.target 包含训练和测试数据

  • 构建深度神经网络分类器
    tf.contrib.learn提供了多种预先定义好的模型,叫做Estimator,他们可以直接用在基于你自己数据的训练和评估操作。首先,我们来配置一个深度神经网络分类器来fit iris数据。你可以用以下几行代码来实例化一个分类器:
# Specify that all features have real-value data
feature_columns = [tf.contrib.layers.real_valued_column("", dimension=4)]

# Build 3 layer DNN with 10, 20, 10 units respectively.
classifier = tf.contrib.learn.DNNClassifier(feature_columns=feature_columns,
                                            hidden_units=[10, 20, 10],
                                            n_classes=3,
                                            model_dir="/tmp/iris_model")

以上代码首先定义了模型的特征列,并且指定了数据类型。所有的特征feature数据都是连续型,所以适合用tf.contrib.layers.real_valued_column来构建特征列,数据集里有4个特征维度sepal width, sepal height, petal width, and petal height,所以相应的维度需要设置为4.

  • 描述训练输入流程
    tf.contrib.learn 的API使用 为模型生成数据的TF 操作 作为输入函数。本例中数据很小,可以直接储存在tf.constant ,下面的代码实现最简单的输入流程:
# Define the train inputs
def get_train_inputs():
  x = tf.constant(training_set.data)
  y = tf.constant(training_set.target)

  return x, y
  • Fit the DNNClassifier to the Iris Training Data
    现在你已经配置好了你的DNN分类模型,你可以用fit方法来 训练你的数据, 传入 get_train_inputs 作为input_fn,还要传入训练的步数。
# Fit model.
classifier.fit(input_fn=get_train_inputs, steps=2000)

模型的状态被保存在classifier中,这就意味着你可以迭代的训练,例如,上面的代码等价于下面的

classifier.fit(x=training_set.data, y=training_set.target, steps=1000)
classifier.fit(x=training_set.data, y=training_set.target, steps=1000)

然而你要追踪模型的训练过程,你需要使用TF的monitor来进行记录操作。See the tutorial “Logging and Monitoring Basics with tf.contrib.learn” for more on this topic.

  • 评估模型精度
    你已经在iris数据集上训练过了DNNClassifier 模型,现在你可以使用evaluate方法检查他在测试集上的精度了。和fit方法一样,evaluate方法也要一个输入函数作为他的输入流程。evaluate方法返回一个包含评估结果的字典。下面的代码传入iris测试集test_set.data and test_set.target给evaluate,然后打印出来精度:
# Define the test inputs
def get_test_inputs():
  x = tf.constant(test_set.data)
  y = tf.constant(test_set.target)

  return x, y

# Evaluate accuracy.
accuracy_score = classifier.evaluate(input_fn=get_test_inputs,
                                     steps=1)["accuracy"]

print("\nTest Accuracy: {0:f}\n".format(accuracy_score))
  • 分类新的样本
    使用estimator的 predict()方法来分类新样本,返回一个生成器,可以很容易的转化为列表。下面代码做检索和打印预测结果:
# Classify two new flower samples.
def new_samples():
  return np.array(
    [[6.4, 3.2, 4.5, 1.5],
     [5.8, 3.1, 5.0, 1.7]], dtype=np.float32)

predictions = list(classifier.predict(input_fn=new_samples))

print("New Samples, Class Predictions:    {}\n"
    .format(predictions))

你可能感兴趣的:(tf.contrib.learn Quickstart)