Skip to content

Commit 95e189d

Browse files
lukaszkaiserkeveman
authored andcommitted
Allow to use a Tensor as initializer in get_variable. Fixes tensorflow#589.
Change: 112993949
1 parent 77c5cbb commit 95e189d

2 files changed

Lines changed: 35 additions & 5 deletions

File tree

‎tensorflow/python/kernel_tests/variable_scope_test.py‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,23 @@ def testVarScopeIntializer(self):
7070
sess.run(tf.initialize_variables([w]))
7171
self.assertAllClose(w.eval(), 0.3)
7272

73+
def testIntializeFromValue(self):
74+
with self.test_session() as sess:
75+
init = tf.constant(0.1)
76+
w = variable_scope.get_variable("v", initializer=init)
77+
sess.run(tf.initialize_variables([w]))
78+
self.assertAllClose(w.eval(), 0.1)
79+
80+
with self.assertRaisesRegexp(ValueError, "shape"):
81+
# We disallow explicit shape specification when initializer is constant.
82+
variable_scope.get_variable("u", [1], initializer=init)
83+
84+
with variable_scope.variable_scope("foo", initializer=init):
85+
# Constant initializer can be passed through scopes if needed.
86+
v = variable_scope.get_variable("v")
87+
sess.run(tf.initialize_variables([v]))
88+
self.assertAllClose(v.eval(), 0.1)
89+
7390
def testControlDeps(self):
7491
with self.test_session() as sess:
7592
v0 = variable_scope.get_variable("v0", [1],

‎tensorflow/python/ops/variable_scope.py‎

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,8 @@ def get_variable(self, name, shape=None, dtype=dtypes.float32,
6060
6161
If initializer is `None` (the default), the default initializer passed in
6262
the constructor is used. If that one is `None` too, we use a new
63-
`UniformUnitScalingInitializer`.
63+
`UniformUnitScalingInitializer`. If initializer is a Tensor, we use
64+
it as a value and derive the shape from the initializer.
6465
6566
Args:
6667
name: the name of the new or existing variable.
@@ -81,9 +82,17 @@ def get_variable(self, name, shape=None, dtype=dtypes.float32,
8182
when reusing a variable and specifying a conflicting shape,
8283
or when violating reuse during variable creation.
8384
"""
85+
# Set to true if initializer is a constant.
86+
initializing_from_value = False
87+
if initializer is not None and isinstance(initializer, ops.Tensor):
88+
initializing_from_value = True
89+
if shape is not None and initializing_from_value:
90+
raise ValueError("If initializer is a constant, do not specify shape.")
91+
8492
should_check = reuse is not None
8593
dtype = dtypes.as_dtype(dtype)
8694
shape = tensor_shape.as_shape(shape)
95+
8796
if name in self._vars:
8897
# Here we handle the case when returning an existing variable.
8998
if should_check and not reuse:
@@ -106,15 +115,18 @@ def get_variable(self, name, shape=None, dtype=dtypes.float32,
106115
if should_check and reuse:
107116
raise ValueError("Under-sharing: Variable %s does not exist, disallowed."
108117
" Did you mean to set reuse=None in VarScope?" % name)
109-
if not shape.is_fully_defined():
118+
if not shape.is_fully_defined() and not initializing_from_value:
110119
raise ValueError("Shape of a new variable (%s) must be fully defined, "
111120
"but instead was %s." % (name, shape))
112121
if initializer is None:
113122
initializer = init_ops.uniform_unit_scaling_initializer()
114123
# Clear control dependencies while creating the initializer ops.
115124
with ops.control_dependencies(None):
116-
with ops.name_scope(name + "/Initializer/"):
117-
init_val = initializer(shape.as_list(), dtype=dtype)
125+
if initializing_from_value:
126+
init_val = initializer
127+
else:
128+
with ops.name_scope(name + "/Initializer/"):
129+
init_val = initializer(shape.as_list(), dtype=dtype)
118130
v = variables.Variable(init_val, name=name, trainable=trainable,
119131
collections=collections)
120132
self._vars[name] = v
@@ -217,7 +229,8 @@ def get_variable(name, shape=None, dtype=dtypes.float32, initializer=None,
217229
218230
If initializer is `None` (the default), the default initializer passed in
219231
the constructor is used. If that one is `None` too, a
220-
`UniformUnitScalingInitializer` will be used.
232+
`UniformUnitScalingInitializer` will be used. The initializer can also be
233+
a Tensor, in which case the variable is initialized to this value and shape.
221234
222235
Args:
223236
name: the name of the new or existing variable.

0 commit comments

Comments
 (0)