<jupyter_start><jupyter_text>Deep MNIST  Construct a deep convolutional MNIST classifier  from https://www.tensorflow.org/versions/r0.9/tutorials/mnist/pros/index.html  Load MNIST Data<jupyter_code>from tensorflow.examples.tutorials.mnist import input_data
# Load training, validation, and testing sets as NumPy arrays. 
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)<jupyter_output>Extracting MNIST_data/train-images-idx3-ubyte.gz
Extracting MNIST_data/train-labels-idx1-ubyte.gz
Extracting MNIST_data/t10k-images-idx3-ubyte.gz
Extracting MNIST_data/t10k-labels-idx1-ubyte.gz<jupyter_text>Start TensorFlow InteractiveSession<jupyter_code># The InteractiveSession class is ideal for IPython notebooks like this one. 
# It facilitates flexibility in how you structure your code, 
# and you can alternate between operations that build the computation graph
# with those that run that graph. 
import tensorflow as tf
sess = tf.InteractiveSession()<jupyter_output><empty_output><jupyter_text>Build a Softmax Regression Model<jupyter_code># Build a softmax regression model with a single linear layer. 
# Create placeholder nodes for the input images and target output classes. 
x = tf.placeholder(tf.float32, shape=[None, 784])
y_ = tf.placeholder(tf.float32, shape=[None, 10])
# Define the weights and biases for the model as Variables.
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))
# Initialize variables for use in session.
sess.run(tf.initialize_all_variables())
# Implement as a softmax regression model. 
y = tf.nn.softmax(tf.matmul(x,W) + b)
# Specify the model's cost function as cross-entropy. 
# Use reduce_sum to sum across all classes; reduce_mean to take sum of averages. 
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))<jupyter_output><empty_output><jupyter_text>Train the Model<jupyter_code># Select steepest gradient descent, with step length of 0.5, to descend the cross entropy. 
# TensorFlow automatically adds operations to: 
# - compute gradients
# - compute parameter update steps
# - apply update steps to the parameters
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
# Run train_step to repeatedly apply gradient descent updates to the parameters. 
# Each training iteration (batch) loads fifty training examples, 
# which feed_dict replaces placeholder tensors x and y_ with. 
for i in range(1000):
    batch = mnist.train.next_batch(50)
    train_step.run(feed_dict={x: batch[0], y_: batch[1]})<jupyter_output><empty_output><jupyter_text>Evaluate the Model<jupyter_code># Use arg_max to identify the label that the model thinks is most likely for each input. 
correct_prediction = tf.equal(tf.arg_max(y,1), tf.arg_max(y_,1))
# Convert booleans to floating point numbers. 
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# Evaluate and print to screen. 
print(accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels}))
# 90.92% classification accuracy. We can do better.<jupyter_output><empty_output><jupyter_text>Build a Multilayer Convolutional Network  Weight Initialization<jupyter_code>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)<jupyter_output><empty_output><jupyter_text>Convolution and Pooling<jupyter_code>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')<jupyter_output><empty_output><jupyter_text>First Convolutional Layer<jupyter_code>W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])
x_image = tf.reshape(x, [-1,28,28,1])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)<jupyter_output><empty_output><jupyter_text>Second Convolutional Layer<jupyter_code>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)<jupyter_output><empty_output><jupyter_text>Densely Connected Layer<jupyter_code>W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])
h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
# Apply dropout before readout layer to reduce overfitting. 
keep_prob = tf.placeholder(tf.float32)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)<jupyter_output><empty_output><jupyter_text>Readout Layer<jupyter_code>W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)<jupyter_output><empty_output><jupyter_text>Train and Evaluate the Model<jupyter_code># Use ADAM optimizer instead of steepest gradient descent. 
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv), reduction_indices=[1]))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
sess.run(tf.initialize_all_variables())
for i in range(20000):
    batch = mnist.train.next_batch(50)
    if i%100 == 0:
        train_accuracy = accuracy.eval(feed_dict={x:batch[0], y_: batch[1], keep_prob: 1.0})
        print("step %d, training accuracy %g"%(i, train_accuracy))
    train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
print("test accuracy %g"%accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))<jupyter_output>test accuracy 0.9908
{'fraction_non_alphanumeric': 0.11818341223917236, 'fraction_numerical': 0.03226372084867613, 'mean_word_length': 6.3981841763942935, 'pattern_counts': {'":': 0, '<': 47, '<?xml version=': 0, '>': 47, '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': '12', 'dir': 'jupyter-structured-clean-dedup', 'id': '527280', 'license': 'MIT', 'n_tokens_mistral': 2190, 'n_tokens_neox': 2060, 'n_words': 461, 'path': 'weekly-work/week1/deep_MNIST.ipynb', 'repo_name': 'nirupam1sharma/Self-Study', 'size': '5703'}