本文整理汇总了Python中tensorflow.compat.v2.executing_eagerly方法的典型用法代码示例。如果您正苦于以下问题:Python v2.executing_eagerly方法的具体用法?Python v2.executing_eagerly怎么用?Python v2.executing_eagerly使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tensorflow.compat.v2
的用法示例。
在下文中一共展示了v2.executing_eagerly方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_dynamic_shapes
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import executing_eagerly [as 别名]
def test_dynamic_shapes(self):
"""Can build op with dynamic shapes in graph mode."""
if tf.executing_eagerly():
return
minimum = np.array([1.0, 1.0])
scales = np.array([2.0, 3.0])
@tff.math.make_val_and_grad_fn
def quadratic(x):
return tf.reduce_sum(input_tensor=scales * (x - minimum)**2)
# Test with a vector of unknown dimension.
start = tf.compat.v1.placeholder(tf.float32, shape=[None])
op = tff.math.optimizer.conjugate_gradient_minimize(
quadratic, initial_position=start, tolerance=1e-8)
self.assertFalse(op.position.shape.is_fully_defined())
with self.cached_session() as session:
results = session.run(op, feed_dict={start: [0.6, 0.8]})
self.assertTrue(results.converged)
self.assertLessEqual(_norm(results.objective_gradient), 1e-8)
self.assertArrayNear(results.position, minimum, 1e-5)
示例2: test_run_in_graph_and_eager_modes
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import executing_eagerly [as 别名]
def test_run_in_graph_and_eager_modes(self):
l = []
def inc(self, with_brackets):
del self # self argument is required by run_in_graph_and_eager_modes.
mode = 'eager' if tf.executing_eagerly() else 'graph'
with_brackets = 'with_brackets' if with_brackets else 'without_brackets'
l.append((with_brackets, mode))
f = test_utils.run_in_graph_and_eager_modes(inc)
f(self, with_brackets=False)
f = test_utils.run_in_graph_and_eager_modes()(inc)
f(self, with_brackets=True)
self.assertEqual(len(l), 4)
self.assertEqual(set(l), {
('with_brackets', 'graph'),
('with_brackets', 'eager'),
('without_brackets', 'graph'),
('without_brackets', 'eager'),
})
示例3: test_run_in_graph_and_eager_modes_setup_in_same_mode
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import executing_eagerly [as 别名]
def test_run_in_graph_and_eager_modes_setup_in_same_mode(self):
modes = []
mode_name = lambda: 'eager' if tf.executing_eagerly() else 'graph'
class ExampleTest(test_case.TestCase):
def runTest(self):
pass
def setUp(self):
super(ExampleTest, self).setUp()
modes.append('setup_' + mode_name())
@test_utils.run_in_graph_and_eager_modes
def testBody(self):
modes.append('run_' + mode_name())
e = ExampleTest()
e.setUp()
e.testBody()
self.assertEqual(modes[0:2], ['setup_eager', 'run_eager'])
self.assertEqual(modes[2:], ['setup_graph', 'run_graph'])
示例4: test_compute_distance_matrix_loo
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import executing_eagerly [as 别名]
def test_compute_distance_matrix_loo(self):
if not tf.executing_eagerly():
self.skipTest("Test requires eager mode.")
np.random.seed(seed=self.random_seed)
x_train = np.random.rand(self.train_samples, self.dim)
d = utils.compute_distance_matrix_loo(x_train)
self.assertEqual(d.shape, (self.train_samples, self.train_samples))
for i in range(self.train_samples):
for j in range(self.train_samples):
if i == j:
self.assertEqual(float("inf"), d[i, j])
else:
d_ij = np.linalg.norm(x_train[j, :] - x_train[i, :])**2
self.assertAlmostEqual(d_ij, d[i, j], places=5)
示例5: test_compute_distance_matrix_loo_cosine
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import executing_eagerly [as 别名]
def test_compute_distance_matrix_loo_cosine(self):
if not tf.executing_eagerly():
self.skipTest("Test requires eager mode.")
np.random.seed(seed=self.random_seed)
x_train = np.random.rand(self.train_samples, self.dim)
d = utils.compute_distance_matrix_loo(x_train, measure="cosine")
self.assertEqual(d.shape, (self.train_samples, self.train_samples))
for i in range(self.train_samples):
for j in range(self.train_samples):
if i == j:
self.assertEqual(float("inf"), d[i, j])
else:
d_ij = spdist.cosine(x_train[i, :], x_train[j, :])
self.assertAlmostEqual(d_ij, d[i, j], places=5)
示例6: knn_errorrate
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import executing_eagerly [as 别名]
def knn_errorrate(self, k):
if not tf.executing_eagerly():
self.skipTest("Test requires eager mode.")
x_train = np.random.rand(self.train_samples, self.dim)
x_test = np.random.rand(self.test_samples, self.dim)
d = utils.compute_distance_matrix(x_train, x_test)
y_test = np.random.randint(self.classes, size=self.test_samples)
y_train = np.random.randint(self.classes, size=self.train_samples)
err = utils.knn_errorrate(d, y_train, y_test, k=k)
knn = KNeighborsClassifier(n_neighbors=k)
knn.fit(x_train, y_train)
y_pred = knn.predict(x_test)
acc = metrics.accuracy_score(y_test, y_pred)
self.assertAlmostEqual(1.0 - err, acc, places=5)
示例7: test_knn_errorrate_multik
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import executing_eagerly [as 别名]
def test_knn_errorrate_multik(self):
if not tf.executing_eagerly():
self.skipTest("Test requires eager mode.")
np.random.seed(seed=self.random_seed)
x_train = np.random.rand(self.train_samples, self.dim)
x_test = np.random.rand(self.test_samples, self.dim)
d = utils.compute_distance_matrix(x_train, x_test)
y_test = np.random.randint(self.classes, size=self.test_samples)
y_train = np.random.randint(self.classes, size=self.train_samples)
ks_input = [5, 1, 5, 3]
ks = [5,3,1]
vals = []
for val in ks:
err = utils.knn_errorrate(d, y_train, y_test, k=val)
vals.append(err)
comp = utils.knn_errorrate(d, y_train, y_test, k=ks_input)
self.assertEqual(len(vals), len(comp))
for k, v in enumerate(comp):
self.assertAlmostEqual(v, vals[k], places=5)
示例8: knn_errorrate_loo
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import executing_eagerly [as 别名]
def knn_errorrate_loo(self, k):
if not tf.executing_eagerly():
self.skipTest("Test requires eager mode.")
x_train = np.random.rand(self.train_samples, self.dim)
d = utils.compute_distance_matrix_loo(x_train)
y_train = np.random.randint(self.classes, size=self.train_samples)
err = utils.knn_errorrate_loo(d, y_train, k=k)
cnt = 0.0
for i in range(self.train_samples):
knn = KNeighborsClassifier(n_neighbors=k)
mask = [True]*self.train_samples
mask[i] = False
knn.fit(x_train[mask], y_train[mask])
y_pred = knn.predict(x_train[i].reshape(-1, self.dim))
if y_pred != y_train[i]:
cnt += 1
self.assertAlmostEqual(err, cnt / self.train_samples, places=5)
示例9: test_knn_errorrate_loo_multik
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import executing_eagerly [as 别名]
def test_knn_errorrate_loo_multik(self):
if not tf.executing_eagerly():
self.skipTest("Test requires eager mode.")
np.random.seed(seed=self.random_seed)
x_train = np.random.rand(self.train_samples, self.dim)
d = utils.compute_distance_matrix_loo(x_train)
y_train = np.random.randint(self.classes, size=self.train_samples)
ks_input = [5, 1, 5, 3]
ks = [5,3,1]
vals = []
for val in ks:
err = utils.knn_errorrate_loo(d, y_train, k=val)
vals.append(err)
comp = utils.knn_errorrate_loo(d, y_train, k=ks_input)
self.assertEqual(len(vals), len(comp))
for k, v in enumerate(comp):
self.assertAlmostEqual(v, vals[k], places=5)
示例10: generate_preset_test_rotation_matrices_3d
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import executing_eagerly [as 别名]
def generate_preset_test_rotation_matrices_3d():
"""Generates pre-set test 3d rotation matrices."""
angles = generate_preset_test_euler_angles()
preset_rotation_matrix = rotation_matrix_3d.from_euler(angles)
if tf.executing_eagerly():
return np.array(preset_rotation_matrix)
with tf.compat.v1.Session() as sess:
return np.array(sess.run([preset_rotation_matrix]))
示例11: generate_preset_test_rotation_matrices_2d
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import executing_eagerly [as 别名]
def generate_preset_test_rotation_matrices_2d():
"""Generates pre-set test 2d rotation matrices."""
angles = generate_preset_test_euler_angles(dimensions=1)
preset_rotation_matrix = rotation_matrix_2d.from_euler(angles)
if tf.executing_eagerly():
return np.array(preset_rotation_matrix)
with tf.compat.v1.Session() as sess:
return np.array(sess.run([preset_rotation_matrix]))
示例12: generate_preset_test_axis_angle
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import executing_eagerly [as 别名]
def generate_preset_test_axis_angle():
"""Generates pre-set test rotation matrices."""
angles = generate_preset_test_euler_angles()
axis, angle = axis_angle.from_euler(angles)
if tf.executing_eagerly():
return np.array(axis), np.array(angle)
with tf.compat.v1.Session() as sess:
return np.array(sess.run([axis])), np.array(sess.run([angle]))
示例13: generate_preset_test_quaternions
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import executing_eagerly [as 别名]
def generate_preset_test_quaternions():
"""Generates pre-set test quaternions."""
angles = generate_preset_test_euler_angles()
preset_quaternion = quaternion.from_euler(angles)
if tf.executing_eagerly():
return np.array(preset_quaternion)
with tf.compat.v1.Session() as sess:
return np.array(sess.run([preset_quaternion]))
示例14: test_valid_gradients
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import executing_eagerly [as 别名]
def test_valid_gradients(self, optimize_for_tpu):
"""Tests none of the gradients is nan."""
# In this example, `x[0]` and `x[1]` are both less than or equal to
# `x_data[0]`. `x[-2]` and `x[-1]` are both greater than or equal to
# `x_data[-1]`. They are set up this way to test none of the tf.where
# branches of the implementation have any nan. An unselected nan could still
# propagate through gradient calculation with the end result being nan.
x = [[-10.0, -1.0, 1.0, 3.0, 6.0, 7.0], [8.0, 15.0, 18.0, 25.0, 30.0, 35.0]]
x_data = [[-1.0, 2.0, 6.0], [8.0, 18.0, 30.0]]
def _value_helper_fn(y_data):
"""A helper function that returns sum of squared interplated values."""
interpolated_values = tff.math.interpolation.linear.interpolate(
x, x_data, y_data,
optimize_for_tpu=optimize_for_tpu,
dtype=tf.float64)
return tf.reduce_sum(tf.math.square(interpolated_values))
y_data = tf.convert_to_tensor([[10.0, -1.0, -5.0], [7.0, 9.0, 20.0]],
dtype=tf.float64)
if tf.executing_eagerly():
with tf.GradientTape(watch_accessed_variables=False) as tape:
tape.watch(y_data)
value = _value_helper_fn(y_data=y_data)
gradients = tape.gradient(value, y_data)
else:
value = _value_helper_fn(y_data=y_data)
gradients = tf.gradients(value, y_data)[0]
gradients = tf.convert_to_tensor(gradients)
self.assertFalse(self.evaluate(tf.reduce_any(tf.math.is_nan(gradients))))
示例15: __repr__
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import executing_eagerly [as 别名]
def __repr__(self):
output = "PeriodTensor: shape={}".format(self.shape)
if tf.executing_eagerly():
return output + ", quantities={}".format(repr(self._quantity.numpy()))
return output