Skip to content

Instantly share code, notes, and snippets.

@domluna
Created July 5, 2017 21:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save domluna/22f104fa14f63bf7564db8aa07a1d11d to your computer and use it in GitHub Desktop.
Save domluna/22f104fa14f63bf7564db8aa07a1d11d to your computer and use it in GitHub Desktop.
import tensorflow as tf
import numpy as np
x = tf.constant(np.random.randn(1, 4, 4, 2), dtype=tf.float32)
# TODO: Use `tf.layers.conv2d_transpose` to return a tensor
# with the shape (1, 8, 8, 5)
conv = 0
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
result = sess.run(conv)
print("Shape = {0}".format(result.shape))
import tensorflow as tf
import numpy as np
# custom init with the seed set to 0 by default
def custom_init(shape, dtype=tf.float32, partition_info=None, seed=0):
return tf.random_normal(shape, dtype=dtype, seed=seed)
num_outputs = 3
x = tf.constant(np.random.randn(1, 2, 2, 1), dtype=tf.float32)
with tf.Session() as sess:
# `tf.layers.dense` flattens the input tensor if the rank > 2 and reshapes it back to the original rank
# as the output.
a = tf.layers.dense(x, num_outputs, kernel_initializer=custom_init)
# TODO: Use `tf.layers.conv2d` to reproduce the result of `tf.layers.dense`.
# Remember to use `custom_init` as the kernel initializer so the weights are
# initialized the same
b = tf.layers.conv2d()
sess.run(tf.global_variables_initializer())
linear_output = sess.run(a)
print("Linear Output =", linear_output, linear_output.shape)
conv1_output = sess.run(b)
print("Conv 1x1 Output =", conv1_output, conv1_output.shape)
print("Same output? =", np.allclose(linear_output, conv1_output, atol=1.e-5))
import tensorflow as tf
ground_truth = tf.constant([
[0, 0, 0, 0],
[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3]], dtype=tf.float32)
prediction = tf.constant([
[0, 0, 0, 0],
[1, 0, 0, 1],
[1, 2, 2, 1],
[3, 3, 0, 3]], dtype=tf.float32)
# TODO: Use `tf.metrics.mean_iou` to compute the mean IoU.
iou = 0
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
# need to initialize local variables for this to run `tf.metrics.mean_iou`
sess.run(tf.local_variables_initializer())
result = sess.run(iou)
# mean iou should be ~0.53869
print("Mean IoU = {0}".format(result))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment