📚 The CoCalc Library - books, templates and other resources
License: OTHER
""" Examples to demonstrate variable sharing1CS 20: 'TensorFlow for Deep Learning Research'2cs20.stanford.edu3Chip Huyen ([email protected])4Lecture 055"""6import os7os.environ['TF_CPP_MIN_LOG_LEVEL']='2'89import tensorflow as tf1011x1 = tf.truncated_normal([200, 100], name='x1')12x2 = tf.truncated_normal([200, 100], name='x2')1314def two_hidden_layers(x):15assert x.shape.as_list() == [200, 100]16w1 = tf.Variable(tf.random_normal([100, 50]), name='h1_weights')17b1 = tf.Variable(tf.zeros([50]), name='h1_biases')18h1 = tf.matmul(x, w1) + b119assert h1.shape.as_list() == [200, 50]20w2 = tf.Variable(tf.random_normal([50, 10]), name='h2_weights')21b2 = tf.Variable(tf.zeros([10]), name='2_biases')22logits = tf.matmul(h1, w2) + b223return logits2425def two_hidden_layers_2(x):26assert x.shape.as_list() == [200, 100]27w1 = tf.get_variable('h1_weights', [100, 50], initializer=tf.random_normal_initializer())28b1 = tf.get_variable('h1_biases', [50], initializer=tf.constant_initializer(0.0))29h1 = tf.matmul(x, w1) + b130assert h1.shape.as_list() == [200, 50]31w2 = tf.get_variable('h2_weights', [50, 10], initializer=tf.random_normal_initializer())32b2 = tf.get_variable('h2_biases', [10], initializer=tf.constant_initializer(0.0))33logits = tf.matmul(h1, w2) + b234return logits3536# logits1 = two_hidden_layers(x1)37# logits2 = two_hidden_layers(x2)3839# logits1 = two_hidden_layers_2(x1)40# logits2 = two_hidden_layers_2(x2)4142# with tf.variable_scope('two_layers') as scope:43# logits1 = two_hidden_layers_2(x1)44# scope.reuse_variables()45# logits2 = two_hidden_layers_2(x2)4647# with tf.variable_scope('two_layers') as scope:48# logits1 = two_hidden_layers_2(x1)49# scope.reuse_variables()50# logits2 = two_hidden_layers_2(x2)5152def fully_connected(x, output_dim, scope):53with tf.variable_scope(scope, reuse=tf.AUTO_REUSE) as scope:54w = tf.get_variable('weights', [x.shape[1], output_dim], initializer=tf.random_normal_initializer())55b = tf.get_variable('biases', [output_dim], initializer=tf.constant_initializer(0.0))56return tf.matmul(x, w) + b5758def two_hidden_layers(x):59h1 = fully_connected(x, 50, 'h1')60h2 = fully_connected(h1, 10, 'h2')6162with tf.variable_scope('two_layers') as scope:63logits1 = two_hidden_layers(x1)64# scope.reuse_variables()65logits2 = two_hidden_layers(x2)6667writer = tf.summary.FileWriter('./graphs/cool_variables', tf.get_default_graph())68writer.close()6970