前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >TensorFlow快速入门

TensorFlow快速入门

作者头像
周小董
发布2019-03-25 09:56:44
7100
发布2019-03-25 09:56:44
举报
文章被收录于专栏:python前行者python前行者

学习资料: https://www.tensorflow.org/get_started/tflearn

相应的中文翻译: http://studyai.site/2017/03/05/%E3%80%90Tensorflow%20r1.0%20%E6%96%87%E6%A1%A3%E7%BF%BB%E8%AF%91%E3%80%91%E3%80%90tf.contrib.learn%E5%BF%AB%E9%80%9F%E5%85%A5%E9%97%A8%E3%80%91/

  • 问题:

我们有 Iris 数据集,它包含150个样本数据,分别来自三个品种,每个品种有50个样本,每个样本具有四个特征,以及它属于哪一类,分别由 0,1,2 代表三个品种。

我们将这150个样本分为两份,一份是训练集具有120个样本,另一份是测试集具有30个样本。

我们要做的就是建立一个神经网络分类模型对每个样本进行分类,识别它是哪个品种。

一共有 5 步:

导入 CSV 格式的数据集 建立神经网络分类模型 用训练数据集训练模型 评价模型的准确率 对新样本数据进行分类

代码:

代码语言:javascript
复制
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
  # 指定数据的形式,下面的意思是形成一个4维度,列名为"",数据格式为float32(默认)的形式。
  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")
  # Define the training inputs
  def get_train_inputs():
    x = tf.constant(training_set.data)
    y = tf.constant(training_set.target)

    return x, y

  # Fit model.
  classifier.fit(input_fn=get_train_inputs, steps=2000)

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

  # Classify two new flower samples.
  # predict参数函数只要返回一个数据矩阵即可
  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))

if __name__ == "__main__":
    main()

关于?tf.contrib.learn?可以查看:?https://www.tensorflow.org/api_guides/python/contrib.learn

可以看到里面也有?kmeans,logistic,linear?等模型:

image
image

在上面的代码中:

  • 用?tf.contrib.learn.datasets.base.load_csv_with_header?可以导入 CSV 数据集。
  • 分类器模型只需要一行代码,就可以设置这个模型具有多少隐藏层,每个隐藏层有多少神经元,以及最后分为几类。
  • 模型的训练也是只需要一行代码,输入指定的数据,包括特征和标签,再指定迭代的次数,就可以进行训练。
  • 获得准确率也同样很简单,只需要输入测试集,调用 evaluate。
  • 预测新的数据集,只需要把新的样本数据传递给 predict。

关于代码里几个新的方法:

1.?load_csv_with_header():

用于导入 CSV,需要三个必需的参数:

  • filename,CSV文件的路径
  • target_dtype,数据集的目标值的numpy数据类型。
  • features_dtype,数据集的特征值的numpy数据类型。

在这里,target 是花的品种,它是一个从 0-2 的整数,所以对应的numpy数据类型是np.int

2.?tf.contrib.layers.real_valued_column:

所有的特征数据都是连续的,因此用 tf.contrib.layers.real_valued_column,数据集中有四个特征(萼片宽度,萼片高度,花瓣宽度和花瓣高度),因此 dimension=4 。

代码语言:javascript
复制
feature_columns = [tf.contrib.layers.real_valued_column("", dimension=4)]

3.?DNNClassifier:

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

Logging and Monitoring Basics with tf.contrib.learn

这部分主要是模型训练的监控,主要利用TensorFlow的 logging capabilities(记录功能)和Monitor API 。如果没有过程记录,其实整个算法就和黑盒子一样什么都看不到,比如有的时候可能模型在很早就已经收敛了或者看看模型是不是early stopping了是很必要的。?

一种解决方法是多次使用fit来一步一步评估模型,但是这明显很慢所以并不建议使用,所以 tf.contrib.learn提供了Monitor API帮助我们在训练过程中评估模型,下面内容主要有三个过程:

  • 如何进行记录
  • 如何设置一个ValidationMonitor进行流式的监控
  • 在TensorBoard上进行可视化

(1)Logging with TensorFlow记录

Tensorflow记录有5个等级DEBUG, INFO, WARN, ERROR, and FATAL(严重程度升序),比如我设计记录等级是INFO,那么我就屏蔽了Debug的内容但是保留高等级的记录信息。默认配置的记录等级是WARN也就是我们平时看到的,因为我们平时并没有看到INFO和DEBUG的信息。但是现在,因为我们要进行模型评估所以调整记录等级为INFO。? 方法是在import后面加上:

代码语言:javascript
复制
tf.logging.set_verbosity(tf.logging.INFO)

这时候运行代码的时候就会看到:

代码语言:javascript
复制
INFO:tensorflow:loss = 1.18812, step = 1
INFO:tensorflow:loss = 0.210323, step = 101
INFO:tensorflow:loss = 0.109025, step = 201

而且tf.contrib.learn会自动的每100个step输出训练损失评估指标到stderr。

(2)ValidationMonitor进行流式监控

tf.contrib.learn提供了一些高级的Monitor帮助我们在fit的时候进一步进行更细微的监控

Monitor

描述

CaptureVariable

每n个step保存一个特殊的变量值

PrintTensor

每n个step记录一个特殊的tensor值

SummarySaver

每n个step用tf.summary.FileWriter保存给定的tensor到tf.Summary protocol buffers

ValidationMonitor

每n个step记录一个特定的评估指标集合,而且可以满足条件情况下设置早停止

我们如果想要在训练的同时评估测试集的结果,就可以使用ValidationMonitor作用在测试数据上。默认的every_n_steps为100,这里我们设置every_n_steps为50,并把下面的程序放到classifier的后面 :

代码语言:javascript
复制
validation_monitor = tf.contrib.learn.monitors.ValidationMonitor(
    test_set.data,
    test_set.target,
    every_n_steps=50)

因为ValidationMonitor依赖于保存当前的checkpoint进行评估操作,所以我们需要在classifier中加入tf.contrib.learn.RunConfig(包含save_checkpoints_secs这个记录着保存两次checkpoint的时间差),因为iris训练数据少,所以可以设置save_checkpoints_secs为1

代码语言:javascript
复制
#model_dir保存着checkpoint是可以断点再训练的关键
classifier = tf.contrib.learn.DNNClassifier(
    feature_columns=feature_columns,
    hidden_units=[10, 20, 10],
    n_classes=3,
    model_dir="/tmp/iris_model",
    config=tf.contrib.learn.RunConfig(save_checkpoints_secs=1))

最终在fit的时候要附上validation_monitor,注意需要一个列表封装,因为可以同时有几种monitor存在:

代码语言:javascript
复制
classifier.fit(x=training_set.data,
               y=training_set.target,
               steps=2000,
               monitors=[validation_monitor])

最终得到的结果应该类似于:

代码语言:javascript
复制
INFO:tensorflow:Validation (step 50): loss = 1.71139, global_step = 0, accuracy = 0.266667
...
INFO:tensorflow:Validation (step 300): loss = 0.0714158, global_step = 268, accuracy = 0.966667
...
INFO:tensorflow:Validation (step 1750): loss = 0.0574449, global_step = 1729, accuracy = 0.966667

流式监控进阶内容

1.自定义度量:? 可以看到ValidationMonitor会记录loss和accuracy,但是我们同样可以自定义度量方法。可以在ValidationMonitor的构造函数上加入metrics参数,其参数是一个键值对,键为想要记录的度量的名称,值为相应的MetricSpec对象。?

MetricSpec对象可以接收下面几个参数(这里不是很明白):

  • metric_fn:计算并返回度量值的函数,可以使用现有的tf.contrib.metrics.streaming_precision或tf.contrib.metrics.streaming_recall也可以定制自己的函数
  • prediction_key:可以看成是预测结果的类别,包括:CLASSES、LOGISTIC、PROBABILITIES、SCORES、TOP_K等
  • label_key:这个在input_fn使用的时候才用
  • weights_key:? 下面的代码就定义了三种度量方法:
代码语言:javascript
复制
validation_metrics = {
    "accuracy":
        tf.contrib.learn.MetricSpec(
            metric_fn=tf.contrib.metrics.streaming_accuracy,
            prediction_key=tf.contrib.learn.PredictionKey.CLASSES),
    "precision":
        tf.contrib.learn.MetricSpec(
            metric_fn=tf.contrib.metrics.streaming_precision,
            prediction_key=tf.contrib.learn.PredictionKey.CLASSES),
    "recall":
        tf.contrib.learn.MetricSpec(
            metric_fn=tf.contrib.metrics.streaming_recall,
            prediction_key=tf.contrib.learn.PredictionKey.CLASSES)
}

把这个字典放入validation_monitor的metrics参数中,即metrics=validation_metrics,得到的结果如下:

代码语言:javascript
复制
INFO:tensorflow:Validation (step 50): recall = 0.0, loss = 1.20626, global_step = 1, precision = 0.0, accuracy = 0.266667
...
INFO:tensorflow:Validation (step 600): recall = 1.0, loss = 0.0530696, global_step = 571, precision = 1.0, accuracy = 0.966667
...
INFO:tensorflow:Validation (step 1500): recall = 1.0, loss = 0.0617403, global_step = 1452, precision = 1.0, accuracy = 0.966667

2.早停止:? 我们可以设置早停止选项在需要停止的时候停止训练:

参数

描述

early_stopping_metric

早停止指标如loss或者accuracy

early_stopping_metric_minimize

True代表希望最小化上面的指标,False希望最大化上面的指标

early_stopping_rounds

默认是None也就是不会早停止,如果是n就代表指标在n轮都不变那就停止

代码语言:javascript
复制
validation_monitor = tf.contrib.learn.monitors.ValidationMonitor(
    test_set.data,
    test_set.target,
    every_n_steps=50,
    metrics=validation_metrics,
    early_stopping_metric="loss",
    early_stopping_metric_minimize=True,
    early_stopping_rounds=200)

结果是:

代码语言:javascript
复制
...
INFO:tensorflow:Validation (step 1150): recall = 1.0, loss = 0.056436, global_step = 1119, precision = 1.0, accuracy = 0.966667
INFO:tensorflow:Stopping. Best step: 800 with loss = 0.048313818872.

接着就可以直接在TensorBoard上看结果了,注意logdir的地址:

代码语言:javascript
复制
$ tensorboard --logdir=/tmp/iris_model/
Starting TensorBoard 39 on port 6006

(3)全部程序

代码语言:javascript
复制
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os

import numpy as np
import tensorflow as tf

tf.logging.set_verbosity(tf.logging.INFO)

# Data sets
IRIS_TRAINING = os.path.join(os.path.dirname(__file__), "iris_training.csv")
IRIS_TEST = os.path.join(os.path.dirname(__file__), "iris_test.csv")

def main(unused_argv):
  # Load datasets.
  training_set = tf.contrib.learn.datasets.base.load_csv_with_header(
      filename=IRIS_TRAINING, target_dtype=np.int, features_dtype=np.float)
  test_set = tf.contrib.learn.datasets.base.load_csv_with_header(
      filename=IRIS_TEST, target_dtype=np.int, features_dtype=np.float)

  validation_metrics = {
      "accuracy":
          tf.contrib.learn.MetricSpec(
              metric_fn=tf.contrib.metrics.streaming_accuracy,
              prediction_key="classes"),
      "precision":
          tf.contrib.learn.MetricSpec(
              metric_fn=tf.contrib.metrics.streaming_precision,
              prediction_key="classes"),
      "recall":
          tf.contrib.learn.MetricSpec(
              metric_fn=tf.contrib.metrics.streaming_recall,
              prediction_key="classes")
  }
  validation_monitor = tf.contrib.learn.monitors.ValidationMonitor(
      test_set.data,
      test_set.target,
      every_n_steps=50,
      metrics=validation_metrics,
      early_stopping_metric="loss",
      early_stopping_metric_minimize=True,
      early_stopping_rounds=200)

  # 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",
      config=tf.contrib.learn.RunConfig(save_checkpoints_secs=1))

  # Fit model.
  classifier.fit(x=training_set.data,
                 y=training_set.target,
                 steps=2000,
                 monitors=[validation_monitor])

  # Evaluate accuracy.
  accuracy_score = classifier.evaluate(
      x=test_set.data, y=test_set.target)["accuracy"]
  print("Accuracy: {0:f}".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=float)
  y = list(classifier.predict(new_samples))
  print("Predictions: {}".format(str(y)))

if __name__ == "__main__":
  tf.app.run()

参考:https://blog.csdn.net/woaidapaopao/article/details/73007741?locationNum=10&fps=1#quickstart

本文参与?腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018年08月30日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客?前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与?腾讯云自媒体分享计划? ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Logging and Monitoring Basics with tf.contrib.learn
    • (1)Logging with TensorFlow记录
      • (2)ValidationMonitor进行流式监控
        • (3)全部程序
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
        http://www.vxiaotou.com