Tensorflow with ContribLearn

As we saw previously how to build a full Multi-Layer Perceptron model with full Sessions in Tensorflow. Unfortunately this was an extremely involved process. However developers have created ContribLearn (previously known as TKFlow or SciKit-Flow) which provides a SciKit Learn like interface for Tensorflow!

It is much easier to use, but you sacrifice some level of customization of your model. Let's go ahead and explore it!

Get the Data

We will the iris data set.

Let's get the data:


In [1]:
from sklearn.datasets import load_iris

In [2]:
iris = load_iris()

In [3]:
X = iris['data']

In [4]:
y = iris['target']

In [5]:
y


Out[5]:
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
       2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
       2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])

In [6]:
y.dtype


Out[6]:
dtype('int64')

Train Test Split


In [7]:
from sklearn.cross_validation import train_test_split

In [8]:
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)

Contrib.learn

Let's show you how to use the simpler contrib.learn interface!


In [9]:
import tensorflow.contrib.learn.python.learn as learn

There are several high level abstraction calls to models in learn, you can explore them with Tab, but we will use DNNClassifier, which stands for Deep Neural Network:


In [10]:
classifier = learn.DNNClassifier(hidden_units=[10, 20, 10], n_classes=3)#,feature_columns=feature_columns)
classifier.fit(X_train, y_train, steps=200, batch_size=32)


Out[10]:
DNNClassifier()

In [11]:
iris_predictions = classifier.predict(X_test)

In [12]:
from sklearn.metrics import classification_report,confusion_matrix

In [14]:
print(classification_report(y_test,iris_predictions))


             precision    recall  f1-score   support

          0       1.00      1.00      1.00        13
          1       1.00      0.75      0.86        16
          2       0.80      1.00      0.89        16

avg / total       0.93      0.91      0.91        45

Great Job!