Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

📚 The CoCalc Library - books, templates and other resources

132937 views
License: OTHER
1
# From [github]/tensorflow/python/kernel_tests/variable_scope_test.py
2
def testGetterThatCreatesTwoVariablesAndSumsThem(self):
3
4
def custom_getter(getter, name, *args, **kwargs):
5
g_0 = getter("%s/0" % name, *args, **kwargs)
6
g_1 = getter("%s/1" % name, *args, **kwargs)
7
with tf.name_scope("custom_getter"):
8
return g_0 + g_1 # or g_0 * const / ||g_0|| or anything you want
9
10
with variable_scope.variable_scope("scope", custom_getter=custom_getter):
11
v = variable_scope.get_variable("v", [1, 2, 3])
12
# Or a full model if you wish. OO layers are ok.
13
14
self.assertEqual([1, 2, 3], v.get_shape())
15
true_vars = variables_lib.trainable_variables()
16
self.assertEqual(2, len(true_vars))
17
self.assertEqual("scope/v/0:0", true_vars[0].name)
18
self.assertEqual("scope/v/1:0", true_vars[1].name)
19
self.assertEqual("custom_getter/add:0", v.name)
20
with self.test_session() as sess:
21
variables_lib.global_variables_initializer().run()
22
np_vars, np_v = sess.run([true_vars, v])
23
self.assertAllClose(np_v, sum(np_vars))
24
25