Home | History | Annotate | Download | only in learn
      1 #  Copyright 2016 The TensorFlow Authors. All Rights Reserved.
      2 #
      3 #  Licensed under the Apache License, Version 2.0 (the "License");
      4 #  you may not use this file except in compliance with the License.
      5 #  You may obtain a copy of the License at
      6 #
      7 #   http://www.apache.org/licenses/LICENSE-2.0
      8 #
      9 #  Unless required by applicable law or agreed to in writing, software
     10 #  distributed under the License is distributed on an "AS IS" BASIS,
     11 #  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     12 #  See the License for the specific language governing permissions and
     13 #  limitations under the License.
     14 """Example of DNNClassifier for Iris plant dataset, with exponential decay."""
     15 
     16 from __future__ import absolute_import
     17 from __future__ import division
     18 from __future__ import print_function
     19 
     20 import numpy as np
     21 from sklearn import datasets
     22 from sklearn import metrics
     23 from sklearn import model_selection
     24 import tensorflow as tf
     25 
     26 
     27 X_FEATURE = 'x'  # Name of the input feature.
     28 
     29 
     30 def my_model(features, labels, mode):
     31   """DNN with three hidden layers."""
     32   # Create three fully connected layers respectively of size 10, 20, and 10.
     33   net = features[X_FEATURE]
     34   for units in [10, 20, 10]:
     35     net = tf.layers.dense(net, units=units, activation=tf.nn.relu)
     36 
     37   # Compute logits (1 per class).
     38   logits = tf.layers.dense(net, 3, activation=None)
     39 
     40   # Compute predictions.
     41   predicted_classes = tf.argmax(logits, 1)
     42   if mode == tf.estimator.ModeKeys.PREDICT:
     43     predictions = {
     44         'class': predicted_classes,
     45         'prob': tf.nn.softmax(logits)
     46     }
     47     return tf.estimator.EstimatorSpec(mode, predictions=predictions)
     48 
     49   # Compute loss.
     50   loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits)
     51 
     52   # Create training op with exponentially decaying learning rate.
     53   if mode == tf.estimator.ModeKeys.TRAIN:
     54     global_step = tf.train.get_global_step()
     55     learning_rate = tf.train.exponential_decay(
     56         learning_rate=0.1, global_step=global_step,
     57         decay_steps=100, decay_rate=0.001)
     58     optimizer = tf.train.AdagradOptimizer(learning_rate=learning_rate)
     59     train_op = optimizer.minimize(loss, global_step=global_step)
     60     return tf.estimator.EstimatorSpec(mode, loss=loss, train_op=train_op)
     61 
     62   # Compute evaluation metrics.
     63   eval_metric_ops = {
     64       'accuracy': tf.metrics.accuracy(
     65           labels=labels, predictions=predicted_classes)
     66   }
     67   return tf.estimator.EstimatorSpec(
     68       mode, loss=loss, eval_metric_ops=eval_metric_ops)
     69 
     70 
     71 def main(unused_argv):
     72   iris = datasets.load_iris()
     73   x_train, x_test, y_train, y_test = model_selection.train_test_split(
     74       iris.data, iris.target, test_size=0.2, random_state=42)
     75 
     76   classifier = tf.estimator.Estimator(model_fn=my_model)
     77 
     78   # Train.
     79   train_input_fn = tf.estimator.inputs.numpy_input_fn(
     80       x={X_FEATURE: x_train}, y=y_train, num_epochs=None, shuffle=True)
     81   classifier.train(input_fn=train_input_fn, steps=1000)
     82 
     83   # Predict.
     84   test_input_fn = tf.estimator.inputs.numpy_input_fn(
     85       x={X_FEATURE: x_test}, y=y_test, num_epochs=1, shuffle=False)
     86   predictions = classifier.predict(input_fn=test_input_fn)
     87   y_predicted = np.array(list(p['class'] for p in predictions))
     88   y_predicted = y_predicted.reshape(np.array(y_test).shape)
     89 
     90   # Score with sklearn.
     91   score = metrics.accuracy_score(y_test, y_predicted)
     92   print('Accuracy (sklearn): {0:f}'.format(score))
     93 
     94   # Score with tensorflow.
     95   scores = classifier.evaluate(input_fn=test_input_fn)
     96   print('Accuracy (tensorflow): {0:f}'.format(scores['accuracy']))
     97 
     98 
     99 if __name__ == '__main__':
    100   tf.app.run()
    101