本文整理匯總了Python中tensorflow.compat.v1.set_random_seed方法的典型用法代碼示例。如果您正苦於以下問題:Python v1.set_random_seed方法的具體用法?Python v1.set_random_seed怎麽用?Python v1.set_random_seed使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類tensorflow.compat.v1
的用法示例。
在下文中一共展示了v1.set_random_seed方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_invertibility
# 需要導入模塊: from tensorflow.compat import v1 [as 別名]
# 或者: from tensorflow.compat.v1 import set_random_seed [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))
示例2: testGreedyFastTPUVsNonTPU
# 需要導入模塊: from tensorflow.compat import v1 [as 別名]
# 或者: from tensorflow.compat.v1 import set_random_seed [as 別名]
def testGreedyFastTPUVsNonTPU(self):
tf.set_random_seed(1234)
decode_length = DECODE_LENGTH
model, features = self._create_greedy_infer_model()
with tf.variable_scope(tf.get_variable_scope(), reuse=True):
fast_result_non_tpu = model._greedy_infer(
features, decode_length, use_tpu=False)["outputs"]
fast_result_tpu = model._greedy_infer(
features, decode_length, use_tpu=True)["outputs"]
with self.test_session():
fast_non_tpu_res = fast_result_non_tpu.eval()
fast_tpu_res = fast_result_tpu.eval()
self.assertEqual(fast_tpu_res.shape,
(BATCH_SIZE, INPUT_LENGTH + decode_length))
self.assertAllClose(fast_tpu_res, fast_non_tpu_res)
示例3: testFlopRegularizerDontConvertToVariable
# 需要導入模塊: from tensorflow.compat import v1 [as 別名]
# 或者: from tensorflow.compat.v1 import set_random_seed [as 別名]
def testFlopRegularizerDontConvertToVariable(self):
tf.reset_default_graph()
tf.set_random_seed(1234)
x = tf.constant(1.0, shape=[2, 6], name='x', dtype=tf.float32)
w = tf.Variable(tf.truncated_normal([6, 4], stddev=1.0), use_resource=True)
net = tf.matmul(x, w)
# Create FLOPs network regularizer.
threshold = 0.9
flop_reg = flop_regularizer.GroupLassoFlopsRegularizer([net.op], threshold,
0)
with self.cached_session():
tf.global_variables_initializer().run()
flop_reg.get_regularization_term().eval()
示例4: setUp
# 需要導入模塊: from tensorflow.compat import v1 [as 別名]
# 或者: from tensorflow.compat.v1 import set_random_seed [as 別名]
def setUp(self):
super(OpRegularizerManagerTest, self).setUp()
tf.set_random_seed(12)
np.random.seed(665544)
IndexOpRegularizer.reset_index()
# Create default OpHandler dict for testing.
self._default_op_handler_dict = collections.defaultdict(
grouping_op_handler.GroupingOpHandler)
self._default_op_handler_dict.update({
'FusedBatchNormV3':
IndexBatchNormSourceOpHandler(),
'Conv2D':
output_non_passthrough_op_handler.OutputNonPassthroughOpHandler(),
'ConcatV2':
concat_op_handler.ConcatOpHandler(),
'DepthwiseConv2dNative':
depthwise_convolution_op_handler.DepthwiseConvolutionOpHandler(),
})
示例5: get_data_and_params
# 需要導入模塊: from tensorflow.compat import v1 [as 別名]
# 或者: from tensorflow.compat.v1 import set_random_seed [as 別名]
def get_data_and_params():
"""Set up input dataset and variables."""
(train_x, train_y), _ = tf.keras.datasets.mnist.load_data()
tf.set_random_seed(0)
hparams = contrib_training.HParams(
batch_size=200,
learning_rate=0.1,
train_steps=101,
)
dataset = tf.data.Dataset.from_tensor_slices((train_x, train_y))
dataset = dataset.repeat()
dataset = dataset.shuffle(hparams.batch_size * 10)
dataset = dataset.batch(hparams.batch_size)
def reshape_ex(x, y):
return (tf.to_float(tf.reshape(x, (-1, 28 * 28))) / 256.0,
tf.one_hot(tf.squeeze(y), 10))
dataset = dataset.map(reshape_ex)
w = tf.get_variable('w0', (28 * 28, 10))
b = tf.get_variable('b0', (10,), initializer=tf.zeros_initializer())
opt = tf.train.GradientDescentOptimizer(hparams.learning_rate)
return dataset, opt, hparams, w, b
示例6: test_generator_graph
# 需要導入模塊: from tensorflow.compat import v1 [as 別名]
# 或者: from tensorflow.compat.v1 import set_random_seed [as 別名]
def test_generator_graph(self):
tf.set_random_seed(1234)
# Check graph construction for a number of image size/depths and batch
# sizes.
for i, batch_size in zip(xrange(3, 7), xrange(3, 8)):
tf.reset_default_graph()
final_size = 2 ** i
noise = tf.random.normal([batch_size, 64])
image, end_points = dcgan.generator(
noise,
depth=32,
final_size=final_size)
self.assertAllEqual([batch_size, final_size, final_size, 3],
image.shape.as_list())
expected_names = ['deconv%i' % j for j in xrange(1, i)] + ['logits']
self.assertSetEqual(set(expected_names), set(end_points.keys()))
# Check layer depths.
for j in range(1, i):
layer = end_points['deconv%i' % j]
self.assertEqual(32 * 2**(i-j-1), layer.get_shape().as_list()[-1])
示例7: testCreateLogisticClassifier
# 需要導入模塊: from tensorflow.compat import v1 [as 別名]
# 或者: from tensorflow.compat.v1 import set_random_seed [as 別名]
def testCreateLogisticClassifier(self):
g = tf.Graph()
with g.as_default():
tf.set_random_seed(0)
tf_inputs = tf.constant(self._inputs, dtype=tf.float32)
tf_labels = tf.constant(self._labels, dtype=tf.float32)
model_fn = LogisticClassifier
clone_args = (tf_inputs, tf_labels)
deploy_config = model_deploy.DeploymentConfig(num_clones=1)
self.assertEqual(slim.get_variables(), [])
clones = model_deploy.create_clones(deploy_config, model_fn, clone_args)
clone = clones[0]
self.assertEqual(len(slim.get_variables()), 2)
for v in slim.get_variables():
self.assertDeviceEqual(v.device, 'CPU:0')
self.assertDeviceEqual(v.value().device, 'CPU:0')
self.assertEqual(clone.outputs.op.name,
'LogisticClassifier/fully_connected/Sigmoid')
self.assertEqual(clone.scope, '')
self.assertDeviceEqual(clone.device, 'GPU:0')
self.assertEqual(len(slim.losses.get_losses()), 1)
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
self.assertEqual(update_ops, [])
示例8: testCreateSingleclone
# 需要導入模塊: from tensorflow.compat import v1 [as 別名]
# 或者: from tensorflow.compat.v1 import set_random_seed [as 別名]
def testCreateSingleclone(self):
g = tf.Graph()
with g.as_default():
tf.set_random_seed(0)
tf_inputs = tf.constant(self._inputs, dtype=tf.float32)
tf_labels = tf.constant(self._labels, dtype=tf.float32)
model_fn = BatchNormClassifier
clone_args = (tf_inputs, tf_labels)
deploy_config = model_deploy.DeploymentConfig(num_clones=1)
self.assertEqual(slim.get_variables(), [])
clones = model_deploy.create_clones(deploy_config, model_fn, clone_args)
clone = clones[0]
self.assertEqual(len(slim.get_variables()), 5)
for v in slim.get_variables():
self.assertDeviceEqual(v.device, 'CPU:0')
self.assertDeviceEqual(v.value().device, 'CPU:0')
self.assertEqual(clone.outputs.op.name,
'BatchNormClassifier/fully_connected/Sigmoid')
self.assertEqual(clone.scope, '')
self.assertDeviceEqual(clone.device, 'GPU:0')
self.assertEqual(len(slim.losses.get_losses()), 1)
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
self.assertEqual(len(update_ops), 2)
示例9: testCreateOnecloneWithPS
# 需要導入模塊: from tensorflow.compat import v1 [as 別名]
# 或者: from tensorflow.compat.v1 import set_random_seed [as 別名]
def testCreateOnecloneWithPS(self):
g = tf.Graph()
with g.as_default():
tf.set_random_seed(0)
tf_inputs = tf.constant(self._inputs, dtype=tf.float32)
tf_labels = tf.constant(self._labels, dtype=tf.float32)
model_fn = BatchNormClassifier
clone_args = (tf_inputs, tf_labels)
deploy_config = model_deploy.DeploymentConfig(num_clones=1,
num_ps_tasks=1)
self.assertEqual(slim.get_variables(), [])
clones = model_deploy.create_clones(deploy_config, model_fn, clone_args)
self.assertEqual(len(clones), 1)
clone = clones[0]
self.assertEqual(clone.outputs.op.name,
'BatchNormClassifier/fully_connected/Sigmoid')
self.assertDeviceEqual(clone.device, '/job:worker/device:GPU:0')
self.assertEqual(clone.scope, '')
self.assertEqual(len(slim.get_variables()), 5)
for v in slim.get_variables():
self.assertDeviceEqual(v.device, '/job:ps/task:0/CPU:0')
self.assertDeviceEqual(v.device, v.value().device)
示例10: _train_and_eval_local
# 需要導入模塊: from tensorflow.compat import v1 [as 別名]
# 或者: from tensorflow.compat.v1 import set_random_seed [as 別名]
def _train_and_eval_local(self,
params,
check_output_values=False,
max_final_loss=10.,
skip=None,
use_test_preprocessor=True):
# TODO(reedwm): check_output_values should default to True and be enabled
# on every test. Currently, if check_output_values=True and the calls to
# tf.set_random_seed(...) and np.seed(...) are passed certain seed values in
# benchmark_cnn.py, then most tests will fail. This indicates the tests
# are brittle and could fail with small changes when
# check_output_values=True, so check_output_values defaults to False for
# now.
def run_fn(run_type, inner_params):
del run_type
if use_test_preprocessor:
return [
self._run_benchmark_cnn_with_black_and_white_images(inner_params)
]
else:
return [self._run_benchmark_cnn(inner_params)]
return test_util.train_and_eval(self, run_fn, params,
check_output_values=check_output_values,
max_final_loss=max_final_loss,
skip=skip)
示例11: setUpClass
# 需要導入模塊: from tensorflow.compat import v1 [as 別名]
# 或者: from tensorflow.compat.v1 import set_random_seed [as 別名]
def setUpClass(cls):
tf.set_random_seed(1)
cls.problem = registry.problem("test_problem")
cls.data_dir = tempfile.gettempdir()
cls.filepatterns = generate_test_data(cls.problem, cls.data_dir)
示例12: set_random_seed
# 需要導入模塊: from tensorflow.compat import v1 [as 別名]
# 或者: from tensorflow.compat.v1 import set_random_seed [as 別名]
def set_random_seed(seed):
tf.set_random_seed(seed)
random.seed(seed)
np.random.seed(seed)
示例13: testSlowVsFast
# 需要導入模塊: from tensorflow.compat import v1 [as 別名]
# 或者: from tensorflow.compat.v1 import set_random_seed [as 別名]
def testSlowVsFast(self):
tf.set_random_seed(1234)
model, features = get_model(transformer.transformer_tiny())
decode_length = DECODE_LENGTH
out_logits, _ = model(features)
out_logits = tf.squeeze(out_logits, axis=[2, 3])
loss = tf.nn.sparse_softmax_cross_entropy_with_logits(
logits=tf.reshape(out_logits, [-1, VOCAB_SIZE]),
labels=tf.reshape(features["targets"], [-1]))
loss = tf.reduce_mean(loss)
apply_grad = tf.train.AdamOptimizer(0.001).minimize(loss)
with self.test_session():
tf.global_variables_initializer().run()
for _ in range(10):
apply_grad.run()
model.set_mode(tf.estimator.ModeKeys.PREDICT)
with tf.variable_scope(tf.get_variable_scope(), reuse=True):
greedy_result = model._slow_greedy_infer(features,
decode_length)["outputs"]
greedy_result = tf.squeeze(greedy_result, axis=[2, 3])
fast_result = model._greedy_infer(features, decode_length)["outputs"]
with self.test_session():
greedy_res = greedy_result.eval()
fast_res = fast_result.eval()
self.assertEqual(fast_res.shape, (BATCH_SIZE, INPUT_LENGTH + decode_length))
self.assertAllClose(greedy_res, fast_res)
示例14: setUp
# 需要導入模塊: from tensorflow.compat import v1 [as 別名]
# 或者: from tensorflow.compat.v1 import set_random_seed [as 別名]
def setUp(self):
tf.set_random_seed(1234)
np.random.seed(123)
示例15: setUp
# 需要導入模塊: from tensorflow.compat import v1 [as 別名]
# 或者: from tensorflow.compat.v1 import set_random_seed [as 別名]
def setUp(self):
tf.reset_default_graph()
tf.set_random_seed(7907)
with contrib_framework.arg_scope(
[layers.conv2d, layers.conv2d_transpose],
weights_initializer=tf.random_normal_initializer):
self.BuildModel()
with self.cached_session():
tf.global_variables_initializer().run()