本文整理汇总了Python中tensorflow.set_random_seed方法的典型用法代码示例。如果您正苦于以下问题:Python tensorflow.set_random_seed方法的具体用法?Python tensorflow.set_random_seed怎么用?Python tensorflow.set_random_seed使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tensorflow
的用法示例。
在下文中一共展示了tensorflow.set_random_seed方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: testCreateLogisticClassifier
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow 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, [])
示例2: testCreateOnecloneWithPS
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow 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)
示例3: testCreateSingleclone
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow 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)
self.assertEqual(len(slim.get_variables()), 5)
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
self.assertEqual(len(update_ops), 2)
optimizer = tf.train.GradientDescentOptimizer(learning_rate=1.0)
total_loss, grads_and_vars = model_deploy.optimize_clones(clones,
optimizer)
self.assertEqual(len(grads_and_vars), len(tf.trainable_variables()))
self.assertEqual(total_loss.op.name, 'total_loss')
for g, v in grads_and_vars:
self.assertDeviceEqual(g.device, 'GPU:0')
self.assertDeviceEqual(v.device, 'CPU:0')
示例4: set_global_seeds
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import set_random_seed [as 别名]
def set_global_seeds(i):
try:
import MPI
rank = MPI.COMM_WORLD.Get_rank()
except ImportError:
rank = 0
myseed = i + 1000 * rank if i is not None else None
try:
import tensorflow as tf
except ImportError:
pass
else:
tf.set_random_seed(myseed)
np.random.seed(myseed)
random.seed(myseed)
示例5: test_generator_graph
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow 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])
示例6: __init__
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import set_random_seed [as 别名]
def __init__(self, train_df, word_count, batch_size, epochs):
tf.set_random_seed(4)
session_conf = tf.ConfigProto(intra_op_parallelism_threads=2, inter_op_parallelism_threads=8)
backend.set_session(tf.Session(graph=tf.get_default_graph(), config=session_conf))
self.batch_size = batch_size
self.epochs = epochs
self.max_name_seq = 10
self.max_item_desc_seq = 75
self.max_text = word_count + 1
self.max_brand = np.max(train_df.brand_name.max()) + 1
self.max_condition = np.max(train_df.item_condition_id.max()) + 1
self.max_subcat0 = np.max(train_df.subcat_0.max()) + 1
self.max_subcat1 = np.max(train_df.subcat_1.max()) + 1
self.max_subcat2 = np.max(train_df.subcat_2.max()) + 1
示例7: test_equalize_sv
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import set_random_seed [as 别名]
def test_equalize_sv(self):
np.random.seed(1)
tf.reset_default_graph()
tf.set_random_seed(0)
latent_dim = 2
res_ranks, res_biplot = paired_omics(
self.microbes, self.metabolites,
epochs=1000, latent_dim=latent_dim,
min_feature_count=1, learning_rate=0.1,
equalize_biplot=True
)
# make sure the biplot is of the correct dimensions
npt.assert_allclose(
res_biplot.samples.shape,
np.array([self.microbes.shape[0], latent_dim]))
npt.assert_allclose(
res_biplot.features.shape,
np.array([self.metabolites.shape[0], latent_dim]))
# make sure that the biplot has the correct ordering
self.assertGreater(res_biplot.proportion_explained[0],
res_biplot.proportion_explained[1])
self.assertGreater(res_biplot.eigvals[0],
res_biplot.eigvals[1])
示例8: test_output_is_integer_in_replace_empty_string_with_random_number
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import set_random_seed [as 别名]
def test_output_is_integer_in_replace_empty_string_with_random_number(self):
string_placeholder = tf.placeholder(tf.string, shape=[])
replaced_string = inputs._replace_empty_string_with_random_number(
string_placeholder)
empty_string = ''
feed_dict = {string_placeholder: empty_string}
tf.set_random_seed(0)
with self.test_session() as sess:
out_string = sess.run(replaced_string, feed_dict=feed_dict)
# Test whether out_string is a string which represents an integer.
int(out_string) # throws an error if out_string is not castable to int.
self.assertEqual(out_string, '2798129067578209328')
示例9: init_tf
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import set_random_seed [as 别名]
def init_tf(config_dict=dict()):
if tf.get_default_session() is None:
tf.set_random_seed(np.random.randint(1 << 31))
create_session(config_dict, force_as_default=True)
#----------------------------------------------------------------------------
# Create tf.Session based on config dict of the form
# {'gpu_options.allow_growth': True}
示例10: test_attack_strength
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import set_random_seed [as 别名]
def test_attack_strength(self):
"""
This test generates a random source and guide and feeds them in a
randomly initialized CNN. Checks if an adversarial example can get
at least 50% closer to the guide compared to the original distance of
the source and the guide.
"""
tf.set_random_seed(1234)
input_shape = self.input_shape
x_src = tf.abs(tf.random_uniform(input_shape, 0., 1.))
x_guide = tf.abs(tf.random_uniform(input_shape, 0., 1.))
layer = 'fc7'
attack_params = {'eps': 5./256, 'clip_min': 0., 'clip_max': 1.,
'nb_iter': 10, 'eps_iter': 0.005,
'layer': layer}
x_adv = self.attack.generate(x_src, x_guide, **attack_params)
h_adv = self.model.fprop(x_adv)[layer]
h_src = self.model.fprop(x_src)[layer]
h_guide = self.model.fprop(x_guide)[layer]
init = tf.global_variables_initializer()
self.sess.run(init)
ha, hs, hg, xa, xs, xg = self.sess.run(
[h_adv, h_src, h_guide, x_adv, x_src, x_guide])
d_as = np.sqrt(((hs-ha)*(hs-ha)).sum())
d_ag = np.sqrt(((hg-ha)*(hg-ha)).sum())
d_sg = np.sqrt(((hg-hs)*(hg-hs)).sum())
print("L2 distance between source and adversarial example `%s`: %.4f" %
(layer, d_as))
print("L2 distance between guide and adversarial example `%s`: %.4f" %
(layer, d_ag))
print("L2 distance between source and guide `%s`: %.4f" %
(layer, d_sg))
print("d_ag/d_sg*100 `%s`: %.4f" % (layer, d_ag*100/d_sg))
self.assertTrue(d_ag*100/d_sg < 50.)
示例11: main
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import set_random_seed [as 别名]
def main(argv):
# Set TF random seed to improve reproducibility
tf.set_random_seed(1234)
input_shape = [FLAGS.batch_size, 224, 224, 3]
x_src = tf.abs(tf.random_uniform(input_shape, 0., 1.))
x_guide = tf.abs(tf.random_uniform(input_shape, 0., 1.))
print("Input shape:")
print(input_shape)
model = make_imagenet_cnn(input_shape)
attack = FastFeatureAdversaries(model)
attack_params = {'eps': 0.3, 'clip_min': 0., 'clip_max': 1.,
'nb_iter': FLAGS.nb_iter, 'eps_iter': 0.01,
'layer': FLAGS.layer}
x_adv = attack.generate(x_src, x_guide, **attack_params)
h_adv = model.fprop(x_adv)[FLAGS.layer]
h_src = model.fprop(x_src)[FLAGS.layer]
h_guide = model.fprop(x_guide)[FLAGS.layer]
with tf.Session() as sess:
init = tf.global_variables_initializer()
sess.run(init)
ha, hs, hg, xa, xs, xg = sess.run(
[h_adv, h_src, h_guide, x_adv, x_src, x_guide])
print("L2 distance between source and adversarial example `%s`: %.4f" %
(FLAGS.layer, ((hs-ha)*(hs-ha)).sum()))
print("L2 distance between guide and adversarial example `%s`: %.4f" %
(FLAGS.layer, ((hg-ha)*(hg-ha)).sum()))
print("L2 distance between source and guide `%s`: %.4f" %
(FLAGS.layer, ((hg-hs)*(hg-hs)).sum()))
print("Maximum perturbation: %.4f" % np.abs((xa-xs)).max())
print("Original features: ")
print(hs[:10, :10])
print("Adversarial features: ")
print(ha[:10, :10])
示例12: setup_tutorial
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import set_random_seed [as 别名]
def setup_tutorial():
"""
Helper function to check correct configuration of tf for tutorial
:return: True if setup checks completed
"""
# Set TF random seed to improve reproducibility
tf.set_random_seed(1234)
return True
示例13: _init_session
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import set_random_seed [as 别名]
def _init_session(self):
# Set TF random seed to improve reproducibility
self.rng = np.random.RandomState([2017, 8, 30])
tf.set_random_seed(1234)
# Create TF session
self.sess = tf.Session(
config=tf.ConfigProto(allow_soft_placement=True))
# Object used to keep track of (and return) key accuracies
if self.hparams.save:
self.writer = tf.summary.FileWriter(self.hparams.save_dir,
flush_secs=10)
else:
self.writer = None
示例14: testAtrousFullyConvolutionalValues
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import set_random_seed [as 别名]
def testAtrousFullyConvolutionalValues(self):
"""Verify dense feature extraction with atrous convolution."""
nominal_stride = 32
for output_stride in [4, 8, 16, 32, None]:
with slim.arg_scope(resnet_utils.resnet_arg_scope()):
with tf.Graph().as_default():
with self.test_session() as sess:
tf.set_random_seed(0)
inputs = create_test_input(2, 81, 81, 3)
# Dense feature extraction followed by subsampling.
output, _ = self._resnet_small(inputs, None,
is_training=False,
global_pool=False,
output_stride=output_stride)
if output_stride is None:
factor = 1
else:
factor = nominal_stride // output_stride
output = resnet_utils.subsample(output, factor)
# Make the two networks use the same weights.
tf.get_variable_scope().reuse_variables()
# Feature extraction at the nominal network rate.
expected, _ = self._resnet_small(inputs, None,
is_training=False,
global_pool=False)
sess.run(tf.global_variables_initializer())
self.assertAllClose(output.eval(), expected.eval(),
atol=1e-4, rtol=1e-4)
示例15: testAtrousFullyConvolutionalValues
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import set_random_seed [as 别名]
def testAtrousFullyConvolutionalValues(self):
"""Verify dense feature extraction with atrous convolution."""
nominal_stride = 32
for output_stride in [4, 8, 16, 32, None]:
with slim.arg_scope(resnet_utils.resnet_arg_scope()):
with tf.Graph().as_default():
with self.test_session() as sess:
tf.set_random_seed(0)
inputs = create_test_input(2, 81, 81, 3)
# Dense feature extraction followed by subsampling.
output, _ = self._resnet_small(inputs, None, is_training=False,
global_pool=False,
output_stride=output_stride)
if output_stride is None:
factor = 1
else:
factor = nominal_stride // output_stride
output = resnet_utils.subsample(output, factor)
# Make the two networks use the same weights.
tf.get_variable_scope().reuse_variables()
# Feature extraction at the nominal network rate.
expected, _ = self._resnet_small(inputs, None, is_training=False,
global_pool=False)
sess.run(tf.global_variables_initializer())
self.assertAllClose(output.eval(), expected.eval(),
atol=1e-4, rtol=1e-4)