當前位置: 首頁>>代碼示例>>Python>>正文


Python tensorflow.set_random_seed方法代碼示例

本文整理匯總了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, []) 
開發者ID:ringringyi,項目名稱:DOTA_models,代碼行數:27,代碼來源:model_deploy_test.py

示例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) 
開發者ID:ringringyi,項目名稱:DOTA_models,代碼行數:26,代碼來源:model_deploy_test.py

示例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') 
開發者ID:ringringyi,項目名稱:DOTA_models,代碼行數:27,代碼來源:model_deploy_test.py

示例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) 
開發者ID:MaxSobolMark,項目名稱:HardRLWithYoutube,代碼行數:18,代碼來源:misc_util.py

示例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]) 
開發者ID:leimao,項目名稱:DeepLab_v3,代碼行數:25,代碼來源:dcgan_test.py

示例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 
開發者ID:aerdem4,項目名稱:mercari-price-suggestion,代碼行數:18,代碼來源:nn_model.py

示例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]) 
開發者ID:biocore,項目名稱:mmvec,代碼行數:26,代碼來源:test_method.py

示例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') 
開發者ID:ahmetozlu,項目名稱:vehicle_counting_tensorflow,代碼行數:20,代碼來源:inputs_test.py

示例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} 
開發者ID:zalandoresearch,項目名稱:disentangling_conditional_gans,代碼行數:10,代碼來源:tfutil.py

示例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.) 
開發者ID:StephanZheng,項目名稱:neural-fingerprinting,代碼行數:39,代碼來源:test_attacks.py

示例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]) 
開發者ID:StephanZheng,項目名稱:neural-fingerprinting,代碼行數:39,代碼來源:attack_model_featadv.py

示例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 
開發者ID:StephanZheng,項目名稱:neural-fingerprinting,代碼行數:12,代碼來源:mnist_blackbox_keras.py

示例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 
開發者ID:StephanZheng,項目名稱:neural-fingerprinting,代碼行數:17,代碼來源:trainer.py

示例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) 
開發者ID:ringringyi,項目名稱:DOTA_models,代碼行數:30,代碼來源:resnet_v2_test.py

示例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) 
開發者ID:ringringyi,項目名稱:DOTA_models,代碼行數:28,代碼來源:resnet_v1_test.py


注:本文中的tensorflow.set_random_seed方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。