本文整理汇总了Python中tensorflow.local_variables_initializer方法的典型用法代码示例。如果您正苦于以下问题:Python tensorflow.local_variables_initializer方法的具体用法?Python tensorflow.local_variables_initializer怎么用?Python tensorflow.local_variables_initializer使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tensorflow
的用法示例。
在下文中一共展示了tensorflow.local_variables_initializer方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_adam
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import local_variables_initializer [as 别名]
def test_adam(self):
with self.test_session() as sess:
w = tf.get_variable(
"w",
shape=[3],
initializer=tf.constant_initializer([0.1, -0.2, -0.1]))
x = tf.constant([0.4, 0.2, -0.5])
loss = tf.reduce_mean(tf.square(x - w))
tvars = tf.trainable_variables()
grads = tf.gradients(loss, tvars)
global_step = tf.train.get_or_create_global_step()
optimizer = optimization.AdamWeightDecayOptimizer(learning_rate=0.2)
train_op = optimizer.apply_gradients(zip(grads, tvars), global_step)
init_op = tf.group(tf.global_variables_initializer(),
tf.local_variables_initializer())
sess.run(init_op)
for _ in range(100):
sess.run(train_op)
w_np = sess.run(w)
self.assertAllClose(w_np.flat, [0.4, 0.2, -0.5], rtol=1e-2, atol=1e-2)
示例2: test_create_summaries_is_runnable
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import local_variables_initializer [as 别名]
def test_create_summaries_is_runnable(self):
ocr_model = self.create_model()
data = data_provider.InputEndpoints(
images=self.fake_images,
images_orig=self.fake_images,
labels=self.fake_labels,
labels_one_hot=slim.one_hot_encoding(self.fake_labels,
self.num_char_classes))
endpoints = ocr_model.create_base(
images=self.fake_images, labels_one_hot=None)
charset = create_fake_charset(self.num_char_classes)
summaries = ocr_model.create_summaries(
data, endpoints, charset, is_training=False)
with self.test_session() as sess:
sess.run(tf.global_variables_initializer())
sess.run(tf.local_variables_initializer())
tf.tables_initializer().run()
sess.run(summaries) # just check it is runnable
示例3: testSigmoidAccuracyOneHot
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import local_variables_initializer [as 别名]
def testSigmoidAccuracyOneHot(self):
logits = np.array([
[-1., 1.],
[1., -1.],
[-1., 1.],
[1., -1.]
])
labels = np.array([
[0, 1],
[1, 0],
[1, 0],
[0, 1]
])
logits = np.expand_dims(np.expand_dims(logits, 1), 1)
labels = np.expand_dims(np.expand_dims(labels, 1), 1)
with self.test_session() as session:
score, _ = metrics.sigmoid_accuracy_one_hot(logits, labels)
session.run(tf.global_variables_initializer())
session.run(tf.local_variables_initializer())
s = session.run(score)
self.assertEqual(s, 0.5)
示例4: testSigmoidPrecisionOneHot
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import local_variables_initializer [as 别名]
def testSigmoidPrecisionOneHot(self):
logits = np.array([
[-1., 1.],
[1., -1.],
[1., -1.],
[1., -1.]
])
labels = np.array([
[0, 1],
[0, 1],
[0, 1],
[0, 1]
])
logits = np.expand_dims(np.expand_dims(logits, 1), 1)
labels = np.expand_dims(np.expand_dims(labels, 1), 1)
with self.test_session() as session:
score, _ = metrics.sigmoid_precision_one_hot(logits, labels)
session.run(tf.global_variables_initializer())
session.run(tf.local_variables_initializer())
s = session.run(score)
self.assertEqual(s, 0.25)
示例5: testSigmoidRecallOneHot
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import local_variables_initializer [as 别名]
def testSigmoidRecallOneHot(self):
logits = np.array([
[-1., 1.],
[1., -1.],
[1., -1.],
[1., -1.]
])
labels = np.array([
[0, 1],
[0, 1],
[0, 1],
[0, 1]
])
logits = np.expand_dims(np.expand_dims(logits, 1), 1)
labels = np.expand_dims(np.expand_dims(labels, 1), 1)
with self.test_session() as session:
score, _ = metrics.sigmoid_recall_one_hot(logits, labels)
session.run(tf.global_variables_initializer())
session.run(tf.local_variables_initializer())
s = session.run(score)
self.assertEqual(s, 0.25)
示例6: testSigmoidCrossEntropyOneHot
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import local_variables_initializer [as 别名]
def testSigmoidCrossEntropyOneHot(self):
logits = np.array([
[-1., 1.],
[1., -1.],
[1., -1.],
[1., -1.]
])
labels = np.array([
[0, 1],
[1, 0],
[0, 0],
[0, 1]
])
logits = np.expand_dims(np.expand_dims(logits, 1), 1)
labels = np.expand_dims(np.expand_dims(labels, 1), 1)
with self.test_session() as session:
score, _ = metrics.sigmoid_cross_entropy_one_hot(logits, labels)
session.run(tf.global_variables_initializer())
session.run(tf.local_variables_initializer())
s = session.run(score)
self.assertAlmostEqual(s, 0.688, places=3)
示例7: testRocAuc
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import local_variables_initializer [as 别名]
def testRocAuc(self):
logits = np.array([
[-1., 1.],
[1., -1.],
[1., -1.],
[1., -1.]
])
labels = np.array([
[1],
[0],
[1],
[0]
])
logits = np.expand_dims(np.expand_dims(logits, 1), 1)
labels = np.expand_dims(np.expand_dims(labels, 1), 1)
with self.test_session() as session:
score, _ = metrics.roc_auc(logits, labels)
session.run(tf.global_variables_initializer())
session.run(tf.local_variables_initializer())
s = session.run(score)
self.assertAlmostEqual(s, 0.750, places=3)
示例8: omniglot
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import local_variables_initializer [as 别名]
def omniglot():
sess = tf.InteractiveSession()
""" def wrapper(v):
return tf.Print(v, [v], message="Printing v")
v = tf.Variable(initial_value=np.arange(0, 36).reshape((6, 6)), dtype=tf.float32, name='Matrix')
sess.run(tf.global_variables_initializer())
sess.run(tf.local_variables_initializer())
temp = tf.Variable(initial_value=np.arange(0, 36).reshape((6, 6)), dtype=tf.float32, name='temp')
temp = wrapper(v)
#with tf.control_dependencies([temp]):
temp.eval()
print 'Hello'"""
def update_tensor(V, dim2, val): # Update tensor V, with index(:,dim2[:]) by val[:]
val = tf.cast(val, V.dtype)
def body(_, (v, d2, chg)):
d2_int = tf.cast(d2, tf.int32)
return tf.slice(tf.concat_v2([v[:d2_int],[chg] ,v[d2_int+1:]], axis=0), [0], [v.get_shape().as_list()[0]])
Z = tf.scan(body, elems=(V, dim2, val), initializer=tf.constant(1, shape=V.get_shape().as_list()[1:], dtype=tf.float32), name="Scan_Update")
return Z
示例9: test_adam
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import local_variables_initializer [as 别名]
def test_adam(self):
with self.test_session() as sess:
w = tf.get_variable(
"w",
shape=[3],
initializer=tf.constant_initializer([0.1, -0.2, -0.1]))
x = tf.constant([0.4, 0.2, -0.5])
loss = tf.reduce_mean(tf.square(x - w))
tvars = tf.trainable_variables()
grads = tf.gradients(loss, tvars)
global_step = tf.train.get_or_create_global_step()
optimizer = optimization.AdamWeightDecayOptimizer(learning_rate=0.2)
train_op = optimizer.apply_gradients(zip(grads, tvars), global_step)
init_op = tf.group(tf.global_variables_initializer(),
tf.local_variables_initializer())
sess.run(init_op)
for _ in range(100):
sess.run(train_op)
w_np = sess.run(w)
self.assertAllClose(w_np.flat, [0.4, 0.2, -0.5], rtol=1e-2, atol=1e-2)
开发者ID:Nagakiran1,项目名称:Extending-Google-BERT-as-Question-and-Answering-model-and-Chatbot,代码行数:22,代码来源:optimization_test.py
示例10: execute_cpu
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import local_variables_initializer [as 别名]
def execute_cpu(self, graph_fn, inputs):
"""Constructs the graph, executes it on CPU and returns the result.
Args:
graph_fn: a callable that constructs the tensorflow graph to test. The
arguments of this function should correspond to `inputs`.
inputs: a list of numpy arrays to feed input to the computation graph.
Returns:
A list of numpy arrays or a scalar returned from executing the tensorflow
graph.
"""
with self.test_session(graph=tf.Graph()) as sess:
placeholders = [tf.placeholder_with_default(v, v.shape) for v in inputs]
results = graph_fn(*placeholders)
sess.run([tf.global_variables_initializer(), tf.tables_initializer(),
tf.local_variables_initializer()])
materialized_results = sess.run(results, feed_dict=dict(zip(placeholders,
inputs)))
if (len(materialized_results) == 1
and (isinstance(materialized_results, list)
or isinstance(materialized_results, tuple))):
materialized_results = materialized_results[0]
return materialized_results
示例11: testMultilabelMatch3
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import local_variables_initializer [as 别名]
def testMultilabelMatch3(self):
predictions = np.random.randint(1, 5, size=(100, 1, 1, 1))
targets = np.random.randint(1, 5, size=(100, 10, 1, 1))
weights = np.random.randint(0, 2, size=(100, 1, 1, 1))
targets *= weights
predictions_repeat = np.repeat(predictions, 10, axis=1)
expected = (predictions_repeat == targets).astype(float)
expected = np.sum(expected, axis=(1, 2, 3))
expected = np.minimum(expected / 3.0, 1.)
expected = np.sum(expected * weights[:, 0, 0, 0]) / weights.shape[0]
with self.test_session() as session:
scores, weights_ = metrics.multilabel_accuracy_match3(
tf.one_hot(predictions, depth=5, dtype=tf.float32),
tf.constant(targets, dtype=tf.int32))
a, a_op = tf.metrics.mean(scores, weights_)
session.run(tf.local_variables_initializer())
session.run(tf.global_variables_initializer())
_ = session.run(a_op)
actual = session.run(a)
self.assertAlmostEqual(actual, expected, places=6)
示例12: run_tester
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import local_variables_initializer [as 别名]
def run_tester(self, tester):
with self.test_session() as sess:
ops = tester.create_model()
init_op = tf.group(tf.global_variables_initializer(),
tf.local_variables_initializer())
sess.run(init_op)
output_result = sess.run(ops)
tester.check_output(output_result)
self.assert_all_tensors_reachable(sess, [init_op, ops])
示例13: initialized_session
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import local_variables_initializer [as 别名]
def initialized_session(self):
"""Wrapper for test session context manager with required initialization.
Yields:
A session object that should be used as a context manager.
"""
with self.test_session() as sess:
sess.run(tf.global_variables_initializer())
sess.run(tf.local_variables_initializer())
yield sess
示例14: initialize_variables
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import local_variables_initializer [as 别名]
def initialize_variables(sess, saver, logdir, checkpoint=None, resume=None):
"""Initialize or restore variables from a checkpoint if available.
Args:
sess: Session to initialize variables in.
saver: Saver to restore variables.
logdir: Directory to search for checkpoints.
checkpoint: Specify what checkpoint name to use; defaults to most recent.
resume: Whether to expect recovering a checkpoint or starting a new run.
Raises:
ValueError: If resume expected but no log directory specified.
RuntimeError: If no resume expected but a checkpoint was found.
"""
sess.run(tf.group(
tf.local_variables_initializer(),
tf.global_variables_initializer()))
if resume and not (logdir or checkpoint):
raise ValueError('Need to specify logdir to resume a checkpoint.')
if logdir:
state = tf.train.get_checkpoint_state(logdir)
if checkpoint:
checkpoint = os.path.join(logdir, checkpoint)
if not checkpoint and state and state.model_checkpoint_path:
checkpoint = state.model_checkpoint_path
if checkpoint and resume is False:
message = 'Found unexpected checkpoint when starting a new run.'
raise RuntimeError(message)
if checkpoint:
saver.restore(sess, checkpoint)
示例15: compute_one_decoding_video_metrics
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import local_variables_initializer [as 别名]
def compute_one_decoding_video_metrics(iterator, feed_dict, num_videos):
"""Computes the average of all the metric for one decoding.
Args:
iterator: dataset iterator.
feed_dict: feed dict to initialize iterator.
num_videos: number of videos.
Returns:
Dictionary which contains the average of each metric per frame.
"""
output, target = iterator.get_next()
metrics_dict = compute_metrics(output, target)
metrics_names, metrics = zip(*six.iteritems(metrics_dict))
means, update_ops = tf.metrics.mean_tensor(metrics)
with tf.Session() as sess:
sess.run(tf.local_variables_initializer())
initalizer = iterator._initializer # pylint: disable=protected-access
if initalizer is not None:
sess.run(initalizer, feed_dict=feed_dict)
# Compute mean over dataset
for i in range(num_videos):
print("Computing video: %d" % i)
sess.run(update_ops)
averaged_metrics = sess.run(means)
results = dict(zip(metrics_names, averaged_metrics))
return results