<jupyter_start><jupyter_text>Let's build a small network with two convolutional layers, followed by one fully connected layer. Convolutional networks are more expensive computationally, so we'll limit its depth and number of fully connected nodes.<jupyter_code>batch_size = 16
patch_size = 5
depth = 16
num_hidden = 64

graph = tf.Graph()

with graph.as_default():

  # Input data.
  tf_train_dataset = tf.placeholder(tf.float32, shape=(batch_size, image_size, image_size, num_channels))
  tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels))
  tf_valid_dataset = tf.constant(valid_dataset)
  tf_test_dataset = tf.constant(test_dataset)
  
  # Variables.
  layer1_weights = tf.Variable(tf.truncated_normal([patch_size, patch_size, num_channels, depth], stddev=0.1))
  layer1_biases = tf.Variable(tf.zeros([depth]))
  layer2_weights = tf.Variable(tf.truncated_normal([patch_size, patch_size, depth, depth], stddev=0.1))
  layer2_biases = tf.Variable(tf.constant(1.0, shape=[depth]))
  layer3_weights = tf.Variable(tf.truncated_normal([image_size // 4 * image_size // 4 * depth, num_hidden], stddev=0.1))
  layer3_biases = tf.Variable(tf.constant(1.0, shape=[num_hidden]))
  layer4_weights = tf.Variable(tf.truncated_normal([num_hidden, num_labels], stddev=0.1))
  layer4_biases = tf.Variable(tf.constant(1.0, shape=[num_labels]))
  
  # Model.
  def model(data):
    conv = tf.nn.conv2d(data, layer1_weights, [1, 2, 2, 1], padding='SAME')
    hidden = tf.nn.relu(conv + layer1_biases)
    conv = tf.nn.conv2d(hidden, layer2_weights, [1, 2, 2, 1], padding='SAME')
    hidden = tf.nn.relu(conv + layer2_biases)
    shape = hidden.get_shape().as_list()
    reshape = tf.reshape(hidden, [shape[0], shape[1] * shape[2] * shape[3]])
    hidden = tf.nn.relu(tf.matmul(reshape, layer3_weights) + layer3_biases)
    return tf.matmul(hidden, layer4_weights) + layer4_biases
  
  # Training computation.
  logits = model(tf_train_dataset)
  loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels))

  # Optimizer.
  optimizer = tf.train.GradientDescentOptimizer(0.05).minimize(loss)
  
  # Predictions for the training, validation, and test data.
  train_prediction = tf.nn.softmax(logits)
  valid_prediction = tf.nn.softmax(model(tf_valid_dataset))
  test_prediction = tf.nn.softmax(model(tf_test_dataset))

num_steps = 1001

with tf.Session(graph=graph) as session:
  tf.initialize_all_variables().run()
  print('Initialized')
  for step in range(num_steps):
    offset = (step * batch_size) % (train_labels.shape[0] - batch_size)
    batch_data = train_dataset[offset:(offset + batch_size), :, :, :]
    batch_labels = train_labels[offset:(offset + batch_size), :]
    feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels}
    _, l, predictions = session.run(
      [optimizer, loss, train_prediction], feed_dict=feed_dict)
    if (step % 100 == 0):
      print('Minibatch loss at step %d: %f' % (step, l))
      print('Minibatch accuracy: %.1f%%' % accuracy(predictions, batch_labels))
      print('Validation accuracy: %.1f%%' % accuracy(
        valid_prediction.eval(), valid_labels))
  print('Test accuracy: %.1f%%' % accuracy(test_prediction.eval(), test_labels))<jupyter_output>WARNING:tensorflow:From <ipython-input-23-b0900ef7635b>:4 in <module>.: initialize_all_variables (from tensorflow.python.ops.variables) is deprecated and will be removed after 2017-03-02.
Instructions for updating:
Use `tf.global_variables_initializer` instead.
Initialized
Minibatch loss at step 0: 3.535262
Minibatch accuracy: 6.2%
Validation accuracy: 10.2%
Minibatch loss at step 100: 1.773929
Minibatch accuracy: 50.0%
Validation accuracy: 62.7%
Minibatch loss at step 200: 1.259379
Minibatch accuracy: 87.5%
Validation accuracy: 77.3%
Minibatch loss at step 300: 1.352542
Minibatch accuracy: 50.0%
Validation accuracy: 79.5%
Minibatch loss at step 400: 1.324809
Minibatch accuracy: 62.5%
Validation accuracy: 80.1%
Minibatch loss at step 500: 0.590050
Minibatch accuracy: 81.2%
Validation accuracy: 81.1%
Minibatch loss at step 600: 1.131197
Minibatch accuracy: 62.5%
Validation accuracy: 80.6%
Minibatch loss at step 700: 0.526126
Minibatch accuracy: 81.2%
Validation accuracy: 81.8%
Minibatch[...]<jupyter_text>Problem 1=========The convolutional model above uses convolutions with stride 2 to reduce the dimensionality. Replace the strides by a max pooling operation (nn.max_pool()) of stride 2 and kernel size 2.<jupyter_code>batch_size = 16
patch_size = 5
depth = 16
num_hidden = 64

graph = tf.Graph()

with graph.as_default():

  # Input data.
  tf_train_dataset = tf.placeholder(tf.float32, shape=(batch_size, image_size, image_size, num_channels))
  tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels))
  tf_valid_dataset = tf.constant(valid_dataset)
  tf_test_dataset = tf.constant(test_dataset)
  
  # Variables.
  layer1_weights = tf.Variable(tf.truncated_normal([patch_size, patch_size, num_channels, depth], stddev=0.1))
  layer1_biases = tf.Variable(tf.zeros([depth]))
  layer2_weights = tf.Variable(tf.truncated_normal([patch_size, patch_size, depth, depth], stddev=0.1))
  layer2_biases = tf.Variable(tf.constant(1.0, shape=[depth]))
  layer3_weights = tf.Variable(tf.truncated_normal([image_size // 4 * image_size // 4 * depth, num_hidden], stddev=0.1))
  layer3_biases = tf.Variable(tf.constant(1.0, shape=[num_hidden]))
  layer4_weights = tf.Variable(tf.truncated_normal([num_hidden, num_labels], stddev=0.1))
  layer4_biases = tf.Variable(tf.constant(1.0, shape=[num_labels]))    
    
    
  # Model.
  def model(data):
    conv = tf.nn.conv2d(data, layer1_weights, [1, 1, 1, 1], padding='SAME')
    pool = tf.nn.max_pool(conv, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME')
    hidden = tf.nn.relu(pool + layer1_biases)
            
    conv = tf.nn.conv2d(hidden, layer2_weights, [1, 1, 1, 1], padding='SAME')
    pool = tf.nn.max_pool(conv, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME')
    hidden = tf.nn.relu(pool + layer2_biases)
    
    shape = hidden.get_shape().as_list()
    reshape = tf.reshape(hidden, [shape[0], shape[1] * shape[2] * shape[3]])
    hidden = tf.nn.relu(tf.matmul(reshape, layer3_weights) + layer3_biases)
    return tf.matmul(hidden, layer4_weights) + layer4_biases
  
  # Training computation.
  logits = model(tf_train_dataset)
  loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels))

  # Optimizer.
  optimizer = tf.train.GradientDescentOptimizer(0.05).minimize(loss)
  
  # Predictions for the training, validation, and test data.
  train_prediction = tf.nn.softmax(logits)
  valid_prediction = tf.nn.softmax(model(tf_valid_dataset))
  test_prediction = tf.nn.softmax(model(tf_test_dataset))

num_steps = 1001

with tf.Session(graph=graph) as session:
  tf.global_variables_initializer().run()
  print('Initialized')
  for step in range(num_steps):
    offset = (step * batch_size) % (train_labels.shape[0] - batch_size)
    batch_data = train_dataset[offset:(offset + batch_size), :, :, :]
    batch_labels = train_labels[offset:(offset + batch_size), :]
    feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels}
    _, l, predictions = session.run(
      [optimizer, loss, train_prediction], feed_dict=feed_dict)
    if (step % 100 == 0):
      print('Minibatch loss at step %d: %f' % (step, l))
      print('Minibatch accuracy: %.1f%%' % accuracy(predictions, batch_labels))
      print('Validation accuracy: %.1f%%' % accuracy(
        valid_prediction.eval(), valid_labels))
  print('Test accuracy: %.1f%%' % accuracy(test_prediction.eval(), test_labels))<jupyter_output>Initialized
Minibatch loss at step 0: 3.494336
Minibatch accuracy: 0.0%
Validation accuracy: 12.6%
Minibatch loss at step 100: 1.925441
Minibatch accuracy: 50.0%
Validation accuracy: 61.4%
Minibatch loss at step 200: 1.107535
Minibatch accuracy: 68.8%
Validation accuracy: 78.4%
Minibatch loss at step 300: 1.229914
Minibatch accuracy: 50.0%
Validation accuracy: 80.4%
Minibatch loss at step 400: 0.898318
Minibatch accuracy: 75.0%
Validation accuracy: 77.2%
Minibatch loss at step 500: 0.736104
Minibatch accuracy: 81.2%
Validation accuracy: 82.2%
Minibatch loss at step 600: 1.124599
Minibatch accuracy: 68.8%
Validation accuracy: 81.5%
Minibatch loss at step 700: 0.548055
Minibatch accuracy: 75.0%
Validation accuracy: 83.1%
Minibatch loss at step 800: 0.425287
Minibatch accuracy: 81.2%
Validation accuracy: 83.1%
Minibatch loss at step 900: 0.600255
Minibatch accuracy: 75.0%
Validation accuracy: 83.2%
Minibatch loss at step 1000: 0.239167
Minibatch accuracy: 93.8%
Validation accuracy: 84.5%
[...]<jupyter_text>Problem 2=========Try to get the best performance you can using a convolutional net. Look for example at the classic LeNet5 architecture, adding Dropout, and/or adding learning rate decay.<jupyter_code>batch_size = 32#16#93.7%
patch_size = 5
depth = 16
num_hidden = 128#64
beta = 0.005

graph = tf.Graph()

with graph.as_default():

  # Placeholder to control dropout probability.
  keep_prob = tf.placeholder(tf.float32)
  keep_prob_conv = tf.placeholder(tf.float32)
    
  # Input data.
  tf_train_dataset = tf.placeholder(tf.float32, shape=(batch_size, image_size, image_size, num_channels))
  tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels))
  tf_valid_dataset = tf.constant(valid_dataset)
  tf_test_dataset = tf.constant(test_dataset)
  
  # Variables.
  layer1_weights = tf.Variable(tf.truncated_normal([patch_size, patch_size, num_channels, depth], stddev=0.1))
  layer1_biases = tf.Variable(tf.zeros([depth]))
  layer2_weights = tf.Variable(tf.truncated_normal([patch_size, patch_size, depth, depth], stddev=0.1))
  layer2_biases = tf.Variable(tf.constant(1.0, shape=[depth]))
  layer3_weights = tf.Variable(tf.truncated_normal([image_size // 4 * image_size // 4 * depth, num_hidden], stddev=0.1))
  layer3_biases = tf.Variable(tf.constant(1.0, shape=[num_hidden]))
  layer4_weights = tf.Variable(tf.truncated_normal([num_hidden, num_labels], stddev=0.1))
  layer4_biases = tf.Variable(tf.constant(1.0, shape=[num_labels]))    
    
    
  # Model.
  def model(data):
    conv = tf.nn.conv2d(data, layer1_weights, [1, 1, 1, 1], padding='SAME')
    pool = tf.nn.max_pool(conv, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME')
    hidden = tf.nn.relu(pool + layer1_biases)
    drop = tf.nn.dropout(hidden, keep_prob_conv)

    conv = tf.nn.conv2d(drop, layer2_weights, [1, 1, 1, 1], padding='SAME')
    pool = tf.nn.max_pool(conv, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME')
    hidden = tf.nn.relu(pool + layer2_biases)
    drop = tf.nn.dropout(hidden, keep_prob_conv)
    
    shape = drop.get_shape().as_list()
    reshape = tf.reshape(drop, [shape[0], shape[1] * shape[2] * shape[3]])
    hidden = tf.nn.relu(tf.matmul(reshape, layer3_weights) + layer3_biases)
    drop = tf.nn.dropout(hidden, keep_prob)
    
    return tf.matmul(drop, layer4_weights) + layer4_biases
  
  # Training computation.
  logits = model(tf_train_dataset)
  loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels))

  # Add the regularization term to the loss.
  loss += beta * (tf.nn.l2_loss(layer3_weights) + tf.nn.l2_loss(layer4_weights))

  # Optimizer.
  optimizer = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
  
  # Predictions for the training, validation, and test data.
  train_prediction = tf.nn.softmax(logits)
  valid_prediction = tf.nn.softmax(model(tf_valid_dataset))
  test_prediction = tf.nn.softmax(model(tf_test_dataset))

num_steps = 3001

with tf.Session(graph=graph) as session:
  tf.global_variables_initializer().run()
  print('Initialized')
  for step in range(num_steps):
    offset = (step * batch_size) % (train_labels.shape[0] - batch_size)
    batch_data = train_dataset[offset:(offset + batch_size), :, :, :]
    batch_labels = train_labels[offset:(offset + batch_size), :]
    feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels, keep_prob:1.0, keep_prob_conv:1.0}
    feed_dict_w_dropout = {tf_train_dataset : batch_data, tf_train_labels : batch_labels, keep_prob:0.5, keep_prob_conv:0.9}
    _, l, predictions = session.run([optimizer, loss, train_prediction], feed_dict=feed_dict_w_dropout)
    if (step % 100 == 0):
      print('Minibatch loss at step %d: %f' % (step, l))
      print('Minibatch accuracy: %.1f%%' % accuracy(predictions, batch_labels))
      print('Validation accuracy: %.1f%%' % accuracy(valid_prediction.eval(feed_dict=feed_dict), valid_labels))
  print('Test accuracy: %.1f%%' % accuracy(test_prediction.eval(feed_dict=feed_dict), test_labels))<jupyter_output>Initialized
Minibatch loss at step 0: 8.447297
Minibatch accuracy: 3.1%
Validation accuracy: 10.0%
Minibatch loss at step 100: 3.203046
Minibatch accuracy: 53.1%
Validation accuracy: 71.8%
Minibatch loss at step 200: 2.274400
Minibatch accuracy: 81.2%
Validation accuracy: 77.1%
Minibatch loss at step 300: 2.290873
Minibatch accuracy: 71.9%
Validation accuracy: 81.8%
Minibatch loss at step 400: 2.502475
Minibatch accuracy: 71.9%
Validation accuracy: 83.0%
Minibatch loss at step 500: 1.741334
Minibatch accuracy: 84.4%
Validation accuracy: 84.2%
Minibatch loss at step 600: 1.773890
Minibatch accuracy: 84.4%
Validation accuracy: 84.7%
Minibatch loss at step 700: 1.321164
Minibatch accuracy: 93.8%
Validation accuracy: 84.8%
Minibatch loss at step 800: 1.355869
Minibatch accuracy: 87.5%
Validation accuracy: 85.0%
Minibatch loss at step 900: 1.482969
Minibatch accuracy: 81.2%
Validation accuracy: 85.8%
Minibatch loss at step 1000: 1.516676
Minibatch accuracy: 78.1%
Validation accuracy: 85.5%
[...]
{'fraction_non_alphanumeric': 0.12858187134502924, 'fraction_numerical': 0.05650584795321637, 'mean_word_length': 4.894442050840155, 'pattern_counts': {'":': 0, '<': 12, '<?xml version=': 0, '>': 12, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '612157', 'license': 'MIT', 'n_tokens_mistral': 5355, 'n_tokens_neox': 4849, 'n_words': 1126, 'path': 'study/udacity-deep-learning/assignment4-convnet.ipynb', 'repo_name': 'flaviostutz/datascience-snippets', 'size': '13680'}