本文整理汇总了Python中tensorflow.compat.v2.zeros方法的典型用法代码示例。如果您正苦于以下问题:Python v2.zeros方法的具体用法?Python v2.zeros怎么用?Python v2.zeros使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tensorflow.compat.v2
的用法示例。
在下文中一共展示了v2.zeros方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: zeros
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import zeros [as 别名]
def zeros(shape, dtype=float): # pylint: disable=redefined-outer-name
"""Returns an ndarray with the given shape and type filled with zeros.
Args:
shape: A fully defined shape. Could be - NumPy array or a python scalar,
list or tuple of integers, - TensorFlow tensor/ndarray of integer type and
rank <=1.
dtype: Optional, defaults to float. The type of the resulting ndarray. Could
be a python type, a NumPy type or a TensorFlow `DType`.
Returns:
An ndarray.
"""
if dtype:
dtype = utils.result_type(dtype)
if isinstance(shape, arrays_lib.ndarray):
shape = shape.data
return arrays_lib.tensor_to_ndarray(tf.zeros(shape, dtype=dtype))
示例2: zeros_like
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import zeros [as 别名]
def zeros_like(a, dtype=None):
"""Returns an array of zeros with the shape and type of the input array.
Args:
a: array_like. Could be an ndarray, a Tensor or any object that can be
converted to a Tensor using `tf.convert_to_tensor`.
dtype: Optional, defaults to dtype of the input array. The type of the
resulting ndarray. Could be a python type, a NumPy type or a TensorFlow
`DType`.
Returns:
An ndarray.
"""
if isinstance(a, arrays_lib.ndarray):
a = a.data
if dtype is None:
# We need to let utils.result_type decide the dtype, not tf.zeros_like
dtype = utils.result_type(a)
else:
# TF and numpy has different interpretations of Python types such as
# `float`, so we let `utils.result_type` decide.
dtype = utils.result_type(dtype)
dtype = tf.as_dtype(dtype) # Work around b/149877262
return arrays_lib.tensor_to_ndarray(tf.zeros_like(a, dtype))
示例3: tri
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import zeros [as 别名]
def tri(N, M=None, k=0, dtype=None): # pylint: disable=invalid-name,missing-docstring
M = M if M is not None else N
if dtype is not None:
dtype = utils.result_type(dtype)
else:
dtype = dtypes.default_float_type()
if k < 0:
lower = -k - 1
if lower > N:
r = tf.zeros([N, M], dtype)
else:
# Keep as tf bool, since we create an upper triangular matrix and invert
# it.
o = tf.ones([N, M], dtype=tf.bool)
r = tf.cast(tf.math.logical_not(tf.linalg.band_part(o, lower, -1)), dtype)
else:
o = tf.ones([N, M], dtype)
if k > M:
r = o
else:
r = tf.linalg.band_part(o, -1, k)
return utils.tensor_to_ndarray(r)
示例4: _tf_gcd
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import zeros [as 别名]
def _tf_gcd(x1, x2):
def _gcd_cond_fn(x1, x2):
return tf.reduce_any(x2 != 0)
def _gcd_body_fn(x1, x2):
# tf.math.mod will raise an error when any element of x2 is 0. To avoid
# that, we change those zeros to ones. Their values don't matter because
# they won't be used.
x2_safe = tf.where(x2 != 0, x2, tf.constant(1, x2.dtype))
x1, x2 = (tf.where(x2 != 0, x2, x1),
tf.where(x2 != 0, tf.math.mod(x1, x2_safe),
tf.constant(0, x2.dtype)))
return (tf.where(x1 < x2, x2, x1), tf.where(x1 < x2, x1, x2))
if (not np.issubdtype(x1.dtype.as_numpy_dtype, np.integer) or
not np.issubdtype(x2.dtype.as_numpy_dtype, np.integer)):
raise ValueError("Arguments to gcd must be integers.")
shape = tf.broadcast_static_shape(x1.shape, x2.shape)
x1 = tf.broadcast_to(x1, shape)
x2 = tf.broadcast_to(x2, shape)
gcd, _ = tf.while_loop(_gcd_cond_fn, _gcd_body_fn,
(tf.math.abs(x1), tf.math.abs(x2)))
return gcd
示例5: test_forward_unconnected_gradient
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import zeros [as 别名]
def test_forward_unconnected_gradient(self):
t = tf.range(1, 3, dtype=tf.float32) # Shape [2]
zeros = tf.zeros([2], dtype=t.dtype)
func = lambda t: tf.stack([zeros, zeros, zeros], axis=0) # Shape [3, 2]
expected_result = [[0.0, 0.0], [0.0, 0.0], [0.0, 0.0]]
with self.subTest("EagerExecution"):
fwd_grad = self.evaluate(tff.math.fwd_gradient(
func, t, unconnected_gradients=tf.UnconnectedGradients.ZERO))
self.assertEqual(fwd_grad.shape, (3, 2))
np.testing.assert_allclose(fwd_grad, expected_result)
with self.subTest("GraphExecution"):
@tf.function
def grad_computation():
y = func(t)
return tff.math.fwd_gradient(
y, t, unconnected_gradients=tf.UnconnectedGradients.ZERO)
fwd_grad = self.evaluate(grad_computation())
self.assertEqual(fwd_grad.shape, (3, 2))
np.testing.assert_allclose(fwd_grad, expected_result)
示例6: test_backward_unconnected_gradient
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import zeros [as 别名]
def test_backward_unconnected_gradient(self):
t = tf.range(1, 3, dtype=tf.float32) # Shape [2]
zeros = tf.zeros([2], dtype=t.dtype)
expected_result = [0.0, 0.0]
func = lambda t: tf.stack([zeros, zeros, zeros], axis=0) # Shape [3, 2]
with self.subTest("EagerExecution"):
backward_grad = self.evaluate(tff.math.gradients(
func, t, unconnected_gradients=tf.UnconnectedGradients.ZERO))
self.assertEqual(backward_grad.shape, (2,))
np.testing.assert_allclose(backward_grad, expected_result)
with self.subTest("GraphExecution"):
@tf.function
def grad_computation():
y = func(t)
return tff.math.gradients(
y, t, unconnected_gradients=tf.UnconnectedGradients.ZERO)
backward_grad = self.evaluate(grad_computation())
self.assertEqual(backward_grad.shape, (2,))
np.testing.assert_allclose(backward_grad, expected_result)
示例7: _make_unit_jacobian
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import zeros [as 别名]
def _make_unit_jacobian(initial_state, params):
"""Creates a unit Jacobian matrix."""
n = len(initial_state)
d = [initial_state[i].shape.as_list()[-1] for i in range(n)]
if None in d:
raise ValueError("Last dimensions of initial_state Tensors must be known.")
p = len(params)
dtype = initial_state[0].dtype
def make_js_block(i, j):
shape = initial_state[i].shape.concatenate((d[j],))
if i != j:
return tf.zeros(shape, dtype=dtype)
eye = tf.eye(d[i], dtype=dtype)
return tf.broadcast_to(eye, shape)
def make_jp_block(i, j):
del j
shape = initial_state[i].shape.concatenate((1,))
return tf.zeros(shape, dtype=dtype)
js = [[make_js_block(i, j) for j in range(n)] for i in range(n)]
jp = [[make_jp_block(i, j) for j in range(p)] for i in range(n)]
return js, jp
示例8: _updated_cashflow
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import zeros [as 别名]
def _updated_cashflow(num_times, exercise_index, exercise_value,
expected_continuation, cashflow):
"""Revises the cashflow tensor where options will be exercised earlier."""
do_exercise_bool = exercise_value > expected_continuation
do_exercise = tf.cast(do_exercise_bool, exercise_value.dtype)
# Shape [num_samples, payoff_dim]
scaled_do_exercise = tf.where(do_exercise_bool, exercise_value,
tf.zeros_like(exercise_value))
# This picks out the samples where we now wish to exercise.
# Shape [num_samples, payoff_dim, 1]
new_samp_masked = tf.expand_dims(scaled_do_exercise, axis=2)
# This should be one on the current time step and zero otherwise.
# This is an array with nonzero entries showing newly exercised payoffs.
zeros = tf.zeros_like(cashflow)
mask = tf.equal(tf.range(0, num_times), exercise_index - 1)
new_cash = tf.where(mask, new_samp_masked, zeros)
# Has shape [num_samples, payoff_dim, 1]
old_mask = tf.expand_dims(1 - do_exercise, axis=2)
mask = tf.range(0, num_times) >= exercise_index
old_mask = tf.where(mask, old_mask, zeros)
# Shape [num_samples, payoff_dim, num_times]
old_cash = old_mask * cashflow
return new_cash + old_cash
示例9: test_maybe_update_along_axis
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import zeros [as 别名]
def test_maybe_update_along_axis(self, dtype):
"""Tests that the values are updated correctly."""
tensor = tf.ones([5, 4, 3, 2], dtype=dtype)
new_tensor = tf.zeros([5, 4, 1, 2], dtype=dtype)
@tf.function
def maybe_update_along_axis(do_update):
return utils.maybe_update_along_axis(
tensor=tensor, new_tensor=new_tensor, axis=1, ind=2,
do_update=do_update)
updated_tensor = maybe_update_along_axis(True)
with self.subTest(name='Shape'):
self.assertEqual(updated_tensor.shape, tensor.shape)
with self.subTest(name='UpdatedVals'):
self.assertAllEqual(updated_tensor[:, 2, :, :],
tf.zeros_like(updated_tensor[:, 2, :, :]))
with self.subTest(name='NotUpdatedVals'):
self.assertAllEqual(updated_tensor[:, 1, :, :],
tf.ones_like(updated_tensor[:, 2, :, :]))
with self.subTest(name='DoNotUpdateVals'):
not_updated_tensor = maybe_update_along_axis(False)
self.assertAllEqual(not_updated_tensor, tensor)
示例10: _exact_discretization_setup
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import zeros [as 别名]
def _exact_discretization_setup(self, dim):
"""Initial setup for efficient computations."""
self._zero_padding = tf.zeros((dim, 1), dtype=self._dtype)
self._jump_locations = tf.concat(
[self._volatility.jump_locations(),
self._mean_reversion.jump_locations()], axis=-1)
self._jump_values_vol = self._volatility(self._jump_locations)
self._jump_values_mr = self._mean_reversion(self._jump_locations)
if dim == 1:
self._padded_knots = tf.concat([
self._zero_padding,
tf.expand_dims(self._jump_locations[:-1], axis=0)
], axis=1)
self._jump_values_vol = tf.expand_dims(self._jump_values_vol, axis=0)
self._jump_values_mr = tf.expand_dims(self._jump_values_mr, axis=0)
self._jump_locations = tf.expand_dims(self._jump_locations, axis=0)
else:
self._padded_knots = tf.concat(
[self._zero_padding, self._jump_locations[:, :-1]], axis=1)
示例11: from_config
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import zeros [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
示例12: _get_initial_state
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import zeros [as 别名]
def _get_initial_state(self, observation, batch_size):
text_token_ids = observation[constants.INS_TOKEN_IDS]
text_enc_outputs, final_state = self._instruction_encoder(text_token_ids)
if self._ndh_instruction_encoder is not None:
ndh_text_enc_outputs, ndh_final_state = self._ndh_instruction_encoder(
text_token_ids)
mask = tf.equal(observation[constants.PROBLEM_TYPE],
constants.PROBLEM_VLN)
text_enc_outputs = tf.nest.map_structure(
lambda x, y: tf.compat.v1.where(mask, x, y), text_enc_outputs,
ndh_text_enc_outputs)
final_state = tf.nest.map_structure(
lambda x, y: tf.compat.v1.where(mask, x, y), final_state,
ndh_final_state)
if self._ins_classifier is not None:
# Concatenate all hidden layers' state vectors. Use state.h
ins_classifier_logits = self._ins_classifier(
tf.concat([s[0] for s in final_state], axis=1))
else:
ins_classifier_logits = tf.zeros(shape=(batch_size, 2))
return (final_state, text_enc_outputs, ins_classifier_logits)
示例13: testBatchApply
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import zeros [as 别名]
def testBatchApply(self):
time_dim = 4
batch_dim = 5
inputs = {
'a': tf.zeros(shape=(time_dim, batch_dim)),
'b': {
'b_1': tf.ones(shape=(time_dim, batch_dim, 9, 10)),
'b_2': tf.ones(shape=(time_dim, batch_dim, 6)),
}
}
def f(tensors):
np.testing.assert_array_almost_equal(
np.zeros(shape=(time_dim * batch_dim)), tensors['a'].numpy())
np.testing.assert_array_almost_equal(
np.ones(shape=(time_dim * batch_dim, 9, 10)),
tensors['b']['b_1'].numpy())
np.testing.assert_array_almost_equal(
np.ones(shape=(time_dim * batch_dim, 6)), tensors['b']['b_2'].numpy())
return tf.ones(shape=(time_dim * batch_dim, 2))
result = utils.batch_apply(f, inputs)
np.testing.assert_array_almost_equal(
np.ones(shape=(time_dim, batch_dim, 2)), result.numpy())
示例14: _neck
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import zeros [as 别名]
def _neck(self, torso_output, state):
# Verify state. It could have been reset if done was true.
expected_state = np.copy(self._current_state.numpy())
done = self._done[self._timestep]
for i, d in enumerate(done):
if d:
expected_state[i] = np.zeros(self._init_state_size)
np.testing.assert_array_almost_equal(expected_state, state.numpy())
# Verify torso_output
expected_torso_output = np.concatenate([
np.ones(shape=(self._batch_size, 50)),
np.zeros(shape=(self._batch_size, 50))
],
axis=1)
np.testing.assert_array_almost_equal(expected_torso_output,
torso_output.numpy())
self._timestep += 1
self._current_state = state + 1
return (tf.ones([self._batch_size, 6]) * self._timestep,
self._current_state)
示例15: empty
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import zeros [as 别名]
def empty(shape, dtype=float): # pylint: disable=redefined-outer-name
"""Returns an empty array with the specified shape and dtype.
Args:
shape: A fully defined shape. Could be - NumPy array or a python scalar,
list or tuple of integers, - TensorFlow tensor/ndarray of integer type and
rank <=1.
dtype: Optional, defaults to float. The type of the resulting ndarray. Could
be a python type, a NumPy type or a TensorFlow `DType`.
Returns:
An ndarray.
"""
return zeros(shape, dtype)