<jupyter_start><jupyter_text>Task 1: XOR<jupyter_code># Import modules
from __future__ import print_function
import tensorflow as tf
import numpy as np
from numpy.random import shuffle
import time
import matplotlib.pyplot as plt

# Plot configurations
% matplotlib inline

# Notebook auto reloads code. (Ref: http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython)
% load_ext autoreload
% autoreload 2<jupyter_output><empty_output><jupyter_text>Task 1, Part 1: Backpropagation through time (BPTT) **Question:** Consider a simple RNN network shown in the following figure, where __ _wi, wh, b, a, c_ __ are the scalar parameters of the network. The loss function is the **mean squared error (MSE)**. Given input (x0, x1) = (1, 0), ground truth (g1, g2) = (1, 1), h0 = 0, (wi, wh, b, a, c) = (1, 1, 1, 1, 1), compute __ _(dwi, dwh, db, da, dc)_ __, which are the gradients of loss with repect to 5 parameters __ _(wi, wh, b, a, c)_ __.![bptt](./img/bptt.png)<jupyter_code>def sigmoid(x):
    return (1 / (1 + np.exp(-x)))
(x0, x1) = (1, 0)
(g1, g2) = (1, 1)
h0 = 0
(wi, wh, b, a, c) = (1, 1, 1, 1, 1)
h1 = sigmoid(wi*x0 + wh*h0 + b)
y1 = a*h1 + c
print(h1)
print(y1)
h2 = sigmoid(wi*x1 + wh*h1 + b)
y2 = a*h2 + c
print(h2)
print(y2)
L = 1/2 * ((y1-g1)**2 + (y2-g2)**2)
d1 = y1-g1
d2 = y2-g2
print(d1)
print(d2)<jupyter_output>0.880797077978
1.88079707798
0.867702653653
1.86770265365
0.880797077978
0.867702653653<jupyter_text>$\dfrac{\delta L}{\delta wi} = \dfrac{1}{2}\sum_{i=1}^n \dfrac{\delta Li}{\delta wi} = \dfrac{\delta L1}{\delta wi} + \dfrac{\delta L2}{\delta wi}$ $ \dfrac{\delta L1}{\delta wi}=\dfrac{\delta L1}{\delta y1}\dfrac{\delta y1}{\delta h1}\dfrac{\delta h1}{\delta wi} =  \dfrac{\delta }{\delta wi} (a*h1+c)= \dfrac{\delta }{\delta wi} (a*sigmoid(wi*x0+wh*h0+b)+c) = d1*a*x0*sigmoid(wi*x0+wh*h0+b)*(1-sigmoid(wi*x0+wh*h0+b)) = d1*a*x0*h1*(1-h1) = 0.092478043229829859$$ \dfrac{\delta L2}{\delta wi}=\dfrac{\delta L2}{\delta y2}\dfrac{\delta y2}{\delta h2}\dfrac{\delta h2}{\delta wi}+\dfrac{\delta L2}{\delta y2}\dfrac{\delta y2}{\delta h2}\dfrac{\delta h2}{\delta h1}\dfrac{\delta h1}{\delta wi}= \dfrac{\delta }{\delta wi} (a*h2+c) = \dfrac{\delta }{\delta wi} (a*sigmoid(wi*x1+wh*h1+b)+c) =  d2*(a*x1*sigmoid(wi*x1+wh*h1+b)*(1-sigmoid(wi*x1+wh*h1+b)) + a*wh*sigmoid(wi*x1+wh*h1+b)*(1-sigmoid(wi*x1+wh*h1+b))*x0*sigmoid(wi*x0+wh*h0+b)*(1-sigmoid(wi*x0+wh*h0+b))) = d2*(a*x1*h2*(1-h2) + a*wh*h2*(1-h2)*x0*h1*(1-h1)) = 0.010458171296869908$$\dfrac{\delta L}{\delta wi} = \dfrac{\delta L1}{\delta wi} + \dfrac{\delta L2}{\delta wi} = 0.10293621452669977$ $\dfrac{\delta L}{\delta wh} = \dfrac{1}{2}\sum_{i=1}^n \dfrac{\delta Li}{\delta wh} = \dfrac{\delta L1}{\delta wh} + \dfrac{\delta L2}{\delta wh}$$ \dfrac{\delta L1}{\delta wh}=\dfrac{\delta L1}{\delta y1}\dfrac{\delta y1}{\delta h1}\dfrac{\delta h1}{\delta wh} =  \dfrac{\delta }{\delta wh} (a*h1+c)= \dfrac{\delta }{\delta wi} (a*sigmoid(wi*x0+wh*h0+b)+c) = d1*a*x0*sigmoid(wi*x0+wh*h0+b)*(1-sigmoid(wi*x0+wh*h0+b)) = d1*a*h0*h1*(1-h1) = 0$$ \dfrac{\delta L2}{\delta wh}=\dfrac{\delta L2}{\delta y2}\dfrac{\delta y2}{\delta h2}\dfrac{\delta h2}{\delta wh}+\dfrac{\delta L2}{\delta y2}\dfrac{\delta y2}{\delta h2}\dfrac{\delta h2}{\delta h1}\dfrac{\delta h1}{\delta wh}= \dfrac{\delta }{\delta wh} (a*h2+c) = \dfrac{\delta }{\delta wi} (a*sigmoid(wi*x1+wh*h1+b)+c) =  d2*(a*x1*sigmoid(wi*x1+wh*h1+b)*(1-sigmoid(wi*x1+wh*h1+b)) + a*wh*sigmoid(wi*x1+wh*h1+b)*(1-sigmoid(wi*x1+wh*h1+b))*x0*sigmoid(wi*x0+wh*h0+b)*(1-sigmoid(wi*x0+wh*h0+b))) = d2*(a*h1*h2*(1-h2) + a*wh*h2*(1-h2)*h0*h1*(1-h1)) = 0.0877341857017$$\dfrac{\delta L}{\delta wh} = \dfrac{\delta L1}{\delta wh} + \dfrac{\delta L2}{\delta wh} = 0.0877341857017$ $\dfrac{\delta L}{\delta b} = \dfrac{1}{2}\sum_{i=1}^n \dfrac{\delta Li}{\delta b} = \dfrac{\delta L1}{\delta b} + \dfrac{\delta L2}{\delta b}$$ \dfrac{\delta L1}{\delta b}=\dfrac{\delta L1}{\delta y1}\dfrac{\delta y1}{\delta h1}\dfrac{\delta h1}{\delta b} =  \dfrac{\delta }{\delta b} (a*h1+c)= \dfrac{\delta }{\delta b} (a*sigmoid(wi*x0+wh*h0+b)+c) = d1*a*x0*sigmoid(wi*x0+wh*h0+b)*(1-sigmoid(wi*x0+wh*h0+b)) = d1*a*h1*(1-h1) = 0.0924780432298$$ \dfrac{\delta L2}{\delta b}=\dfrac{\delta L2}{\delta y2}\dfrac{\delta y2}{\delta h2}\dfrac{\delta h2}{\delta b}+\dfrac{\delta L2}{\delta y2}\dfrac{\delta y2}{\delta h2}\dfrac{\delta h2}{\delta h1}\dfrac{\delta h1}{\delta b}= \dfrac{\delta }{\delta b} (a*h2+c) = \dfrac{\delta }{\delta b} (a*sigmoid(wi*x1+wh*h1+b)+c) =  d2*(a*x1*sigmoid(wi*x1+wh*h1+b)*(1-sigmoid(wi*x1+wh*h1+b)) + a*wh*sigmoid(wi*x1+wh*h1+b)*(1-sigmoid(wi*x1+wh*h1+b))*x0*sigmoid(wi*x0+wh*h0+b)*(1-sigmoid(wi*x0+wh*h0+b))) = d2*(a*h2*(1-h2) + a*h2*(1-h2)*wh*h1*(1-h1)) = 0.11006588787$$\dfrac{\delta L}{\delta b} = \dfrac{\delta L1}{\delta b} + \dfrac{\delta L2}{\delta b} = 0.20254393109983646$ $\dfrac{\delta L}{\delta a} = \dfrac{1}{2}\sum_{i=1}^n \dfrac{\delta Li}{\delta a} = \dfrac{\delta L1}{\delta a} + \dfrac{\delta L2}{\delta a}$$ \dfrac{\delta L1}{\delta a}=\dfrac{\delta L1}{\delta y1}\dfrac{\delta y1}{\delta a} =  \dfrac{\delta }{\delta a} (a*h1+c)= \dfrac{\delta }{\delta a} (a*sigmoid(wi*x0+wh*h0+b)+c) = d1*sigmoid(wi*x0+wh*h0+b) = d1*h1 = 0.775803492574$$ \dfrac{\delta L2}{\delta a}=\dfrac{\delta L2}{\delta y2}\dfrac{\delta y2}{\delta a} = \dfrac{\delta }{\delta a} (a*h2+c) = \dfrac{\delta }{\delta a} (a*sigmoid(wi*x1+wh*h1+b)+c) = d2*sigmoid(wi*x1+wh*h1+b)= d2*h2 = 0.752907895156$$\dfrac{\delta L}{\delta a} = \dfrac{\delta L1}{\delta a} + \dfrac{\delta L2}{\delta a} = 1.5287113877300644$ $\dfrac{\delta L}{\delta c} = \dfrac{1}{2}\sum_{i=1}^n \dfrac{\delta Li}{\delta c} = \dfrac{\delta L1}{\delta c} + \dfrac{\delta L2}{\delta c}$$ \dfrac{\delta L1}{\delta c}=\dfrac{\delta L1}{\delta y1}\dfrac{\delta y1}{\delta c} =  \dfrac{\delta }{\delta c} (a*h1+c)= \dfrac{\delta }{\delta a} (a*sigmoid(wi*x0+wh*h0+b)+c) = d1 = 0.880797077978$$ \dfrac{\delta L2}{\delta c}=\dfrac{\delta L2}{\delta y2}\dfrac{\delta y2}{\delta c} = \dfrac{\delta }{\delta c} (a*h2+c) = \dfrac{\delta }{\delta a} (a*sigmoid(wi*x1+wh*h1+b)+c) = d2 = 0.867702653653$$\dfrac{\delta L}{\delta c} = \dfrac{\delta L1}{\delta c} + \dfrac{\delta L2}{\delta c} = 1.7484997316304389$ TODO:Answer the above question. * The answers are listed above.* You can use LATEX to edit the equations, and Jupyter notebook can recognize basic LATEX syntax. Alternatively, you can edit equations in some other environment and then paste the screenshot of the equations here. So,$dwi =0.10293621452669977$$dwh =0.0877341857017$$db =0.20254393109983646$$da =1.5287113877300644$$dc =1.7484997316304389$  Task 1, Part 2: Use tensorflow modules to create XOR networkIn this part, you need to build and train an XOR network that can learn the XOR function. It is a very simple implementation of RNN and will give you an idea how RNN is built and how to train it.  XOR networkXOR network can learn the XOR $\oplus$ functionAs shown in the figure below, and for instance, if input $(x0, x1, x2)$=(1,0,0), then output $(y1, y2, y3)$=(1,1,1). That is, $y_n = x_0\oplus x_1 \oplus ... \oplus x_{n-1}$![xor_net](./img/xor.png)  Create data setThis function provides you the way to generate the data which is required for the training process. You should utilize it when building your training function for the LSTM. Please read the source code for more information.<jupyter_code>from ecbm4040.xor.utils import create_dataset<jupyter_output><empty_output><jupyter_text>Build a network using a Tensorlow LSTMCellThis section shows an example how to build a RNN network using an LSTM cell. LSTM cell is an inbuilt class in tensorflow which implements the real behavior of the LSTM neuron. Reference: [TensorFlow LSTM cell](https://www.tensorflow.org/api_docs/python/tf/contrib/rnn/LSTMCell)<jupyter_code>from tensorflow.contrib.rnn import LSTMCell

tf.reset_default_graph()

# Input shape: (num_samples, seq_length, input_dimension)
# Output shape: (num_samples, output_ground_truth), and output_ground_truth is 0/1. 
input_data = tf.placeholder(tf.float32,shape=[None,None,1])
output_data = tf.placeholder(tf.int64,shape=[None,None])

# define LSTM cell
lstm_units = 64
cell = LSTMCell(lstm_units,num_proj=2,state_is_tuple=True)

# create LSTM network: you can also choose other modules provided by tensorflow, like static_rnn etc.
out,_ = tf.nn.dynamic_rnn(cell,input_data,dtype=tf.float32)
pred = tf.argmax(out,axis=2)

# loss function
loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(labels=output_data,logits=out))

# optimization
optimizer = tf.train.AdamOptimizer(learning_rate=0.1).minimize(loss)

# accuracy
correct_num = tf.equal(output_data,pred)
accuracy = tf.reduce_mean(tf.cast(correct_num,tf.float32))<jupyter_output><empty_output><jupyter_text>Training TODO: 1. Build your training funciton for RNN; 2. Plot the cost during the traning<jupyter_code># YOUR TRAINING AND PLOTTING CODE HERE
init_op = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init_op)
costs = []

for epoch in range(100):
    inp_data,out_data = create_dataset(4096)
    _,c,acc = sess.run([optimizer,loss,accuracy],feed_dict={input_data: inp_data, output_data: out_data})
    print("Epoch: {}, Cost: {}, Accuracy: {}%".format(epoch,c,acc*100))
    costs.append(c)
plt.grid("off")
plt.plot(costs,label="Cost Function")
plt.xlabel("Epoch")
plt.ylabel("Cost")
plt.legend()
plt.show()
 
sess.close()<jupyter_output><empty_output><jupyter_text>Task 1, Part 3 :  Build your own LSTMCellIn this part, you need to build your own LSTM cell to achieve the LSTM functionality. TODO: 1. Finish class **MyLSTMCell** in ecbm4040/xor/rnn.py;2. Write the training function for your RNN;3. Plot the cost during training.<jupyter_code>print(tf.__file__)
from ecbm4040.xor.rnn import MyLSTMCell

# recreate xor netowrk with your own LSTM cell
tf.reset_default_graph()

#Input shape: (num_samples,seq_length,input_dimension)
#Output shape: (num_samples, output_ground_truth), and output_ground_truth is 0/1. 
input_data = tf.placeholder(tf.float32,shape=[None,None,1])
output_data = tf.placeholder(tf.int64,shape=[None,None])

# recreate xor netowrk with your own LSTM cell
lstm_units = 64
cell = MyLSTMCell(lstm_units,num_proj=2)

# create LSTM network: you can also choose other modules provided by tensorflow, like static_rnn etc.
out,_ = tf.nn.dynamic_rnn(cell,input_data,dtype=tf.float32)
pred = tf.argmax(out,axis=2)

# loss function
loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(labels=output_data,logits=out))
# optimization
optimizer = tf.train.AdamOptimizer(learning_rate=0.1).minimize(loss)
# accuracy
correct = tf.equal(output_data,pred)
accuracy = tf.reduce_mean(tf.cast(correct,tf.float32))<jupyter_output><empty_output><jupyter_text>Training<jupyter_code># YOUR TRAINING AND PLOTTING CODE HERE
init_op = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init_op)
costs = []

for epoch in range(100):
    inp_data,out_data = create_dataset(4096)
    _,c,acc = sess.run([optimizer,loss,accuracy],feed_dict={input_data: inp_data, output_data: out_data})
    print("Epoch: {}, Cost: {}, Accuracy: {}%".format(epoch,c,acc*100))
    costs.append(c)
import tensorflow as tf
print (tf.__file__)
plt.grid("off")
plt.plot(costs,label="Cost Function")
plt.xlabel("Epoch")
plt.ylabel("Cost")
plt.legend()
plt.show()
 
sess.close()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.19179406079775083, 'fraction_numerical': 0.07134071340713408, 'mean_word_length': 5.500856653340948, 'pattern_counts': {'":': 0, '<': 28, '<?xml version=': 0, '>': 28, 'https://': 1, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '7', 'dir': 'jupyter-structured-clean-dedup', 'id': '387749', 'license': 'BSD-Source-Code', 'n_tokens_mistral': 5120, 'n_tokens_neox': 4617, 'n_words': 997, 'path': 'task1-xor.ipynb', 'repo_name': 'HuangYukun/columbia_cs_deep_learning_3', 'size': '11382'}