How to do it...

Let's see how to simplify machine learning workflow using TensorFlow:

  1. We start, as always, by importing the libraries:
from sklearn import datasets
from sklearn import model_selection
import tensorflow as tf

The first two libraries are imported only to load and split the data. The third library loads the tensorflow library.

  1. Load the iris dataset:
iris = datasets.load_iris()

  1. Load and split the features and classes:
x_train, x_test, y_train, y_test = model_selection.train_test_split(iris.data, 
iris.target,
test_size=0.7,
random_state=1)

The data is split into 70% for training and 30% for testing. The random_state=1 parameter is the seed used by the random number generator.

  1. Now we will build a simple neural network with one hidden layer and 10 nodes:
feature_columns = tf.contrib.learn.infer_real_valued_columns_from_input(x_train)
classifier_tf = tf.contrib.learn.DNNClassifier(feature_columns=feature_columns,
hidden_units=[10],
n_classes=3)
  1. Then we fit the network:
classifier_tf.fit(x_train, y_train, steps=5000)
  1. We will then make the predictions:
predictions = list(classifier_tf.predict(x_test, as_iterable=True))
  1. Finally, we will calculate the accuracy metric of the model:
n_items = y_test.size
accuracy = (y_test == predictions).sum() / n_items
print("Accuracy :", accuracy)

The following result is returned:

Accuracy : 0.9333333333333333