本文整理汇总了Python中tensorflow.compat.v2.constant方法的典型用法代码示例。如果您正苦于以下问题:Python v2.constant方法的具体用法?Python v2.constant怎么用?Python v2.constant使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tensorflow.compat.v2
的用法示例。
在下文中一共展示了v2.constant方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _key2seed
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import constant [as 别名]
def _key2seed(a):
"""Converts an RNG key to an RNG seed.
Args:
a: an RNG key, an ndarray of shape [] and dtype `np.int64`.
Returns:
an RNG seed, a tensor of shape [2] and dtype `tf.int32`.
"""
def int64_to_int32s(a):
"""Converts an int64 tensor of shape [] to an int32 tensor of shape [2]."""
a = tf.cast(a, tf.uint64)
fst = tf.cast(a, tf.uint32)
snd = tf.cast(
tf.bitwise.right_shift(a, tf.constant(32, tf.uint64)), tf.uint32)
a = [fst, snd]
a = tf.nest.map_structure(lambda x: tf.cast(x, tf.int32), a)
a = tf.stack(a)
return a
return int64_to_int32s(a.data)
示例2: _seed2key
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import constant [as 别名]
def _seed2key(a):
"""Converts an RNG seed to an RNG key.
Args:
a: an RNG seed, a tensor of shape [2] and dtype `tf.int32`.
Returns:
an RNG key, an ndarray of shape [] and dtype `np.int64`.
"""
def int32s_to_int64(a):
"""Converts an int32 tensor of shape [2] to an int64 tensor of shape []."""
a = tf.bitwise.bitwise_or(
tf.cast(a[0], tf.uint64),
tf.bitwise.left_shift(
tf.cast(a[1], tf.uint64), tf.constant(32, tf.uint64)))
a = tf.cast(a, tf.int64)
return a
return tf_np.asarray(int32s_to_int64(a))
示例3: tril
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import constant [as 别名]
def tril(m, k=0): # pylint: disable=missing-docstring
m = asarray(m).data
m_shape = m.shape.as_list()
if len(m_shape) < 2:
raise ValueError('Argument to tril must have rank at least 2')
if m_shape[-1] is None or m_shape[-2] is None:
raise ValueError('Currently, the last two dimensions of the input array '
'need to be known.')
z = tf.constant(0, m.dtype)
mask = tri(*m_shape[-2:], k=k, dtype=bool)
return utils.tensor_to_ndarray(
tf.where(tf.broadcast_to(mask, tf.shape(m)), m, z))
示例4: triu
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import constant [as 别名]
def triu(m, k=0): # pylint: disable=missing-docstring
m = asarray(m).data
m_shape = m.shape.as_list()
if len(m_shape) < 2:
raise ValueError('Argument to triu must have rank at least 2')
if m_shape[-1] is None or m_shape[-2] is None:
raise ValueError('Currently, the last two dimensions of the input array '
'need to be known.')
z = tf.constant(0, m.dtype)
mask = tri(*m_shape[-2:], k=k - 1, dtype=bool)
return utils.tensor_to_ndarray(
tf.where(tf.broadcast_to(mask, tf.shape(m)), z, m))
示例5: _tf_gcd
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import constant [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
示例6: argsort
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import constant [as 别名]
def argsort(a, axis=-1, kind='quicksort', order=None): # pylint: disable=missing-docstring
# TODO(nareshmodi): make string tensors also work.
if kind not in ('quicksort', 'stable'):
raise ValueError("Only 'quicksort' and 'stable' arguments are supported.")
if order is not None:
raise ValueError("'order' argument to sort is not supported.")
stable = (kind == 'stable')
a = array_ops.array(a).data
def _argsort(a, axis, stable):
if axis is None:
a = tf.reshape(a, [-1])
axis = 0
return tf.argsort(a, axis, stable=stable)
tf_ans = tf.cond(
tf.rank(a) == 0, lambda: tf.constant([0]),
lambda: _argsort(a, axis, stable))
return array_ops.array(tf_ans, dtype=np.intp)
示例7: testPad
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import constant [as 别名]
def testPad(self):
t = [[1, 2, 3], [4, 5, 6]]
paddings = [[1, 1,], [2, 2]]
self.assertAllEqual(
array_ops.pad(t, paddings, 'constant'),
[[0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 2, 3, 0, 0], [0, 0, 4, 5, 6, 0, 0],
[0, 0, 0, 0, 0, 0, 0]])
self.assertAllEqual(
array_ops.pad(t, paddings, 'reflect'),
[[6, 5, 4, 5, 6, 5, 4], [3, 2, 1, 2, 3, 2, 1], [6, 5, 4, 5, 6, 5, 4],
[3, 2, 1, 2, 3, 2, 1]])
self.assertAllEqual(
array_ops.pad(t, paddings, 'symmetric'),
[[2, 1, 1, 2, 3, 3, 2], [2, 1, 1, 2, 3, 3, 2], [5, 4, 4, 5, 6, 6, 5],
[5, 4, 4, 5, 6, 6, 5]])
示例8: testOutputIsPermutation
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import constant [as 别名]
def testOutputIsPermutation(self):
"""Checks that stateless_random_shuffle outputs a permutation."""
for dtype in (tf.int32, tf.int64, tf.float32, tf.float64):
identity_permutation = tf.range(10, dtype=dtype)
random_shuffle_seed_1 = tff_rnd.stateless_random_shuffle(
identity_permutation, seed=tf.constant((1, 42), tf.int64))
random_shuffle_seed_2 = tff_rnd.stateless_random_shuffle(
identity_permutation, seed=tf.constant((2, 42), tf.int64))
# Check that the shuffles are of the correct dtype
for shuffle in (random_shuffle_seed_1, random_shuffle_seed_2):
np.testing.assert_equal(shuffle.dtype, dtype.as_numpy_dtype)
random_shuffle_seed_1 = self.evaluate(random_shuffle_seed_1)
random_shuffle_seed_2 = self.evaluate(random_shuffle_seed_2)
identity_permutation = self.evaluate(identity_permutation)
# Check that the shuffles are different
self.assertTrue(
np.abs(random_shuffle_seed_1 - random_shuffle_seed_2).max())
# Check that the shuffles are indeed permutations
for shuffle in (random_shuffle_seed_1, random_shuffle_seed_2):
self.assertAllEqual(set(shuffle), set(identity_permutation))
示例9: testMultiDimensionalShape
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import constant [as 别名]
def testMultiDimensionalShape(self):
"""Check that stateless_random_shuffle works with multi-dim shapes."""
for dtype in (tf.int32, tf.int64, tf.float32, tf.float64):
input_permutation = tf.constant([[[1], [2], [3]], [[4], [5], [6]]],
dtype=dtype)
random_shuffle = tff_rnd.stateless_random_shuffle(
input_permutation, seed=(1, 42))
random_permutation_first_call = self.evaluate(random_shuffle)
random_permutation_next_call = self.evaluate(random_shuffle)
input_permutation = self.evaluate(input_permutation)
# Check that the dtype is correct
np.testing.assert_equal(random_permutation_first_call.dtype,
dtype.as_numpy_dtype)
# Check that the shuffles are the same
np.testing.assert_array_equal(random_permutation_first_call,
random_permutation_next_call)
# Check that the output shape is correct
np.testing.assert_equal(random_permutation_first_call.shape,
input_permutation.shape)
示例10: test_batching
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import constant [as 别名]
def test_batching(self):
x = tf.constant([[3.0, 4.0], [30.0, 40.0]])
y = tf.constant([[5.0, 6.0], [50.0, 60.0]])
z = tf.constant([[7.0, 8.0], [70.0, 80.0]])
alpha = tf.constant(2.0)
beta = tf.constant(1.0)
with tf.GradientTape(persistent=True) as tape:
tape.watch([alpha, beta])
def body(i, state):
x, y, z = state
k = tf.cast(i + 1, tf.float32)
return [x * alpha - beta, y * k * alpha * beta, z * beta + x]
out = for_loop(body, [x, y, z], [alpha, beta], 3)
with self.subTest("independent_vars"):
grad = tape.gradient(out[1], alpha)
self.assertAllEqual(8712, grad)
with self.subTest("dependent_vars"):
grad = tape.gradient(out[2], beta)
self.assertAllEqual(783, grad)
示例11: test_with_xla
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import constant [as 别名]
def test_with_xla(self):
@tf.function
def fn():
x = tf.constant([[3.0, 4.0], [30.0, 40.0]])
y = tf.constant([[7.0, 8.0], [70.0, 80.0]])
alpha = tf.constant(2.0)
beta = tf.constant(1.0)
with tf.GradientTape(persistent=True) as tape:
tape.watch([alpha, beta])
def body(i, state):
del i
x, y = state
return [x * alpha - beta, y * beta + x]
out = for_loop(body, [x, y], [alpha, beta], 3)
return tape.gradient(out[1], beta)
grad = self.evaluate(tf.xla.experimental.compile(fn))[0]
self.assertAllEqual(783, grad)
示例12: _test_batches_and_types
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import constant [as 别名]
def _test_batches_and_types(self, integrate_function, args):
"""Checks handling batches and dtypes."""
dtypes = [np.float32, np.float64, np.complex64, np.complex128]
a = [[0.0, 0.0], [0.0, 0.0]]
b = [[np.pi / 2, np.pi], [1.5 * np.pi, 2 * np.pi]]
a = [a, a]
b = [b, b]
k = tf.constant([[[[1.0]]], [[[2.0]]]])
func = lambda x: tf.cast(k, dtype=x.dtype) * tf.sin(x)
ans = [[[1.0, 2.0], [1.0, 0.0]], [[2.0, 4.0], [2.0, 0.0]]]
results = []
for dtype in dtypes:
lower = tf.constant(a, dtype=dtype)
upper = tf.constant(b, dtype=dtype)
results.append(integrate_function(func, lower, upper, **args))
results = self.evaluate(results)
for i in range(len(results)):
assert results[i].dtype == dtypes[i]
assert np.allclose(results[i], ans, atol=1e-3)
示例13: testHomogeneousBackwards
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import constant [as 别名]
def testHomogeneousBackwards(self, scheme, accuracy_order):
# Tests solving du/dt = At for a backward time step.
# Compares with exact solution u(0) = exp(-At) u(t).
time_step = 0.0001
u = tf.constant([1, 2, -1, -2], dtype=tf.float64)
matrix = tf.constant(
[[1, -1, 0, 0], [3, 1, 2, 0], [0, -2, 1, 4], [0, 0, 3, 1]],
dtype=tf.float64)
tridiag_form = self._convert_to_tridiagonal_format(matrix)
actual = self.evaluate(
scheme(u, time_step, 0, lambda t: (tridiag_form, None)))
expected = self.evaluate(
tf.squeeze(
tf.matmul(
tf.linalg.expm(-matrix * time_step), tf.expand_dims(u, 1))))
error_tolerance = 30 * time_step**(accuracy_order + 1)
self.assertLess(np.max(np.abs(actual - expected)), error_tolerance)
示例14: testInhomogeneous
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import constant [as 别名]
def testInhomogeneous(self, scheme, accuracy_order):
# Tests solving du/dt = At + b for a time step.
# Compares with exact solution u(t) = exp(At) u(0) + (exp(At) - 1) A^(-1) b.
time_step = 0.0001
u = tf.constant([1, 2, -1, -2], dtype=tf.float64)
matrix = tf.constant(
[[1, -1, 0, 0], [3, 1, 2, 0], [0, -2, 1, 4], [0, 0, 3, 1]],
dtype=tf.float64)
b = tf.constant([1, -1, -2, 2], dtype=tf.float64)
tridiag_form = self._convert_to_tridiagonal_format(matrix)
actual = self.evaluate(scheme(u, 0, time_step, lambda t: (tridiag_form, b)))
exponent = tf.linalg.expm(matrix * time_step)
eye = tf.eye(4, 4, dtype=tf.float64)
u = tf.expand_dims(u, 1)
b = tf.expand_dims(b, 1)
expected = (
tf.matmul(exponent, u) +
tf.matmul(exponent - eye, tf.matmul(tf.linalg.inv(matrix), b)))
expected = self.evaluate(tf.squeeze(expected))
error_tolerance = 30 * time_step**(accuracy_order + 1)
self.assertLess(np.max(np.abs(actual - expected)), error_tolerance)
示例15: testInhomogeneousBackwards
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import constant [as 别名]
def testInhomogeneousBackwards(self, scheme, accuracy_order):
# Tests solving du/dt = At + b for a backward time step.
# Compares with exact solution u(0) = exp(-At) u(t)
# + (exp(-At) - 1) A^(-1) b.
time_step = 0.0001
u = tf.constant([1, 2, -1, -2], dtype=tf.float64)
matrix = tf.constant(
[[1, -1, 0, 0], [3, 1, 2, 0], [0, -2, 1, 4], [0, 0, 3, 1]],
dtype=tf.float64)
b = tf.constant([1, -1, -2, 2], dtype=tf.float64)
tridiag_form = self._convert_to_tridiagonal_format(matrix)
actual = self.evaluate(scheme(u, time_step, 0, lambda t: (tridiag_form, b)))
exponent = tf.linalg.expm(-matrix * time_step)
eye = tf.eye(4, 4, dtype=tf.float64)
u = tf.expand_dims(u, 1)
b = tf.expand_dims(b, 1)
expected = (
tf.matmul(exponent, u) +
tf.matmul(exponent - eye, tf.matmul(tf.linalg.inv(matrix), b)))
expected = self.evaluate(tf.squeeze(expected))
error_tolerance = 30 * time_step**(accuracy_order + 1)
self.assertLess(np.max(np.abs(actual - expected)), error_tolerance)