本文整理汇总了Python中tensorflow.compat.v2.Variable方法的典型用法代码示例。如果您正苦于以下问题:Python v2.Variable方法的具体用法?Python v2.Variable怎么用?Python v2.Variable使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tensorflow.compat.v2
的用法示例。
在下文中一共展示了v2.Variable方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: build
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import Variable [as 别名]
def build(self, input_shape):
with math_lib.use_backend("tf"):
# Using `is` instead of `==` following Trax's practice
if self._trax_layer.weights is base.EMPTY_WEIGHTS:
sanitized_input_shape = math_lib.nested_map(
functools.partial(_replace_none_batch, batch_size=self._batch_size),
input_shape)
weights, state = self._trax_layer.init(
tensor_shapes_to_shape_dtypes(sanitized_input_shape, self.dtype),
rng=self._initializer_rng)
else:
weights = self._trax_layer.weights
state = self._trax_layer.state
# Note: `weights` may contain `EMPTY_WEIGHTS`
self._weights = math_lib.nested_map(
functools.partial(tf.Variable, trainable=True), weights)
self._state = math_lib.nested_map(
functools.partial(tf.Variable, trainable=False), state)
self._rng = tf.Variable(self._forward_rng_init, trainable=False)
super(TraxKerasLayer, self).build(input_shape)
示例2: from_config
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import Variable [as 别名]
def from_config(cls, config):
"""Instantiates an entropy model from a configuration dictionary.
Arguments:
config: A `dict`, typically the output of `get_config`.
Returns:
An entropy model.
"""
self = super().from_config(config)
with self.name_scope:
# pylint:disable=protected-access
if config["quantization_offset"]:
zeros = tf.zeros(self.prior_shape, dtype=self.dtype)
self._quantization_offset = tf.Variable(
zeros, name="quantization_offset")
else:
self._quantization_offset = None
# pylint:enable=protected-access
return self
示例3: __init__
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import Variable [as 别名]
def __init__(self, config):
"""Initialize R2R Agent."""
super(DiscriminatorAgent, self).__init__(name='discriminator_r2r')
self._instruction_encoder = instruction_encoder.InstructionEncoder(
num_hidden_layers=2,
output_dim=256,
pretrained_embed_path=config.pretrained_embed_path,
oov_bucket_size=config.oov_bucket_size,
vocab_size=config.vocab_size,
word_embed_dim=config.word_embed_dim,
)
self._image_encoder = image_encoder.ImageEncoder(
256, 512, num_hidden_layers=2)
self.affine_a = tf.Variable(1.0, dtype=tf.float32, trainable=True)
self.affine_b = tf.Variable(0.0, dtype=tf.float32, trainable=True)
示例4: test_no_vars
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import Variable [as 别名]
def test_no_vars(self, target, c, type_):
c = type_(c)
self.assertFunctionMatchesEager(target, c, tf.Variable(0))
示例5: test_while_no_vars
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import Variable [as 别名]
def test_while_no_vars(self, n, type_):
n = type_(n)
self.assertFunctionMatchesEager(while_no_vars, n, tf.Variable(0))
示例6: test_for_no_vars
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import Variable [as 别名]
def test_for_no_vars(self, l, type_):
l = type_(l)
self.assertFunctionMatchesEager(for_no_vars, l, tf.Variable(0))
示例7: test_for_no_vars_ds_iterator
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import Variable [as 别名]
def test_for_no_vars_ds_iterator(self, l):
inputs_ = lambda: (iter(_int_dataset(l)), tf.Variable(0))
self.assertFunctionMatchesEagerStatefulInput(for_no_vars, inputs_)
示例8: test_for_one_var_ds_iterator
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import Variable [as 别名]
def test_for_one_var_ds_iterator(self, l):
inputs_ = lambda: (iter(_int_dataset(l)), tf.Variable(0))
self.assertFunctionMatchesEagerStatefulInput(for_one_var, inputs_)
示例9: tf
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import Variable [as 别名]
def tf(self):
"""A Tensorflow expression which evaluates this NeuralQueryExpression.
Returns:
A Tensorflow expression that computes this NeuralQueryExpression's value.
"""
if isinstance(self._tf, tf.Tensor) or isinstance(self._tf, tf.Variable):
return self._tf # pytype: disable=bad-return-type
else:
return tf.constant(self._tf)
示例10: test_group_rel_from_variable
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import Variable [as 别名]
def test_group_rel_from_variable(self):
x = self.context.one(cell(2, 2), 'place_t')
initializer = tf.keras.initializers.GlorotUniform()(
[1, self.context.get_max_id('dir_g')])
dir_tf_var = tf.Variable(initializer)
dir_nql_exp = self.context.as_nql(dir_tf_var, 'dir_g')
y = x.follow(dir_nql_exp)
y.eval()
示例11: __init__
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import Variable [as 别名]
def __init__(self):
super(AddNet, self).__init__(
tensor_spec.TensorSpec((), tf.float32), (), 'add_net')
self.var = tf.Variable(0.0, dtype=tf.float32)
示例12: __init__
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import Variable [as 别名]
def __init__(self,
time_step_spec: ts.TimeStep,
action_spec: types.NestedTensorSpec,
debug_summaries: bool = False,
summarize_grads_and_vars: bool = False,
train_step_counter: Optional[tf.Variable] = None,
num_outer_dims: int = 1,
name: Optional[Text] = None):
"""Creates a random agent.
Args:
time_step_spec: A `TimeStep` spec of the expected time_steps.
action_spec: A nest of BoundedTensorSpec representing the actions.
debug_summaries: A bool to gather debug summaries.
summarize_grads_and_vars: If true, gradient summaries will be written.
train_step_counter: An optional counter to increment every time the train
op is run. Defaults to the global_step.
num_outer_dims: same as base class.
name: The name of this agent. All variables in this module will fall under
that name. Defaults to the class name.
"""
tf.Module.__init__(self, name=name)
policy_class = random_tf_policy.RandomTFPolicy
super(RandomAgent, self).__init__(
time_step_spec,
action_spec,
policy_class=policy_class,
debug_summaries=debug_summaries,
summarize_grads_and_vars=summarize_grads_and_vars,
train_step_counter=train_step_counter,
num_outer_dims=num_outer_dims)
示例13: test_variables_receive_gradients
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import Variable [as 别名]
def test_variables_receive_gradients(self):
loc = tf.Variable(1., dtype=tf.float32)
log_scale = tf.Variable(0., dtype=tf.float32)
with tf.GradientTape() as tape:
dist = self.dist_cls(loc=loc, scale=tf.exp(log_scale))
x = tf.random.normal([20])
loss = -tf.reduce_mean(dist.log_prob(x))
grads = tape.gradient(loss, [loc, log_scale])
self.assertLen(grads, 2)
self.assertNotIn(None, grads)
示例14: _make_variables
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import Variable [as 别名]
def _make_variables(self):
"""Creates the variables representing the parameters of the distribution."""
channels = self.batch_shape.num_elements()
filters = (1,) + self.num_filters + (1,)
scale = self.init_scale ** (1 / (len(self.num_filters) + 1))
self._matrices = []
self._biases = []
self._factors = []
for i in range(len(self.num_filters) + 1):
init = tf.math.log(tf.math.expm1(1 / scale / filters[i + 1]))
init = tf.cast(init, dtype=self.dtype)
init = tf.broadcast_to(init, (channels, filters[i + 1], filters[i]))
matrix = tf.Variable(init, name="matrix_{}".format(i))
self._matrices.append(matrix)
bias = tf.Variable(
tf.random.uniform(
(channels, filters[i + 1], 1), -.5, .5, dtype=self.dtype),
name="bias_{}".format(i))
self._biases.append(bias)
if i < len(self.num_filters):
factor = tf.Variable(
tf.zeros((channels, filters[i + 1], 1), dtype=self.dtype),
name="factor_{}".format(i))
self._factors.append(factor)
示例15: __init__
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import Variable [as 别名]
def __init__(self, returns_dict=False):
embeddings = [
("", [0, 0, 0, 0]), # OOV items are mapped to this embedding.
("hello world", [1, 2, 3, 4]),
("pair-programming", [5, 5, 5, 5]),
]
keys = tf.constant([item[0] for item in embeddings], dtype=tf.string)
indices = tf.constant(list(range(len(embeddings))), dtype=tf.int64)
tbl_init = KeyValueTensorInitializer(keys, indices)
self.table = HashTable(tbl_init, 0)
self.weights = tf.Variable(
list([item[1] for item in embeddings]), dtype=tf.float32)
self.variables = [self.weights]
self.trainable_variables = self.variables
self._returns_dict = returns_dict