本文整理汇总了Python中tensorflow.compat.v1.Graph方法的典型用法代码示例。如果您正苦于以下问题:Python v1.Graph方法的具体用法?Python v1.Graph怎么用?Python v1.Graph使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tensorflow.compat.v1
的用法示例。
在下文中一共展示了v1.Graph方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _load_frozen_graph
# 需要导入模块: from tensorflow.compat import v1 [as 别名]
# 或者: from tensorflow.compat.v1 import Graph [as 别名]
def _load_frozen_graph(self, frozen_graph_path):
frozen_graph = tf.GraphDef()
with open(frozen_graph_path, 'rb') as f:
frozen_graph.ParseFromString(f.read())
self.graph = tf.Graph()
with self.graph.as_default():
self.output_node = tf.import_graph_def(
frozen_graph, return_elements=[
'probabilities:0',
])
self.session = tf.InteractiveSession(graph=self.graph)
tf_probabilities = self.graph.get_tensor_by_name('import/probabilities:0')
self._output_nodes = [tf_probabilities]
self.sliding_window = None
self.frames_since_last_inference = self.config.inference_rate
self.last_annotations = []
示例2: _benchmark_train
# 需要导入模块: from tensorflow.compat import v1 [as 别名]
# 或者: from tensorflow.compat.v1 import Graph [as 别名]
def _benchmark_train(self):
"""Run cnn in benchmark mode. Skip the backward pass if forward_only is on.
Returns:
Dictionary containing training statistics (num_workers, num_steps,
average_wall_time, images_per_sec).
"""
graph = tf.Graph()
with graph.as_default():
build_result = self._build_graph()
if self.mode == constants.BenchmarkMode.TRAIN_AND_EVAL:
with self.variable_mgr.reuse_variables():
with tf.name_scope('Evaluation') as ns:
eval_build_results = self._build_eval_graph(ns)
else:
eval_build_results = None
(graph, result_to_benchmark) = self._preprocess_graph(graph, build_result)
with graph.as_default():
return self._benchmark_graph(result_to_benchmark, eval_build_results)
示例3: evaluate
# 需要导入模块: from tensorflow.compat import v1 [as 别名]
# 或者: from tensorflow.compat.v1 import Graph [as 别名]
def evaluate(self, env_fn, hparams, sampling_temp):
with tf.Graph().as_default():
with tf.name_scope("rl_eval"):
eval_env = env_fn(in_graph=True)
(collect_memory, _, collect_init) = _define_collect(
eval_env,
hparams,
"ppo_eval",
eval_phase=True,
frame_stack_size=self.frame_stack_size,
force_beginning_resets=False,
sampling_temp=sampling_temp,
distributional_size=self._distributional_size,
)
model_saver = tf.train.Saver(
tf.global_variables(hparams.policy_network + "/.*")
# tf.global_variables("clean_scope.*") # Needed for sharing params.
)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
collect_init(sess)
trainer_lib.restore_checkpoint(self.agent_model_dir, model_saver,
sess)
sess.run(collect_memory)
示例4: __init__
# 需要导入模块: from tensorflow.compat import v1 [as 别名]
# 或者: from tensorflow.compat.v1 import Graph [as 别名]
def __init__(self, hparams, action_space, observation_space, policy_dir):
assert hparams.base_algo == "ppo"
ppo_hparams = trainer_lib.create_hparams(hparams.base_algo_params)
frame_stack_shape = (1, hparams.frame_stack_size) + observation_space.shape
self._frame_stack = np.zeros(frame_stack_shape, dtype=np.uint8)
with tf.Graph().as_default():
self.obs_t = tf.placeholder(shape=self.frame_stack_shape, dtype=np.uint8)
self.logits_t, self.value_function_t = get_policy(
self.obs_t, ppo_hparams, action_space
)
model_saver = tf.train.Saver(
tf.global_variables(scope=ppo_hparams.policy_network + "/.*") # pylint: disable=unexpected-keyword-arg
)
self.sess = tf.Session()
self.sess.run(tf.global_variables_initializer())
trainer_lib.restore_checkpoint(policy_dir, model_saver,
self.sess)
示例5: __init__
# 需要导入模块: from tensorflow.compat import v1 [as 别名]
# 或者: from tensorflow.compat.v1 import Graph [as 别名]
def __init__(
self, batch_size, observation_space, action_space, policy_hparams,
policy_dir, sampling_temp
):
super(PolicyAgent, self).__init__(
batch_size, observation_space, action_space
)
self._sampling_temp = sampling_temp
with tf.Graph().as_default():
self._observations_t = tf.placeholder(
shape=((batch_size,) + self.observation_space.shape),
dtype=self.observation_space.dtype
)
(logits, self._values_t) = rl.get_policy(
self._observations_t, policy_hparams, self.action_space
)
actions = common_layers.sample_with_temperature(logits, sampling_temp)
self._probs_t = tf.nn.softmax(logits / sampling_temp)
self._actions_t = tf.cast(actions, tf.int32)
model_saver = tf.train.Saver(
tf.global_variables(policy_hparams.policy_network + "/.*") # pylint: disable=unexpected-keyword-arg
)
self._sess = tf.Session()
self._sess.run(tf.global_variables_initializer())
trainer_lib.restore_checkpoint(policy_dir, model_saver, self._sess)
示例6: run_in_graph_mode_only
# 需要导入模块: from tensorflow.compat import v1 [as 别名]
# 或者: from tensorflow.compat.v1 import Graph [as 别名]
def run_in_graph_mode_only(func=None, config=None, use_gpu=True):
"""Runs a test in graph mode only, when eager is enabled by default."""
def decorator(f):
"""Decorator for a method."""
def decorated(self, *args, **kwargs):
"""Run the decorated test method."""
self.tearDown()
# Run in graph mode block
with tf.Graph().as_default():
self.setUp()
with self.test_session(use_gpu=use_gpu, config=config):
f(self, *args, **kwargs)
return decorated
if func is not None:
return decorator(func)
return decorator
示例7: test_invertibility
# 需要导入模块: from tensorflow.compat import v1 [as 别名]
# 或者: from tensorflow.compat.v1 import Graph [as 别名]
def test_invertibility(self, op, name, dropout=0.0):
with tf.Graph().as_default():
tf.set_random_seed(42)
x = tf.random_uniform(shape=(16, 32, 32, 4))
if op in [glow_ops.affine_coupling, glow_ops.additive_coupling]:
with arg_scope([glow_ops.get_dropout], init=False):
x_inv, _ = op(name, x, reverse=False, dropout=dropout)
x_inv_inv, _ = op(name, x_inv, reverse=True, dropout=dropout)
else:
x_inv, _ = op(name, x, reverse=False)
x_inv_inv, _ = op(name, x_inv, reverse=True)
with tf.Session() as session:
session.run(tf.global_variables_initializer())
diff = session.run(x - x_inv_inv)
self.assertTrue(np.allclose(diff, 0.0, atol=1e-5))
示例8: test_conv2d
# 需要导入模块: from tensorflow.compat import v1 [as 别名]
# 或者: from tensorflow.compat.v1 import Graph [as 别名]
def test_conv2d(self):
with tf.Graph().as_default():
x = 10.0 * tf.random_uniform(shape=(16, 5, 5, 32))
with arg_scope([glow_ops.actnorm], init=True):
actnorm_conv2d = glow_ops.conv(
"actnorm_conv2d", x, output_channels=64, apply_actnorm=True)
actnorm_zeros2d = glow_ops.conv(
"actnorm_zeros2d", x, output_channels=64, apply_actnorm=False)
with tf.Session() as session:
session.run(tf.global_variables_initializer())
# test if apply_actnorm is set to True, the first minibatch has
# zero mean and unit variance.
actnorm_np, zeros_np = session.run([actnorm_conv2d, actnorm_zeros2d])
self.assertEqual(actnorm_np.shape, (16, 5, 5, 64))
mean = np.mean(actnorm_np, axis=(0, 1, 2))
var = np.var(actnorm_np, axis=(0, 1, 2))
self.assertTrue(np.allclose(mean, 0.0, atol=1e-5))
self.assertTrue(np.allclose(var, 1.0, atol=1e-5))
# test shape in case apply_actnorm is set to False,
self.assertEqual(zeros_np.shape, (16, 5, 5, 64))
示例9: test_temporal_latent_to_dist
# 需要导入模块: from tensorflow.compat import v1 [as 别名]
# 或者: from tensorflow.compat.v1 import Graph [as 别名]
def test_temporal_latent_to_dist(self, apply_dilation, activation,
dropout=0.0, noise=0.1, num_steps=5):
with tf.Graph().as_default():
hparams = self.get_glow_hparams()
hparams.latent_apply_dilations = apply_dilation
hparams.latent_activation = activation
hparams.latent_dropout = dropout
hparams.latent_noise = noise
latent_shape = (16, num_steps, 32, 32, 48)
latents = tf.random_normal(latent_shape)
dist = glow_ops.temporal_latent_to_dist(
"tensor_to_dist", latents, hparams)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
# dilated conv_3d is not available on CPU.
is_gpu = tf.test.is_gpu_available()
if not apply_dilation or is_gpu:
mean, scale = dist.loc, dist.scale
mean_np, scale_np = sess.run([mean, scale])
self.assertTrue(np.allclose(mean_np, 0.0))
self.assertTrue(np.allclose(scale_np, 1.0))
示例10: linear_interpolate_rank
# 需要导入模块: from tensorflow.compat import v1 [as 别名]
# 或者: from tensorflow.compat.v1 import Graph [as 别名]
def linear_interpolate_rank(self):
with tf.Graph().as_default():
# Since rank is 1, the first channel should remain 1.0.
# and the second channel should be interpolated between 1.0 and 6.0
z1 = np.ones(shape=(4, 4, 2))
z2 = np.copy(z1)
z2[:, :, 0] += 0.01
z2[:, :, 1] += 5.0
coeffs = np.linspace(0.0, 1.0, 11)
z1 = np.expand_dims(z1, axis=0)
z2 = np.expand_dims(z2, axis=0)
tensor1 = tf.convert_to_tensor(z1, dtype=tf.float32)
tensor2 = tf.convert_to_tensor(z2, dtype=tf.float32)
lin_interp_max = glow_ops.linear_interpolate_rank(
tensor1, tensor2, coeffs)
with tf.Session() as sess:
lin_interp_np_max = sess.run(lin_interp_max)
for lin_interp_np, coeff in zip(lin_interp_np_max, coeffs):
exp_val = 1.0 + coeff * (6.0 - 1.0)
self.assertTrue(np.allclose(lin_interp_np[:, :, 0], 1.0))
self.assertTrue(np.allclose(lin_interp_np[:, :, 1], exp_val))
示例11: testVarNames
# 需要导入模块: from tensorflow.compat import v1 [as 别名]
# 或者: from tensorflow.compat.v1 import Graph [as 别名]
def testVarNames(self):
with tf.Graph().as_default():
model, features = get_model(
mode=tf.estimator.ModeKeys.PREDICT,
model_cls=transformer.TransformerScorer)
_ = model.infer(features)
scorer_vars = [v.name for v in tf.global_variables()]
with tf.Graph().as_default():
model, features = get_model(
mode=tf.estimator.ModeKeys.EVAL,
model_cls=transformer.TransformerScorer)
_ = model(features)
scorer_eval_vars = [v.name for v in tf.global_variables()]
with tf.Graph().as_default():
model, features = get_model(
mode=tf.estimator.ModeKeys.EVAL,
model_cls=transformer.Transformer)
_ = model(features)
transformer_vars = [v.name for v in tf.global_variables()]
self.assertEqual(sorted(scorer_vars), sorted(transformer_vars))
self.assertEqual(sorted(scorer_eval_vars), sorted(transformer_vars))
示例12: testSpectralNorm
# 需要导入模块: from tensorflow.compat import v1 [as 别名]
# 或者: from tensorflow.compat.v1 import Graph [as 别名]
def testSpectralNorm(self):
# Test that after 20 calls to apply_spectral_norm, the spectral
# norm of the normalized matrix is close to 1.0
with tf.Graph().as_default():
weights = tf.get_variable("w", dtype=tf.float32, shape=[2, 3, 50, 100])
weights = tf.multiply(weights, 10.0)
normed_weight, assign_op = common_layers.apply_spectral_norm(weights)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for _ in range(20):
sess.run(assign_op)
normed_weight, assign_op = common_layers.apply_spectral_norm(
weights)
normed_weight = sess.run(normed_weight).reshape(-1, 100)
_, s, _ = np.linalg.svd(normed_weight)
self.assertTrue(np.allclose(s[0], 1.0, rtol=0.1))
示例13: __init__
# 需要导入模块: from tensorflow.compat import v1 [as 别名]
# 或者: from tensorflow.compat.v1 import Graph [as 别名]
def __init__(self, batch_size, *args, **kwargs):
self._store_rollouts = kwargs.pop("store_rollouts", True)
super(T2TEnv, self).__init__(*args, **kwargs)
self.batch_size = batch_size
self._rollouts_by_epoch_and_split = collections.OrderedDict()
self.current_epoch = None
self._should_preprocess_on_reset = True
with tf.Graph().as_default() as tf_graph:
self._tf_graph = _Noncopyable(tf_graph)
self._decoded_image_p = _Noncopyable(
tf.placeholder(dtype=tf.uint8, shape=(None, None, None))
)
self._encoded_image_t = _Noncopyable(
tf.image.encode_png(self._decoded_image_p.obj)
)
self._encoded_image_p = _Noncopyable(tf.placeholder(tf.string))
self._decoded_image_t = _Noncopyable(
tf.image.decode_png(self._encoded_image_p.obj)
)
self._session = _Noncopyable(tf.Session())
示例14: generate_samples
# 需要导入模块: from tensorflow.compat import v1 [as 别名]
# 或者: from tensorflow.compat.v1 import Graph [as 别名]
def generate_samples(self, data_dir, tmp_dir, dataset_split):
with tf.Graph().as_default():
# train and eval set are generated on-the-fly.
# test set is the official test-set.
if dataset_split == problem.DatasetSplit.TEST:
moving_ds = self.get_test_iterator(tmp_dir)
else:
moving_ds = self.get_train_iterator()
next_video = moving_ds.get_next()
with tf.Session() as sess:
sess.run(moving_ds.initializer)
n_samples = SPLIT_TO_SIZE[dataset_split]
for _ in range(n_samples):
next_video_np = sess.run(next_video)
for frame_number, frame in enumerate(next_video_np):
yield {
"frame_number": [frame_number],
"frame": frame,
}
示例15: export_module_spec_with_checkpoint
# 需要导入模块: from tensorflow.compat import v1 [as 别名]
# 或者: from tensorflow.compat.v1 import Graph [as 别名]
def export_module_spec_with_checkpoint(module_spec,
checkpoint_path,
export_path,
scope_prefix=""):
"""Exports given checkpoint as tfhub module with given spec."""
# The main requirement is that it is possible to know how to map from
# module variable name to checkpoint variable name.
# This is trivial if the original code used variable scopes,
# but can be messy if the variables to export are interwined
# with variables not export.
with tf.Graph().as_default():
m = hub.Module(module_spec)
assign_map = {
scope_prefix + name: value for name, value in m.variable_map.items()
}
tf.train.init_from_checkpoint(checkpoint_path, assign_map)
init_op = tf.initializers.global_variables()
with tf.Session() as session:
session.run(init_op)
m.export(export_path, session)