本文整理汇总了Python中tensorflow.python.ops.variables.Variable方法的典型用法代码示例。如果您正苦于以下问题:Python variables.Variable方法的具体用法?Python variables.Variable怎么用?Python variables.Variable使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tensorflow.python.ops.variables
的用法示例。
在下文中一共展示了variables.Variable方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: testEmbeddingOp
# 需要导入模块: from tensorflow.python.ops import variables [as 别名]
# 或者: from tensorflow.python.ops.variables import Variable [as 别名]
def testEmbeddingOp(self):
graph = tf.Graph()
with self.test_session(graph=graph):
params = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]],
tf.float32)
var = variables.Variable([self.MakeSparseFeatures([1, 2], [1.0, 1.0]),
self.MakeSparseFeatures([], [])])
var.initializer.run()
embeddings = graph_builder.EmbeddingLookupFeatures(params, var,
True).eval()
self.assertAllClose([[8.0, 10.0], [0.0, 0.0]], embeddings)
var = variables.Variable([self.MakeSparseFeatures([], []),
self.MakeSparseFeatures([0, 2],
[0.5, 2.0])])
var.initializer.run()
embeddings = graph_builder.EmbeddingLookupFeatures(params, var,
True).eval()
self.assertAllClose([[0.0, 0.0], [10.5, 13.0]], embeddings)
示例2: _underlying_variable_ref
# 需要导入模块: from tensorflow.python.ops import variables [as 别名]
# 或者: from tensorflow.python.ops.variables import Variable [as 别名]
def _underlying_variable_ref(t):
"""Find the underlying variable ref.
Traverses through Identity, ReadVariableOp, and Enter ops.
Stops when op type has Variable or VarHandle in name.
Args:
t: a Tensor
Returns:
a Tensor that is a variable ref, or None on error.
"""
while t.op.type in ["Identity", "ReadVariableOp", "Enter"]:
t = t.op.inputs[0]
op_type = t.op.type
if "Variable" in op_type or "VarHandle" in op_type:
return t
else:
return None
示例3: _create_local
# 需要导入模块: from tensorflow.python.ops import variables [as 别名]
# 或者: from tensorflow.python.ops.variables import Variable [as 别名]
def _create_local(name, shape, collections=None, validate_shape=True,
dtype=tf.float32):
"""Creates a new local variable.
Args:
name: The name of the new or existing variable.
shape: Shape of the new or existing variable.
collections: A list of collection names to which the Variable will be added.
validate_shape: Whether to validate the shape of the variable.
dtype: Data type of the variables.
Returns:
The created variable.
"""
# Make sure local variables are added to tf.GraphKeys.LOCAL_VARIABLES
collections = list(collections or [])
collections += [ops.GraphKeys.LOCAL_VARIABLES]
return variables.Variable(
initial_value=array_ops.zeros(shape, dtype=dtype),
name=name,
trainable=False,
collections=collections,
validate_shape=validate_shape)
示例4: testDebugCondWatchingWholeGraphWorks
# 需要导入模块: from tensorflow.python.ops import variables [as 别名]
# 或者: from tensorflow.python.ops.variables import Variable [as 别名]
def testDebugCondWatchingWholeGraphWorks(self):
with session.Session() as sess:
x = variables.Variable(10.0, name="x")
y = variables.Variable(20.0, name="y")
cond = control_flow_ops.cond(
x > y, lambda: math_ops.add(x, 1), lambda: math_ops.add(y, 1))
sess.run(variables.global_variables_initializer())
run_options = config_pb2.RunOptions(output_partition_graphs=True)
debug_utils.watch_graph(run_options,
sess.graph,
debug_urls=self._debug_urls())
run_metadata = config_pb2.RunMetadata()
self.assertEqual(
21, sess.run(cond, options=run_options, run_metadata=run_metadata))
dump = debug_data.DebugDumpDir(
self._dump_root, partition_graphs=run_metadata.partition_graphs)
self.assertAllClose(
[21.0], dump.get_tensors("cond/Merge", 0, "DebugIdentity"))
示例5: _get_fetch_names
# 需要导入模块: from tensorflow.python.ops import variables [as 别名]
# 或者: from tensorflow.python.ops.variables import Variable [as 别名]
def _get_fetch_names(fetches):
"""Get a flattened list of the names in run() call fetches.
Args:
fetches: Fetches of the `Session.run()` call. It maybe a Tensor, an
Operation or a Variable. It may also be nested lists, tuples or
dicts. See doc of `Session.run()` for more details.
Returns:
(list of str) A flattened list of fetch names from `fetches`.
"""
lines = []
if isinstance(fetches, (list, tuple)):
for fetch in fetches:
lines.extend(_get_fetch_names(fetch))
elif isinstance(fetches, dict):
for key in fetches:
lines.extend(_get_fetch_names(fetches[key]))
else:
# This ought to be a Tensor, an Operation or a Variable, for which the name
# attribute should be available. (Bottom-out condition of the recursion.)
lines.append(_get_fetch_name(fetches))
return lines
示例6: variable
# 需要导入模块: from tensorflow.python.ops import variables [as 别名]
# 或者: from tensorflow.python.ops.variables import Variable [as 别名]
def variable(initial_value=None,
trainable=True,
collections=None,
validate_shape=True,
caching_device=None,
name=None,
dtype=None):
if get_variable_scope().use_resource:
return resource_variable_ops.ResourceVariable(
initial_value=initial_value, trainable=trainable,
collections=collections, validate_shape=validate_shape,
caching_device=caching_device, name=name, dtype=dtype)
else:
return variables.Variable(
initial_value=initial_value, trainable=trainable,
collections=collections, validate_shape=validate_shape,
caching_device=caching_device, name=name, dtype=dtype)
示例7: _apply_sparse
# 需要导入模块: from tensorflow.python.ops import variables [as 别名]
# 或者: from tensorflow.python.ops.variables import Variable [as 别名]
def _apply_sparse(self, grad, var):
"""Add ops to apply sparse gradients to `var`.
The IndexedSlices object passed to `grad` in this function is by default
pre-processed in `_apply_sparse_duplicate_indices` to remove duplicate
indices (see its docstring for details). Optimizers which can tolerate or
have correct special cases for duplicate sparse indices may override
`_apply_sparse_duplicate_indices` instead of this function, avoiding that
overhead.
Args:
grad: `IndexedSlices`, with no repeated indices.
var: A `Variable` object.
Return:
An `Operation`.
"""
raise NotImplementedError()
示例8: _get_or_make_slot_with_initializer
# 需要导入模块: from tensorflow.python.ops import variables [as 别名]
# 或者: from tensorflow.python.ops.variables import Variable [as 别名]
def _get_or_make_slot_with_initializer(self, var, initializer, shape, dtype,
slot_name, op_name):
"""Find or create a slot for a variable, using an Initializer.
Args:
var: A `Variable` object.
initializer: An `Initializer`. The initial value of the slot.
shape: Shape of the initial value of the slot.
dtype: Type of the value of the slot.
slot_name: Name for the slot.
op_name: Name to use when scoping the Variable that
needs to be created for the slot.
Returns:
A `Variable` object.
"""
named_slots = self._slot_dict(slot_name)
if _var_key(var) not in named_slots:
named_slots[_var_key(var)] = slot_creator.create_slot_with_initializer(
var, initializer, shape, dtype, op_name)
return named_slots[_var_key(var)]
示例9: _zeros_slot
# 需要导入模块: from tensorflow.python.ops import variables [as 别名]
# 或者: from tensorflow.python.ops.variables import Variable [as 别名]
def _zeros_slot(self, var, slot_name, op_name):
"""Find or create a slot initialized with 0.0.
Args:
var: A `Variable` object.
slot_name: Name for the slot.
op_name: Name to use when scoping the Variable that
needs to be created for the slot.
Returns:
A `Variable` object.
"""
named_slots = self._slot_dict(slot_name)
if _var_key(var) not in named_slots:
named_slots[_var_key(var)] = slot_creator.create_zeros_slot(var, op_name)
return named_slots[_var_key(var)]
示例10: _set_checkpoint_initializer
# 需要导入模块: from tensorflow.python.ops import variables [as 别名]
# 或者: from tensorflow.python.ops.variables import Variable [as 别名]
def _set_checkpoint_initializer(variable,
ckpt_file,
tensor_name,
slice_spec,
name="checkpoint_initializer"):
"""Overrides given variable's initialization op.
Sets variable initializer to assign op that initializes variable from tensor's
value in the checkpoint.
Args:
variable: `tf.Variable` object.
ckpt_file: string, full path of the checkpoint.
tensor_name: Name of the tensor to load from the checkpoint.
slice_spec: Slice specification for loading partitioned tensors.
name: Name of the operation.
"""
base_type = variable.dtype.base_dtype
restore_op = io_ops.restore_v2(
ckpt_file, [tensor_name], [slice_spec], [base_type], name=name)[0]
variable._initializer_op = state_ops.assign(variable, restore_op) # pylint:disable=protected-access
示例11: global_step
# 需要导入模块: from tensorflow.python.ops import variables [as 别名]
# 或者: from tensorflow.python.ops.variables import Variable [as 别名]
def global_step(sess, global_step_tensor):
"""Small helper to get the global step.
```python
# Creates a variable to hold the global_step.
global_step_tensor = tf.Variable(10, trainable=False, name='global_step')
# Creates a session.
sess = tf.Session()
# Initializes the variable.
print('global_step: %s' % tf.train.global_step(sess, global_step_tensor))
global_step: 10
```
Args:
sess: A TensorFlow `Session` object.
global_step_tensor: `Tensor` or the `name` of the operation that contains
the global step.
Returns:
The global step value.
"""
return int(sess.run(global_step_tensor))
示例12: assert_global_step
# 需要导入模块: from tensorflow.python.ops import variables [as 别名]
# 或者: from tensorflow.python.ops.variables import Variable [as 别名]
def assert_global_step(global_step_tensor):
"""Asserts `global_step_tensor` is a scalar int `Variable` or `Tensor`.
Args:
global_step_tensor: `Tensor` to test.
"""
if not (isinstance(global_step_tensor, variables.Variable) or
isinstance(global_step_tensor, ops.Tensor) or
isinstance(global_step_tensor,
resource_variable_ops.ResourceVariable)):
raise TypeError(
'Existing "global_step" must be a Variable or Tensor: %s.' %
global_step_tensor)
if not global_step_tensor.dtype.base_dtype.is_integer:
raise TypeError('Existing "global_step" does not have integer type: %s' %
global_step_tensor.dtype)
if global_step_tensor.get_shape().ndims != 0:
raise TypeError('Existing "global_step" is not scalar: %s' %
global_step_tensor.get_shape())
示例13: constant_value
# 需要导入模块: from tensorflow.python.ops import variables [as 别名]
# 或者: from tensorflow.python.ops.variables import Variable [as 别名]
def constant_value(pred):
"""Return the bool value for `pred`, or None if `pred` had a dynamic value.
Arguments:
pred: A scalar, either a Python bool or a TensorFlow boolean variable
or tensor.
Returns:
True or False if `pred` has a constant boolean value, None otherwise.
Raises:
TypeError is pred is not a Variable, Tensor or bool.
"""
if isinstance(pred, bool):
pred_value = pred
elif isinstance(pred, variables.Variable):
pred_value = None
elif isinstance(pred, ops.Tensor):
pred_value = tensor_util.constant_value(pred)
else:
raise TypeError('`pred` must be a Tensor, a Variable, or a Python bool.')
return pred_value
示例14: _prepare_gramian
# 需要导入模块: from tensorflow.python.ops import variables [as 别名]
# 或者: from tensorflow.python.ops.variables import Variable [as 别名]
def _prepare_gramian(self, factors, gramian):
"""Helper function to create ops to prepare/calculate gramian.
Args:
factors: Variable or list of Variable representing (sharded) factors.
Used to compute the updated corresponding gramian value.
gramian: Variable storing the gramian calculated from the factors.
Returns:
A op that updates the gramian with the calcuated value from the factors.
"""
partial_gramians = []
for f in factors:
with ops.colocate_with(f):
partial_gramians.append(math_ops.matmul(f, f, transpose_a=True))
with ops.colocate_with(gramian):
prep_gramian = state_ops.assign(gramian,
math_ops.add_n(partial_gramians)).op
return prep_gramian
示例15: record_variable_inits
# 需要导入模块: from tensorflow.python.ops import variables [as 别名]
# 或者: from tensorflow.python.ops.variables import Variable [as 别名]
def record_variable_inits(self):
"""Context manager to record Variable initializations.
Sets _in_variable_creation to True before a Variable is initialized.
NOTE(keveman): This is used for recording the list of assign ops
that are used to initialize variables. It relies on the fact that
the constructor of Variable class creates exactly one assign op that is
used for initializing the variable. Variable ops not created using the
variables.Variable class are not added to _init_ops and hence not
initialized automatically.
"""
old_init = getattr(variables.Variable, '__init__')
def record(*args, **kwargs):
self._in_variable_creation = True
old_init(*args, **kwargs)
self._in_variable_creation = False
setattr(variables.Variable, '__init__', record)
yield
setattr(variables.Variable, '__init__', old_init)
# pylint: enable=g-doc-return-or-yield