当前位置: 首页>>代码示例>>Python>>正文


Python app.run方法代码示例

本文整理汇总了Python中tensorflow.python.platform.app.run方法的典型用法代码示例。如果您正苦于以下问题:Python app.run方法的具体用法?Python app.run怎么用?Python app.run使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在tensorflow.python.platform.app的用法示例。


在下文中一共展示了app.run方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: report_benchmark

# 需要导入模块: from tensorflow.python.platform import app [as 别名]
# 或者: from tensorflow.python.platform.app import run [as 别名]
def report_benchmark(
      self,
      iters=None,
      cpu_time=None,
      wall_time=None,
      throughput=None,
      extras=None,
      name=None):
    """Report a benchmark.

    Args:
      iters: (optional) How many iterations were run
      cpu_time: (optional) Total cpu time in seconds
      wall_time: (optional) Total wall time in seconds
      throughput: (optional) Throughput (in MB/s)
      extras: (optional) Dict mapping string keys to additional benchmark info.
        Values may be either floats or values that are convertible to strings.
      name: (optional) Override the BenchmarkEntry name with `name`.
        Otherwise it is inferred from the top-level method name.
    """
    name = self._get_name(overwrite_name=name)
    _global_report_benchmark(
        name=name, iters=iters, cpu_time=cpu_time, wall_time=wall_time,
        throughput=throughput, extras=extras) 
开发者ID:ryfeus,项目名称:lambda-packs,代码行数:26,代码来源:benchmark.py

示例2: benchmarks_main

# 需要导入模块: from tensorflow.python.platform import app [as 别名]
# 或者: from tensorflow.python.platform.app import run [as 别名]
def benchmarks_main(true_main, argv=None):
  """Run benchmarks as declared in argv.

  Args:
    true_main: True main function to run if benchmarks are not requested.
    argv: the command line arguments (if None, uses sys.argv).
  """
  if argv is None:
    argv = sys.argv
  found_arg = [arg for arg in argv
               if arg.startswith("--benchmarks=")
               or arg.startswith("-benchmarks=")]
  if found_arg:
    # Remove --benchmarks arg from sys.argv
    argv.remove(found_arg[0])

    regex = found_arg[0].split("=")[1]
    app.run(lambda _: _run_benchmarks(regex), argv=argv)
  else:
    true_main() 
开发者ID:ryfeus,项目名称:lambda-packs,代码行数:22,代码来源:benchmark.py

示例3: main

# 需要导入模块: from tensorflow.python.platform import app [as 别名]
# 或者: from tensorflow.python.platform.app import run [as 别名]
def main(argv=None):
    imgnames = filter(lambda x: x.lower().endswith(".jpg") or x.lower().endswith(".png"), os.listdir(FLAGS.srcimgs))
    imgs = np.asarray(map(lambda x: preprocess_yadav(x),
                          map(lambda x: cv2.resize(read_img(os.path.join(FLAGS.srcimgs, x)), (FLAGS.img_cols, FLAGS.img_rows)),
                              imgnames))
                      , dtype=np.float32)
    print 'Loaded images from %s'%FLAGS.srcimgs
    sys.stdout.flush()
    results = []
    with tf.Session() as sess:
        model = YadavModel(train=False)
        saver = tf.train.Saver()
        saver.restore(sess, FLAGS.weights)
        print 'Loaded model from %s'%FLAGS.weights
        sys.stdout.flush()
        output = sess.run(model.labels_pred, feed_dict={model.features: imgs, model.keep_prob: 1.0}) 
        for i in range(len(imgs)):
            results.append((imgnames[i], top3_as_string(output, i)))

    for i in range(len(results)):
        print results[i][0], results[i][1] 
开发者ID:evtimovi,项目名称:robust_physical_perturbations,代码行数:23,代码来源:classify_yadav.py

示例4: main

# 需要导入模块: from tensorflow.python.platform import app [as 别名]
# 或者: from tensorflow.python.platform.app import run [as 别名]
def main(argv=None):
    X_train, Y_train, X_test, Y_test = gtsrb(FLAGS.train_dataset, FLAGS.test_dataset, labels_filename=FLAGS.labels)
    print 'Loaded GTSRB data'

    X_train = np.asarray(map(lambda x: pre_process_image(x), X_train.astype(np.uint8)),dtype=np.float32)
    X_test = np.asarray(map(lambda x: pre_process_image(x), X_test.astype(np.uint8)),dtype=np.float32)
    global total_iterations 
    global best_validation_accuracy
    global last_improvement
    global best_test_accuracy 
    
    global val_acc_list 
    global batch_acc_list 
    global test_acc_list


    with tf.Session() as sess:
        model = YadavModel()
	sess.run(tf.initialize_all_variables())
        #X_train, Y_train = gen_transformed_data(X_train,Y_train,43,10,30,5,5,1)
	print(X_train.shape)
	print(Y_train.shape)
	optimize(sess, model, X_train, Y_train, X_test, Y_test, 10000, 128) 
开发者ID:evtimovi,项目名称:robust_physical_perturbations,代码行数:25,代码来源:train_yadav.py

示例5: main

# 需要导入模块: from tensorflow.python.platform import app [as 别名]
# 或者: from tensorflow.python.platform.app import run [as 别名]
def main(argv=None):
    with tf.device(FLAGS.device):
        with tf.Session() as sess:
            print "Noise loaded from", FLAGS.model_path
            print "Mask", FLAGS.attack_mask
            print "Source image", FLAGS.src_image
            bimg = cv2.resize(read_img(FLAGS.src_image), (FLAGS.img_rows, FLAGS.img_cols))/255.0 - 0.5

            noise= tf.Variable(tf.random_uniform( \
                [FLAGS.img_rows, FLAGS.img_cols, FLAGS.nb_channels], -0.5, 0.5), \
                name='noiseattack/noise', collections=[tf.GraphKeys.GLOBAL_VARIABLES, 'adv_var'])

            saver = tf.train.Saver(var_list=[noise])
            saver.restore(sess, FLAGS.model_path)

            noise_val = sess.run(noise)
            write_img('noise.png', (noise_val)*255.0)
            mask = read_img(FLAGS.attack_mask)/255.0
            noise_val = noise_val*mask
            write_img(FLAGS.output_path,(bimg+noise_val+0.5)*255)
            print "Wrote image to", FLAGS.output_path 
开发者ID:evtimovi,项目名称:robust_physical_perturbations,代码行数:23,代码来源:apply_noise_no_resize.py

示例6: benchmarks_main

# 需要导入模块: from tensorflow.python.platform import app [as 别名]
# 或者: from tensorflow.python.platform.app import run [as 别名]
def benchmarks_main(true_main):
  """Run benchmarks as declared in args.

  Args:
    true_main: True main function to run if benchmarks are not requested.
  """
  argv = sys.argv
  found_arg = [arg for arg in argv
               if arg.startswith("--benchmarks=")
               or arg.startswith("-benchmarks=")]
  if found_arg:
    # Remove --benchmarks arg from sys.argv
    argv.remove(found_arg[0])

    regex = found_arg[0].split("=")[1]
    app.run(lambda _: _run_benchmarks(regex))
  else:
    true_main() 
开发者ID:tobegit3hub,项目名称:deep_image_model,代码行数:20,代码来源:benchmark.py

示例7: _get_tf2_parser

# 需要导入模块: from tensorflow.python.platform import app [as 别名]
# 或者: from tensorflow.python.platform.app import run [as 别名]
def _get_tf2_parser():
  """Returns ArgumentParser for tflite_convert for TensorFlow 2.0."""
  parser = argparse.ArgumentParser(
      description=("Command line tool to run TensorFlow Lite Converter."))

  # Output file flag.
  parser.add_argument(
      "--output_file",
      type=str,
      help="Full filepath of the output file.",
      required=True)

  # Input file flags.
  input_file_group = parser.add_mutually_exclusive_group(required=True)
  input_file_group.add_argument(
      "--saved_model_dir",
      type=str,
      help="Full path of the directory containing the SavedModel.")
  input_file_group.add_argument(
      "--keras_model_file",
      type=str,
      help="Full filepath of HDF5 file containing tf.Keras model.")
  return parser 
开发者ID:david8862,项目名称:keras-YOLOv3-model-set,代码行数:25,代码来源:custom_tflite_convert.py

示例8: report_benchmark

# 需要导入模块: from tensorflow.python.platform import app [as 别名]
# 或者: from tensorflow.python.platform.app import run [as 别名]
def report_benchmark(
      self,
      iters=None,
      cpu_time=None,
      wall_time=None,
      throughput=None,
      extras=None,
      name=None):
    """Report a benchmark.

    Args:
      iters: (optional) How many iterations were run
      cpu_time: (optional) median or mean cpu time in seconds.
      wall_time: (optional) median or mean wall time in seconds.
      throughput: (optional) Throughput (in MB/s)
      extras: (optional) Dict mapping string keys to additional benchmark info.
        Values may be either floats or values that are convertible to strings.
      name: (optional) Override the BenchmarkEntry name with `name`.
        Otherwise it is inferred from the top-level method name.
    """
    name = self._get_name(overwrite_name=name)
    _global_report_benchmark(
        name=name, iters=iters, cpu_time=cpu_time, wall_time=wall_time,
        throughput=throughput, extras=extras) 
开发者ID:PacktPublishing,项目名称:Serverless-Deep-Learning-with-TensorFlow-and-AWS-Lambda,代码行数:26,代码来源:benchmark.py

示例9: main

# 需要导入模块: from tensorflow.python.platform import app [as 别名]
# 或者: from tensorflow.python.platform.app import run [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

示例10: _run_benchmarks

# 需要导入模块: from tensorflow.python.platform import app [as 别名]
# 或者: from tensorflow.python.platform.app import run [as 别名]
def _run_benchmarks(regex):
  """Run benchmarks that match regex `regex`.

  This function goes through the global benchmark registry, and matches
  benchmark class and method names of the form
  `module.name.BenchmarkClass.benchmarkMethod` to the given regex.
  If a method matches, it is run.

  Args:
    regex: The string regular expression to match Benchmark classes against.
  """
  registry = list(GLOBAL_BENCHMARK_REGISTRY)

  # Match benchmarks in registry against regex
  for benchmark in registry:
    benchmark_name = "%s.%s" % (benchmark.__module__, benchmark.__name__)
    attrs = dir(benchmark)
    # Don't instantiate the benchmark class unless necessary
    benchmark_instance = None

    for attr in attrs:
      if not attr.startswith("benchmark"):
        continue
      candidate_benchmark_fn = getattr(benchmark, attr)
      if not callable(candidate_benchmark_fn):
        continue
      full_benchmark_name = "%s.%s" % (benchmark_name, attr)
      if regex == "all" or re.search(regex, full_benchmark_name):
        # Instantiate the class if it hasn't been instantiated
        benchmark_instance = benchmark_instance or benchmark()
        # Get the method tied to the class
        instance_benchmark_fn = getattr(benchmark_instance, attr)
        # Call the instance method
        instance_benchmark_fn() 
开发者ID:ryfeus,项目名称:lambda-packs,代码行数:36,代码来源:benchmark.py

示例11: main

# 需要导入模块: from tensorflow.python.platform import app [as 别名]
# 或者: from tensorflow.python.platform.app import run [as 别名]
def main(argv=None):  # pylint: disable=function-redefined
  def main_wrapper():
    args = argv
    if args is None:
      args = sys.argv
    return app.run(main=g_main, argv=args)
  benchmark.benchmarks_main(true_main=main_wrapper) 
开发者ID:ryfeus,项目名称:lambda-packs,代码行数:9,代码来源:googletest.py

示例12: restore_or_init_noise

# 需要导入模块: from tensorflow.python.platform import app [as 别名]
# 或者: from tensorflow.python.platform.app import run [as 别名]
def restore_or_init_noise(sess, attack_graph, noise_path):
    if noise_path != "":
        noise_restorer = tf.train.Saver(var_list=[attack_graph.noise])
        noise_restorer.restore(sess, noise_path)
        return True
    else:
        sess.run(attack_graph.init_noise)
        return False 
开发者ID:evtimovi,项目名称:robust_physical_perturbations,代码行数:10,代码来源:attack.py

示例13: __init__

# 需要导入模块: from tensorflow.python.platform import app [as 别名]
# 或者: from tensorflow.python.platform.app import run [as 别名]
def __init__(self, just_apply_noise, batch_size):
        self.just_apply_noise = just_apply_noise

        tfconfig = tf.ConfigProto(allow_soft_placement=True)
        tfconfig.gpu_options.allow_growth = FLAGS.tf_allow_growth
        self.sess = tf.Session(config=tfconfig)
        with self.sess.as_default():
            self.attack_graph = AttackGraph(batch_size=batch_size, \
                                            image_height=FLAGS.image_height, \
                                            image_width=FLAGS.image_width, \
                                            image_channels=FLAGS.image_channels, \
                                            noise_initializer=get_noise_init_from_flags(), \
                                            num_classes=FLAGS.num_classes, \
                                            pixel_low=FLAGS.pixel_low, \
                                            pixel_high=FLAGS.pixel_high)

            if not self.just_apply_noise:
                self.losses_dict = None
                self.reg_losses = get_reg_losses_from_flags()
                self.optimization_op = self.attack_graph.build_everything(inception, \
                                            self.reg_losses, \
                                            epsilon=FLAGS.adam_epsilon, \
                                            beta1=FLAGS.adam_beta1, \
                                            beta2=FLAGS.adam_beta2)
                self.sess.run(self.attack_graph.init_adam)
                restore_model_vars(self.sess, self.attack_graph.model_vars, FLAGS.model_path)
                
                _, self.train_data = read_data_inception(FLAGS.attack_srcdir)
                _, self.val_data = read_data_inception(FLAGS.validation_set)

                self.saver = tf.train.Saver(max_to_keep=2, \
                                            var_list=[self.attack_graph.noise])
            
            restore_or_init_noise(self.sess, self.attack_graph, FLAGS.noise_restore_checkpoint) 
开发者ID:evtimovi,项目名称:robust_physical_perturbations,代码行数:36,代码来源:attack.py

示例14: calculate_acc

# 需要导入模块: from tensorflow.python.platform import app [as 别名]
# 或者: from tensorflow.python.platform.app import run [as 别名]
def calculate_acc(self):
        assert FLAGS.validation_set is not None
        assert self.val_data is not None

        val_feed_dict = self.create_feed_dict(np.array(self.val_data), self.attack_graph)

        net_predictions = self.sess.run(tf.argmax(self.attack_graph.adv_pred, axis=1), \
                                        feed_dict=val_feed_dict)
        labels = [FLAGS.attack_target for _ in range(len(net_predictions))]
        
        val_feed_dict = None
        gc.collect()

        return accuracy_score(labels, net_predictions, normalize=True) 
开发者ID:evtimovi,项目名称:robust_physical_perturbations,代码行数:16,代码来源:attack.py

示例15: extract_noise

# 需要导入模块: from tensorflow.python.platform import app [as 别名]
# 或者: from tensorflow.python.platform.app import run [as 别名]
def extract_noise(self, folder, fnames, data):
        feed_dict = self.create_feed_dict(data, self.attack_graph) 
        noisy_images = self.sess.run( \
                        tf.clip_by_value(self.attack_graph.noisy_inputs, FLAGS.pixel_low, FLAGS.pixel_high), \
                        feed_dict=feed_dict)

        save_folder = os.path.join(folder, "noisy_%s"%FLAGS.noise_restore_checkpoint)
        if not os.path.isdir(save_folder):
            os.makedirs(save_folder)
        
        for name, img in zip(fnames, noisy_images):
            fpath = os.path.join(save_folder, name)
            print("Writing %s"%fpath)
            write_reverse_preprocess_inception(fpath, img) 
开发者ID:evtimovi,项目名称:robust_physical_perturbations,代码行数:16,代码来源:attack.py


注:本文中的tensorflow.python.platform.app.run方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。