In [1]:
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
import os
import sys
from six.moves import cPickle as pickle
%matplotlib inline

In [2]:
pickle_file = 'mini_train.pickle'

with open(pickle_file, 'rb') as f:
    save = pickle.load(f)
    mini_X = save['data']
    mini_outcome = save['outcome']
    del save  # hint to help gc free up memory

define a batch generator


In [3]:
batch_size=40
num_unrollings=5

class BatchGenerator(object):
    
    def __init__(self, x_image, y_labels, batch_size, num_unrollings):
        self._x_image = x_image
        self._y_labels = y_labels
        self._batch_size = batch_size
        self._num_unrollings = num_unrollings
        self._y_digits = self._extract_digits()
        
        
    def _extract_digits(self):
        end_digit = 10.0
        
        digits = np.ndarray(shape=(
                self._num_unrollings, len(self._y_labels), int(end_digit + 1)), 
                            dtype=np.float32)
        
        for i in range(self._num_unrollings):
            digit_coding = np.asarray( [x[i] if len(x)>i else end_digit 
                                        for x in self._y_labels])
            digit_coding = (
                np.arange(end_digit+1) == digit_coding[:,None]).astype(np.float32)
            digits[i,:,:] = digit_coding
        
        return digits
    
    def next_batch(self):
        idx = np.random.choice(self._x_image.shape[0],self._batch_size)
        batch_x = self._x_image[idx,:,:,:]
        batch_y = self._y_digits[:,idx,:]
        
        return batch_x, batch_y

sample a small data set


In [4]:
mini_train_batches = BatchGenerator(mini_X[:100], 
                                    mini_outcome['label'][:100],
                                    batch_size, num_unrollings)

In [5]:
batch_x, batch_y = mini_train_batches.next_batch()
print batch_y.shape
print batch_x.shape


(5, 40, 11)
(40, 64, 64, 3)

start a tensorflow session


In [6]:
sess = tf.InteractiveSession()

In [7]:
def weight_variable(shape):
    initial = tf.truncated_normal(shape, stddev=0.1)
    return tf.Variable(initial)

def bias_variable(shape):
    initial = tf.constant(0.1, shape=shape)
    return tf.Variable(initial)

def conv2d(x, W):
    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

def max_pool_2x2(x):
    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')

In [8]:
image_size = mini_X.shape[1]
num_channels = mini_X.shape[3]
CNN_num_nodes = 1024

x_image = tf.placeholder(tf.float32, shape=(batch_size, 
                                            image_size, 
                                            image_size, num_channels))

Construct CNN


In [9]:
W_conv1 = weight_variable([5, 5, num_channels, 32])
b_conv1 = bias_variable([32])

h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)

In [10]:
W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])

h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)

In [11]:
W_fc1 = weight_variable([16 * 16 * 64, CNN_num_nodes])
b_fc1 = bias_variable([CNN_num_nodes])

h_pool2_flat = tf.reshape(h_pool2, [-1, 16*16*64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)

Now connect with a RNN


In [12]:
RNN_num_nodes = 1024

#11 collums for each digits, i.e., 0,1,...,9, and a ending ch <END>
vocabulary_size = 11

# Input gate: input, previous output, and bias.
ix = weight_variable([vocabulary_size, RNN_num_nodes])
im = weight_variable([RNN_num_nodes, RNN_num_nodes])
ib = bias_variable([RNN_num_nodes])

# Forget gate: input, previous output, and bias.
fx = weight_variable([vocabulary_size, RNN_num_nodes])
fm = weight_variable([RNN_num_nodes, RNN_num_nodes])
fb = bias_variable([RNN_num_nodes])

# Memory cell: input, state and bias.                             
cx = weight_variable([vocabulary_size, RNN_num_nodes])
cm = weight_variable([RNN_num_nodes, RNN_num_nodes])
cb = bias_variable([RNN_num_nodes])

# Output gate: input, previous output, and bias.
ox = weight_variable([vocabulary_size, RNN_num_nodes])
om = weight_variable([RNN_num_nodes, RNN_num_nodes])
ob = bias_variable([RNN_num_nodes])

define the lstm cell


In [13]:
# Definition of the cell computation.
# state is cell state, o is hidden state, i is input
def lstm_cell(i, o, state):
    """Create a LSTM cell. See e.g.: http://arxiv.org/pdf/1402.1128v1.pdf
    Note that in this formulation, we omit the various connections between the
    previous state and the gates."""
    input_gate = tf.sigmoid(tf.matmul(i, ix) + tf.matmul(o, im) + ib)
    forget_gate = tf.sigmoid(tf.matmul(i, fx) + tf.matmul(o, fm) + fb)
    update = tf.matmul(i, cx) + tf.matmul(o, cm) + cb
    state = forget_gate * state + input_gate * tf.tanh(update)
    output_gate = tf.sigmoid(tf.matmul(i, ox) + tf.matmul(o, om) + ob)
    return output_gate * tf.tanh(state), state

In [14]:
# placeholder for digit input and digit labels
digits_data = []
for _ in range(num_unrollings + 1):
    digits_data.append(
        tf.placeholder(tf.float32, shape=[batch_size,vocabulary_size]))
    digits_inputs = digits_data[:num_unrollings]
    digits_labels = digits_data[1:]  # labels are inputs shifted by one time step.

In [15]:
# Variables saving state across unrollings.
saved_output = tf.Variable(tf.zeros([batch_size, RNN_num_nodes]), trainable=False)
saved_state = tf.Variable(tf.zeros([batch_size, RNN_num_nodes]), trainable=False)

#connect with CNN

W_CNN = weight_variable([CNN_num_nodes, RNN_num_nodes])
b_CNN = bias_variable([RNN_num_nodes])

CNN_output = tf.matmul(h_fc1, W_CNN) + b_CNN

output = saved_output + CNN_output
state = saved_state + CNN_output

# Unrolled LSTM loop.
outputs = list()

for i in digits_inputs:
    output, state = lstm_cell(i, output, state)
    outputs.append(output)

In [16]:
# Classifier weights and biases.
w_fc_rnn = weight_variable([RNN_num_nodes, vocabulary_size])
b_fc_rnn = bias_variable([vocabulary_size])

# State saving across unrollings.
with tf.control_dependencies([saved_output.assign(output), saved_state.assign(state)]):
    # Classifier.
    logits = tf.nn.xw_plus_b(tf.concat(0, outputs), w_fc_rnn, b_fc_rnn)
    loss = tf.reduce_mean(
        tf.nn.softmax_cross_entropy_with_logits(
            logits, tf.concat(0, digits_labels)))

In [17]:
# Optimizer.
optimizer = tf.train.AdamOptimizer(1e-4).minimize(loss)

In [18]:
#let's check the prediction accuracy for 2st digit
correct_prediction = tf.equal(tf.argmax(
        tf.matmul(outputs[1], w_fc_rnn) + b_fc_rnn
        ,1), 
                              tf.argmax(
        digits_labels[1]
        ,1))

accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

Train on a small data to overfit

if overfit, then ok. If not, check bugs.


In [19]:
num_steps = 1000
summary_frequency = 20

sess.run(tf.initialize_all_variables())
print('Initialized')

mean_loss = 0
mean_accuracy = 0

for step in range(num_steps):
    batch_x, batch_y = mini_train_batches.next_batch()
    
    feed_dict = dict()
    feed_dict[x_image] = batch_x
    
    feed_dict[digits_data[0]] = np.zeros([batch_y.shape[1],batch_y.shape[2]])
    
    for i in range(num_unrollings):
        feed_dict[digits_data[i+1]] = batch_y[i]
            
    _, l = sess.run(
        [optimizer, loss], feed_dict=feed_dict)
    mean_loss += l
    
    train_accuracy = accuracy.eval(feed_dict=feed_dict)
    mean_accuracy += train_accuracy
    
    #now print something
    if step % summary_frequency == 0:
        if step > 0:
            mean_loss = mean_loss / summary_frequency
            mean_accuracy = mean_accuracy/ summary_frequency
            
        # The mean loss is an estimate of the loss over the last few batches.
        print('Average loss at step %d: %f' % (step, mean_loss))
        mean_loss = 0
        
        
        print("step %d, training accuracy %g"%(step, mean_accuracy))
        mean_accuracy = 0


Initialized
Average loss at step 0: 3.217974
step 0, training accuracy 0.2
Average loss at step 20: 1.129356
step 20, training accuracy 0.27625
Average loss at step 40: 0.893669
step 40, training accuracy 0.43875
Average loss at step 60: 0.832818
step 60, training accuracy 0.515
Average loss at step 80: 0.731927
step 80, training accuracy 0.6175
Average loss at step 100: 0.686664
step 100, training accuracy 0.65625
Average loss at step 120: 0.604402
step 120, training accuracy 0.72625
Average loss at step 140: 0.543630
step 140, training accuracy 0.79
Average loss at step 160: 0.480441
step 160, training accuracy 0.80125
Average loss at step 180: 0.443382
step 180, training accuracy 0.8675
Average loss at step 200: 0.394744
step 200, training accuracy 0.9175
Average loss at step 220: 0.312721
step 220, training accuracy 0.955
Average loss at step 240: 0.264531
step 240, training accuracy 0.96
Average loss at step 260: 0.221890
step 260, training accuracy 0.97125
Average loss at step 280: 0.167557
step 280, training accuracy 0.98625
Average loss at step 300: 0.133320
step 300, training accuracy 0.99375
Average loss at step 320: 0.103768
step 320, training accuracy 0.99875
Average loss at step 340: 0.087972
step 340, training accuracy 1
Average loss at step 360: 0.071505
step 360, training accuracy 1
Average loss at step 380: 0.059441
step 380, training accuracy 1
Average loss at step 400: 0.050296
step 400, training accuracy 1
Average loss at step 420: 0.048009
step 420, training accuracy 1
Average loss at step 440: 0.039700
step 440, training accuracy 1
Average loss at step 460: 0.034613
step 460, training accuracy 1
Average loss at step 480: 0.029943
step 480, training accuracy 1
Average loss at step 500: 0.028714
step 500, training accuracy 1
Average loss at step 520: 0.024119
step 520, training accuracy 1
Average loss at step 540: 0.021070
step 540, training accuracy 1
Average loss at step 560: 0.020393
step 560, training accuracy 1
Average loss at step 580: 0.018360
step 580, training accuracy 1
Average loss at step 600: 0.016775
step 600, training accuracy 1
Average loss at step 620: 0.015905
step 620, training accuracy 1
Average loss at step 640: 0.014515
step 640, training accuracy 1
Average loss at step 660: 0.013302
step 660, training accuracy 1
Average loss at step 680: 0.013569
step 680, training accuracy 1
Average loss at step 700: 0.011875
step 700, training accuracy 1
Average loss at step 720: 0.011247
step 720, training accuracy 1
Average loss at step 740: 0.010443
step 740, training accuracy 1
Average loss at step 760: 0.010166
step 760, training accuracy 1
Average loss at step 780: 0.009609
step 780, training accuracy 1
Average loss at step 800: 0.008911
step 800, training accuracy 1
Average loss at step 820: 0.008663
step 820, training accuracy 1
Average loss at step 840: 0.008309
step 840, training accuracy 1
Average loss at step 860: 0.007734
step 860, training accuracy 1
Average loss at step 880: 0.007084
step 880, training accuracy 1
Average loss at step 900: 0.007402
step 900, training accuracy 1
Average loss at step 920: 0.006863
step 920, training accuracy 1
Average loss at step 940: 0.006531
step 940, training accuracy 1
Average loss at step 960: 0.006217
step 960, training accuracy 1
Average loss at step 980: 0.006617
step 980, training accuracy 1

In [ ]:


In [ ]: