Files
2017-09-12 13:56:28 +05:30

1.4 MiB

Python Machine Learning 2nd Edition by Sebastian Raschka and Vahid Mirjalili, Packt Publishing Ltd. 2017

Code Repository: https://github.com/rasbt/python-machine-learning-book-2nd-edition

Code License: MIT License

Python Machine Learning - Code Examples

Chapter 13 - Parallelizing Neural Network Training with TensorFlow

Note that the optional watermark extension is a small IPython notebook plugin that I developed to make the code reproducible. You can just skip the following line(s).

In [1]:
%load_ext watermark
%watermark -a "Sebastian Raschka & Vahid Mirjalili" -u -d -v -p numpy,tensorflow,matplotlib
Sebastian Raschka & Vahid Mirjalili 
last updated: 2017-09-06 

CPython 3.6.1
IPython 6.1.0

numpy 1.12.1
tensorflow 1.3.0
matplotlib 2.0.2

The use of watermark is optional. You can install this IPython extension via "pip install watermark". For more information, please see: https://github.com/rasbt/watermark.

In [2]:
%matplotlib inline
In [3]:
from IPython.display import Image
%matplotlib inline

Building, compiling, and running machine learning models with TensorFlow

Performance challenges of expensive computations

In [4]:
Image(filename='images/13_05.png', width=600)
Out [4]:

What is TensorFlow?

First steps with TensorFlow

In [5]:
import tensorflow as tf

## create a graph
g = tf.Graph()
with g.as_default():
    x = tf.placeholder(dtype=tf.float32,
                       shape=(None), name='x')
    w = tf.Variable(2.0, name='weight')
    b = tf.Variable(0.7, name='bias')

    z = w*x + b
    init = tf.global_variables_initializer()

## create a session and pass in graph g
with tf.Session(graph=g) as sess:
    ## initialize w and b:
    sess.run(init)
    ## evaluate z:
    for t in [1.0, 0.6, -1.8]:
        print('x=%4.1f --> z=%4.1f'%(
              t, sess.run(z, feed_dict={x:t})))
x= 1.0 --> z= 2.7
x= 0.6 --> z= 1.9
x=-1.8 --> z=-2.9
In [6]:
with tf.Session(graph=g) as sess:
    sess.run(init)
    print(sess.run(z, feed_dict={x:[1., 2., 3.]})) 
[ 2.70000005  4.69999981  6.69999981]

Working with array structures

In [7]:
import tensorflow as tf
import numpy as np


g = tf.Graph()
with g.as_default():
    x = tf.placeholder(dtype=tf.float32, 
                       shape=(None, 2, 3),
                       name='input_x')

    x2 = tf.reshape(x, shape=(-1, 6),
                    name='x2')

    ## calculate the sum of each column
    xsum = tf.reduce_sum(x2, axis=0, name='col_sum')

    ## calculate the mean of each column
    xmean = tf.reduce_mean(x2, axis=0, name='col_mean')

    
with tf.Session(graph=g) as sess:
    x_array = np.arange(18).reshape(3, 2, 3)
    print('input shape: ', x_array.shape)
    print('Reshaped:\n', 
          sess.run(x2, feed_dict={x:x_array}))
    print('Column Sums:\n', 
          sess.run(xsum, feed_dict={x:x_array}))
    print('Column Means:\n', 
          sess.run(xmean, feed_dict={x:x_array}))
input shape:  (3, 2, 3)
Reshaped:
 [[  0.   1.   2.   3.   4.   5.]
 [  6.   7.   8.   9.  10.  11.]
 [ 12.  13.  14.  15.  16.  17.]]
Column Sums:
 [ 18.  21.  24.  27.  30.  33.]
Column Means:
 [  6.   7.   8.   9.  10.  11.]

Developing a simple model with low-level TensorFlow API

In [8]:
import tensorflow as tf
import numpy as np
 
X_train = np.arange(10).reshape((10, 1))
y_train = np.array([1.0, 1.3, 3.1,
                    2.0, 5.0, 6.3, 
                    6.6, 7.4, 8.0, 
                    9.0])
In [9]:
class TfLinreg(object):
    
    def __init__(self, x_dim, learning_rate=0.01,
                 random_seed=None):
        self.x_dim = x_dim
        self.learning_rate = learning_rate
        self.g = tf.Graph()
        ## build the model
        with self.g.as_default():
            ## set graph-level random-seed
            tf.set_random_seed(random_seed)
            
            self.build()
            ## create initializer
            self.init_op = tf.global_variables_initializer()
        
    def build(self):
        ## define placeholders for inputs
        self.X = tf.placeholder(dtype=tf.float32,
                                shape=(None, self.x_dim),
                                name='x_input')
        self.y = tf.placeholder(dtype=tf.float32,
                                shape=(None),
                                name='y_input')
        print(self.X)
        print(self.y)
        ## define weight matrix and bias vector
        w = tf.Variable(tf.zeros(shape=(1)),
                        name='weight')
        b = tf.Variable(tf.zeros(shape=(1)), 
                        name="bias")
        print(w)
        print(b)

        self.z_net = tf.squeeze(w*self.X + b,
                                name='z_net')
        print(self.z_net)
        
        sqr_errors = tf.square(self.y - self.z_net, 
                               name='sqr_errors')
        print(sqr_errors)
        self.mean_cost = tf.reduce_mean(sqr_errors,
                                        name='mean_cost')
        
        optimizer = tf.train.GradientDescentOptimizer(
                    learning_rate=self.learning_rate, 
                    name='GradientDescent')
        self.optimizer = optimizer.minimize(self.mean_cost)
In [10]:
lrmodel = TfLinreg(x_dim=X_train.shape[1], learning_rate=0.01)
Tensor("x_input:0", shape=(?, 1), dtype=float32)
Tensor("y_input:0", dtype=float32)
<tf.Variable 'weight:0' shape=(1,) dtype=float32_ref>
<tf.Variable 'bias:0' shape=(1,) dtype=float32_ref>
Tensor("z_net:0", dtype=float32)
Tensor("sqr_errors:0", dtype=float32)
In [11]:
def train_linreg(sess, model, X_train, y_train, num_epochs=10):
    ## initialiaze all variables: W & b
    sess.run(model.init_op)
    
    training_costs = []
    for i in range(num_epochs):
        _, cost = sess.run([model.optimizer, model.mean_cost], 
                           feed_dict={model.X:X_train, 
                                      model.y:y_train})
        training_costs.append(cost)
        
    return training_costs
In [12]:
sess = tf.Session(graph=lrmodel.g)
training_costs = train_linreg(sess, lrmodel, X_train, y_train)
In [13]:
import matplotlib.pyplot as plt

plt.plot(range(1,len(training_costs) + 1), training_costs)
plt.tight_layout()
plt.xlabel('Epoch')
plt.ylabel('Training Cost')
#plt.savefig('images/13_01.png', dpi=300)
plt.show()
In [14]:
def predict_linreg(sess, model, X_test):
    y_pred = sess.run(model.z_net, 
                      feed_dict={model.X:X_test})
    return y_pred
In [15]:
plt.scatter(X_train, y_train,
            marker='s', s=50,
            label='Training Data')
plt.plot(range(X_train.shape[0]), 
         predict_linreg(sess, lrmodel, X_train),
         color='gray', marker='o', 
         markersize=6, linewidth=3,
         label='LinReg Model')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.tight_layout()
#plt.savefig('images/13_02.png')
plt.show()

Training neural networks efficiently with high-level TensorFlow APIs

Building multilayer neural networks using TensorFlow's Layers API

  • See Chapter 12 for details on MNIST
In [16]:
# unzips mnist

import sys
import gzip
import shutil
import os

if (sys.version_info > (3, 0)):
    writemode = 'wb'
else:
    writemode = 'w'

zipped_mnist = [f for f in os.listdir('./') if f.endswith('ubyte.gz')]
for z in zipped_mnist:
    with gzip.GzipFile(z, mode='rb') as decompressed, open(z[:-3], writemode) as outfile:
        outfile.write(decompressed.read())
In [17]:
import struct
 
def load_mnist(path, kind='train'):
    """Load MNIST data from `path`"""
    labels_path = os.path.join(path, 
                               '%s-labels-idx1-ubyte' % kind)
    images_path = os.path.join(path, 
                               '%s-images-idx3-ubyte' % kind)
        
    with open(labels_path, 'rb') as lbpath:
        magic, n = struct.unpack('>II', 
                                 lbpath.read(8))
        labels = np.fromfile(lbpath, 
                             dtype=np.uint8)

    with open(images_path, 'rb') as imgpath:
        magic, num, rows, cols = struct.unpack(">IIII", 
                                               imgpath.read(16))
        images = np.fromfile(imgpath, 
                             dtype=np.uint8).reshape(len(labels), 784)
        images = ((images / 255.) - .5) * 2
 
    return images, labels
In [18]:
## loading the data
X_train, y_train = load_mnist('.', kind='train')
print('Rows: %d,  Columns: %d' %(X_train.shape[0], 
                                 X_train.shape[1]))

X_test, y_test = load_mnist('.', kind='t10k')
print('Rows: %d,  Columns: %d' %(X_test.shape[0], 
                                     X_test.shape[1]))
## mean centering and normalization:
mean_vals = np.mean(X_train, axis=0)
std_val = np.std(X_train)

X_train_centered = (X_train - mean_vals)/std_val
X_test_centered = (X_test - mean_vals)/std_val

del X_train, X_test

print(X_train_centered.shape, y_train.shape)

print(X_test_centered.shape, y_test.shape)
Rows: 60000,  Columns: 784
Rows: 10000,  Columns: 784
(60000, 784) (60000,)
(10000, 784) (10000,)
In [19]:
import tensorflow as tf

n_features = X_train_centered.shape[1]
n_classes = 10
random_seed = 123
np.random.seed(random_seed)

g = tf.Graph()
with g.as_default():
    tf.set_random_seed(random_seed)
    tf_x = tf.placeholder(dtype=tf.float32,
                       shape=(None, n_features),
                       name='tf_x')

    tf_y = tf.placeholder(dtype=tf.int32, 
                        shape=None, name='tf_y')
    y_onehot = tf.one_hot(indices=tf_y, depth=n_classes)

    h1 = tf.layers.dense(inputs=tf_x, units=50,
                         activation=tf.tanh,
                         name='layer1')

    h2 = tf.layers.dense(inputs=h1, units=50,
                         activation=tf.tanh,
                         name='layer2')

    logits = tf.layers.dense(inputs=h2, 
                             units=10,
                             activation=None,
                             name='layer3')

    predictions = {
        'classes' : tf.argmax(logits, axis=1, 
                              name='predicted_classes'),
        'probabilities' : tf.nn.softmax(logits, 
                              name='softmax_tensor')
    }
In [20]:
## define cost function and optimizer:
with g.as_default():
    cost = tf.losses.softmax_cross_entropy(
            onehot_labels=y_onehot, logits=logits)

    optimizer = tf.train.GradientDescentOptimizer(
            learning_rate=0.001)

    train_op = optimizer.minimize(loss=cost)

    init_op = tf.global_variables_initializer()
In [21]:
def create_batch_generator(X, y, batch_size=128, shuffle=False):
    X_copy = np.array(X)
    y_copy = np.array(y)
    
    if shuffle:
        data = np.column_stack((X_copy, y_copy))
        np.random.shuffle(data)
        X_copy = data[:, :-1]
        y_copy = data[:, -1].astype(int)
    
    for i in range(0, X.shape[0], batch_size):
        yield (X[i:i+batch_size, :], y[i:i+batch_size])
In [22]:
## create a session to launch the graph
sess =  tf.Session(graph=g)
## run the variable initialization operator
sess.run(init_op)

## 50 epochs of training:
training_costs = []
for epoch in range(50):
    training_loss = []
    batch_generator = create_batch_generator(
            X_train_centered, y_train, 
            batch_size=64, shuffle=True)
    for batch_X, batch_y in batch_generator:
        ## prepare a dict to feed data to our network:
        feed = {tf_x:batch_X, tf_y:batch_y}
        _, batch_cost = sess.run([train_op, cost],
                                 feed_dict=feed)
        training_costs.append(batch_cost)
    print(' -- Epoch %2d  '
          'Avg. Training Loss: %.4f' % (
              epoch+1, np.mean(training_costs)
    ))
 -- Epoch  1  Avg. Training Loss: 1.5573
 -- Epoch  2  Avg. Training Loss: 1.2532
 -- Epoch  3  Avg. Training Loss: 1.0854
 -- Epoch  4  Avg. Training Loss: 0.9738
 -- Epoch  5  Avg. Training Loss: 0.8924
 -- Epoch  6  Avg. Training Loss: 0.8296
 -- Epoch  7  Avg. Training Loss: 0.7794
 -- Epoch  8  Avg. Training Loss: 0.7381
 -- Epoch  9  Avg. Training Loss: 0.7032
 -- Epoch 10  Avg. Training Loss: 0.6734
 -- Epoch 11  Avg. Training Loss: 0.6475
 -- Epoch 12  Avg. Training Loss: 0.6247
 -- Epoch 13  Avg. Training Loss: 0.6045
 -- Epoch 14  Avg. Training Loss: 0.5864
 -- Epoch 15  Avg. Training Loss: 0.5700
 -- Epoch 16  Avg. Training Loss: 0.5551
 -- Epoch 17  Avg. Training Loss: 0.5415
 -- Epoch 18  Avg. Training Loss: 0.5290
 -- Epoch 19  Avg. Training Loss: 0.5175
 -- Epoch 20  Avg. Training Loss: 0.5068
 -- Epoch 21  Avg. Training Loss: 0.4968
 -- Epoch 22  Avg. Training Loss: 0.4875
 -- Epoch 23  Avg. Training Loss: 0.4788
 -- Epoch 24  Avg. Training Loss: 0.4706
 -- Epoch 25  Avg. Training Loss: 0.4629
 -- Epoch 26  Avg. Training Loss: 0.4556
 -- Epoch 27  Avg. Training Loss: 0.4487
 -- Epoch 28  Avg. Training Loss: 0.4422
 -- Epoch 29  Avg. Training Loss: 0.4359
 -- Epoch 30  Avg. Training Loss: 0.4300
 -- Epoch 31  Avg. Training Loss: 0.4243
 -- Epoch 32  Avg. Training Loss: 0.4189
 -- Epoch 33  Avg. Training Loss: 0.4138
 -- Epoch 34  Avg. Training Loss: 0.4088
 -- Epoch 35  Avg. Training Loss: 0.4041
 -- Epoch 36  Avg. Training Loss: 0.3995
 -- Epoch 37  Avg. Training Loss: 0.3951
 -- Epoch 38  Avg. Training Loss: 0.3909
 -- Epoch 39  Avg. Training Loss: 0.3868
 -- Epoch 40  Avg. Training Loss: 0.3829
 -- Epoch 41  Avg. Training Loss: 0.3791
 -- Epoch 42  Avg. Training Loss: 0.3754
 -- Epoch 43  Avg. Training Loss: 0.3718
 -- Epoch 44  Avg. Training Loss: 0.3684
 -- Epoch 45  Avg. Training Loss: 0.3651
 -- Epoch 46  Avg. Training Loss: 0.3618
 -- Epoch 47  Avg. Training Loss: 0.3587
 -- Epoch 48  Avg. Training Loss: 0.3556
 -- Epoch 49  Avg. Training Loss: 0.3527
 -- Epoch 50  Avg. Training Loss: 0.3498
In [23]:
## do prediction on the test set:
feed = {tf_x : X_test_centered}
y_pred = sess.run(predictions['classes'], 
                  feed_dict=feed)
 
print('Test Accuracy: %.2f%%' % (
      100*np.sum(y_pred == y_test)/y_test.shape[0]))
Test Accuracy: 93.89%

Developing Multilayer Neural Networks with Keras

In [24]:
X_train, y_train = load_mnist('./', kind='train')
print('Rows: %d,  Columns: %d' %(X_train.shape[0], 
                                 X_train.shape[1]))
X_test, y_test = load_mnist('./', kind='t10k')
print('Rows: %d,  Columns: %d' %(X_test.shape[0], 
                                 X_test.shape[1]))

## mean centering and normalization:
mean_vals = np.mean(X_train, axis=0)
std_val = np.std(X_train)

X_train_centered = (X_train - mean_vals)/std_val
X_test_centered = (X_test - mean_vals)/std_val
 
del X_train, X_test
 
print(X_train_centered.shape, y_train.shape)

print(X_test_centered.shape, y_test.shape)
Rows: 60000,  Columns: 784
Rows: 10000,  Columns: 784
(60000, 784) (60000,)
(10000, 784) (10000,)
In [25]:
import tensorflow as tf
import tensorflow.contrib.keras as keras

np.random.seed(123)
tf.set_random_seed(123)
In [26]:
y_train_onehot = keras.utils.to_categorical(y_train)
 
print('First 3 labels: ', y_train[:3])
print('\nFirst 3 labels (one-hot):\n', y_train_onehot[:3])
First 3 labels:  [5 0 4]

First 3 labels (one-hot):
 [[ 0.  0.  0.  0.  0.  1.  0.  0.  0.  0.]
 [ 1.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  1.  0.  0.  0.  0.  0.]]
In [27]:
model = keras.models.Sequential()

model.add(
    keras.layers.Dense(
        units=50,    
        input_dim=X_train_centered.shape[1],
        kernel_initializer='glorot_uniform',
        bias_initializer='zeros',
        activation='tanh'))

model.add(
    keras.layers.Dense(
        units=50,    
        input_dim=50,
        kernel_initializer='glorot_uniform',
        bias_initializer='zeros',
        activation='tanh'))

model.add(
    keras.layers.Dense(
        units=y_train_onehot.shape[1],    
        input_dim=50,
        kernel_initializer='glorot_uniform',
        bias_initializer='zeros',
        activation='softmax'))


sgd_optimizer = keras.optimizers.SGD(
        lr=0.001, decay=1e-7, momentum=.9)

model.compile(optimizer=sgd_optimizer,
              loss='categorical_crossentropy')
In [28]:
history = model.fit(X_train_centered, y_train_onehot,
                    batch_size=64, epochs=50,
                    verbose=1,
                    validation_split=0.1)
Train on 54000 samples, validate on 6000 samples
Epoch 1/50
54000/54000 [==============================] - 2s - loss: 0.7247 - val_loss: 0.3616
Epoch 2/50
54000/54000 [==============================] - 2s - loss: 0.3718 - val_loss: 0.2815
Epoch 3/50
54000/54000 [==============================] - 2s - loss: 0.3087 - val_loss: 0.2447
Epoch 4/50
54000/54000 [==============================] - 2s - loss: 0.2728 - val_loss: 0.2216
Epoch 5/50
54000/54000 [==============================] - 2s - loss: 0.2475 - val_loss: 0.2042
Epoch 6/50
54000/54000 [==============================] - 2s - loss: 0.2277 - val_loss: 0.1918
Epoch 7/50
54000/54000 [==============================] - 2s - loss: 0.2115 - val_loss: 0.1810
Epoch 8/50
54000/54000 [==============================] - 2s - loss: 0.1979 - val_loss: 0.1719
Epoch 9/50
54000/54000 [==============================] - 2s - loss: 0.1860 - val_loss: 0.1646
Epoch 10/50
54000/54000 [==============================] - 2s - loss: 0.1758 - val_loss: 0.1591
Epoch 11/50
54000/54000 [==============================] - 2s - loss: 0.1667 - val_loss: 0.1543
Epoch 12/50
54000/54000 [==============================] - 2s - loss: 0.1589 - val_loss: 0.1491
Epoch 13/50
54000/54000 [==============================] - 2s - loss: 0.1516 - val_loss: 0.1451
Epoch 14/50
54000/54000 [==============================] - 2s - loss: 0.1450 - val_loss: 0.1420
Epoch 15/50
54000/54000 [==============================] - 2s - loss: 0.1389 - val_loss: 0.1386
Epoch 16/50
54000/54000 [==============================] - 2s - loss: 0.1333 - val_loss: 0.1363
Epoch 17/50
54000/54000 [==============================] - 2s - loss: 0.1283 - val_loss: 0.1332
Epoch 18/50
54000/54000 [==============================] - 2s - loss: 0.1234 - val_loss: 0.1327
Epoch 19/50
54000/54000 [==============================] - 2s - loss: 0.1191 - val_loss: 0.1293
Epoch 20/50
54000/54000 [==============================] - 2s - loss: 0.1148 - val_loss: 0.1282
Epoch 21/50
54000/54000 [==============================] - 2s - loss: 0.1109 - val_loss: 0.1270
Epoch 22/50
54000/54000 [==============================] - 2s - loss: 0.1071 - val_loss: 0.1265
Epoch 23/50
54000/54000 [==============================] - 2s - loss: 0.1037 - val_loss: 0.1243
Epoch 24/50
54000/54000 [==============================] - 2s - loss: 0.1003 - val_loss: 0.1229
Epoch 25/50
54000/54000 [==============================] - 2s - loss: 0.0971 - val_loss: 0.1216
Epoch 26/50
54000/54000 [==============================] - 2s - loss: 0.0941 - val_loss: 0.1212
Epoch 27/50
54000/54000 [==============================] - 2s - loss: 0.0912 - val_loss: 0.1200
Epoch 28/50
54000/54000 [==============================] - 2s - loss: 0.0884 - val_loss: 0.1202
Epoch 29/50
54000/54000 [==============================] - 2s - loss: 0.0858 - val_loss: 0.1189
Epoch 30/50
54000/54000 [==============================] - 2s - loss: 0.0834 - val_loss: 0.1184
Epoch 31/50
54000/54000 [==============================] - 2s - loss: 0.0810 - val_loss: 0.1184
Epoch 32/50
54000/54000 [==============================] - 2s - loss: 0.0787 - val_loss: 0.1189
Epoch 33/50
54000/54000 [==============================] - 2s - loss: 0.0765 - val_loss: 0.1183
Epoch 34/50
54000/54000 [==============================] - 2s - loss: 0.0743 - val_loss: 0.1196
Epoch 35/50
54000/54000 [==============================] - 2s - loss: 0.0723 - val_loss: 0.1179
Epoch 36/50
54000/54000 [==============================] - 2s - loss: 0.0703 - val_loss: 0.1174
Epoch 37/50
54000/54000 [==============================] - 2s - loss: 0.0684 - val_loss: 0.1185
Epoch 38/50
54000/54000 [==============================] - 2s - loss: 0.0665 - val_loss: 0.1187
Epoch 39/50
54000/54000 [==============================] - 2s - loss: 0.0647 - val_loss: 0.1171
Epoch 40/50
54000/54000 [==============================] - 2s - loss: 0.0629 - val_loss: 0.1172
Epoch 41/50
54000/54000 [==============================] - 2s - loss: 0.0613 - val_loss: 0.1175
Epoch 42/50
54000/54000 [==============================] - 2s - loss: 0.0597 - val_loss: 0.1170
Epoch 43/50
54000/54000 [==============================] - 2s - loss: 0.0581 - val_loss: 0.1168
Epoch 44/50
54000/54000 [==============================] - 2s - loss: 0.0566 - val_loss: 0.1166
Epoch 45/50
54000/54000 [==============================] - 2s - loss: 0.0552 - val_loss: 0.1166
Epoch 46/50
54000/54000 [==============================] - 2s - loss: 0.0537 - val_loss: 0.1162
Epoch 47/50
54000/54000 [==============================] - 2s - loss: 0.0523 - val_loss: 0.1170
Epoch 48/50
54000/54000 [==============================] - 2s - loss: 0.0510 - val_loss: 0.1172
Epoch 49/50
54000/54000 [==============================] - 2s - loss: 0.0498 - val_loss: 0.1171
Epoch 50/50
54000/54000 [==============================] - 2s - loss: 0.0485 - val_loss: 0.1174
In [29]:
y_train_pred = model.predict_classes(X_train_centered, verbose=0)
print('First 3 predictions: ', y_train_pred[:3])
First 3 predictions:  [5 0 4]
In [30]:
y_train_pred = model.predict_classes(X_train_centered, 
                                     verbose=0)
correct_preds = np.sum(y_train == y_train_pred, axis=0) 
train_acc = correct_preds / y_train.shape[0]

print('First 3 predictions: ', y_train_pred[:3])
print('Training accuracy: %.2f%%' % (train_acc * 100))
First 3 predictions:  [5 0 4]
Training accuracy: 98.88%
In [31]:
y_test_pred = model.predict_classes(X_test_centered, 
                                    verbose=0)

correct_preds = np.sum(y_test == y_test_pred, axis=0) 
test_acc = correct_preds / y_test.shape[0]
print('Test accuracy: %.2f%%' % (test_acc * 100))
Test accuracy: 96.04%

Choosing activation functions for multilayer networks

Logistic function recap

In [5]:
import numpy as np

X = np.array([1, 1.4, 2.5]) ## first value must be 1
w = np.array([0.4, 0.3, 0.5])

def net_input(X, w):
    return np.dot(X, w)

def logistic(z):
    return 1.0 / (1.0 + np.exp(-z))

def logistic_activation(X, w):
    z = net_input(X, w)
    return logistic(z)

print('P(y=1|x) = %.3f' % logistic_activation(X, w))
P(y=1|x) = 0.888
In [33]:
# W : array with shape = (n_output_units, n_hidden_units+1)
#     note that the first column are the bias units

W = np.array([[1.1, 1.2, 0.8, 0.4],
              [0.2, 0.4, 1.0, 0.2],
              [0.6, 1.5, 1.2, 0.7]])

# A : data array with shape = (n_hidden_units + 1, n_samples)
#     note that the first column of this array must be 1

A = np.array([[1, 0.1, 0.4, 0.6]])

Z = np.dot(W, A[0])
y_probas = logistic(Z)

print('Net Input: \n', Z)

print('Output Units:\n', y_probas)
Net Input: 
 [ 1.78  0.76  1.65]
Output Units:
 [ 0.85569687  0.68135373  0.83889105]
In [34]:
y_class = np.argmax(Z, axis=0)
print('Predicted class label: %d' % y_class)
Predicted class label: 0

Estimating class probabilities in multi-class classification via the softmax function

In [35]:
def softmax(z):
    return np.exp(z) / np.sum(np.exp(z))

y_probas = softmax(Z)
print('Probabilities:\n', y_probas)
Probabilities:
 [ 0.44668973  0.16107406  0.39223621]
In [36]:
np.sum(y_probas)
Out [36]:
1.0

Broadening the output spectrum by using a hyperbolic tangent

In [7]:
import matplotlib.pyplot as plt

def tanh(z):
    e_p = np.exp(z)
    e_m = np.exp(-z)
    return (e_p - e_m) / (e_p + e_m)

z = np.arange(-5, 5, 0.005)
log_act = logistic(z)
tanh_act = tanh(z)

plt.ylim([-1.5, 1.5])
plt.xlabel('net input $z$')
plt.ylabel('activation $\phi(z)$')
plt.axhline(1, color='black', linestyle=':')
plt.axhline(0.5, color='black', linestyle=':')
plt.axhline(0, color='black', linestyle=':')
plt.axhline(-0.5, color='black', linestyle=':')
plt.axhline(-1, color='black', linestyle=':')

plt.plot(z, tanh_act,
         linewidth=3, linestyle='--',
         label='tanh')

plt.plot(z, log_act,
         linewidth=3,
         label='logistic')
plt.legend(loc='lower right')
plt.tight_layout()
#plt.savefig('images/13_03.png')
plt.show()

Rectified Linear Unit activation

In [38]:
Image(filename='images/13_04.png', width=600)
Out [38]:

Summary

...


Readers may ignore the next cell.

In [1]:
! python ../.convert_notebook_to_script.py --input ch13.ipynb --output ch13.py
[NbConvertApp] Converting notebook ch13.ipynb to script
[NbConvertApp] Writing 18188 bytes to ch13.py