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


Python app.run方法代碼示例

本文整理匯總了Python中absl.app.run方法的典型用法代碼示例。如果您正苦於以下問題:Python app.run方法的具體用法?Python app.run怎麽用?Python app.run使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在absl.app的用法示例。


在下文中一共展示了app.run方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: DeployWebApp

# 需要導入模塊: from absl import app [as 別名]
# 或者: from absl.app import run [as 別名]
def DeployWebApp(self):
    """Bundle then deploy (or run locally) the web application."""
    self._BundleWebApp()

    if self.on_local:
      print('Run locally...')
    else:
      cmds = [
          'gcloud', 'app', 'deploy', '--no-promote', '--project={}'.format(
              self.project_id), '--version={}'.format(self.version)]
      for yaml_filename in self._yaml_files:
        cmds.append(self._GetYamlFile(yaml_filename))
      logging.info(
          'Deploying to the Google Cloud project: %s using gcloud...',
          self.project_id)
      _ExecuteCommand(cmds)

    if self.on_google_cloud_shell:
      self._CleanWebAppBackend() 
開發者ID:google,項目名稱:loaner,代碼行數:21,代碼來源:deploy_impl.py

示例2: _BuildChromeApp

# 需要導入模塊: from absl import app [as 別名]
# 或者: from absl.app import run [as 別名]
def _BuildChromeApp(self):
    """Build and bundle the Chrome App."""
    logging.debug('Building the Chrome Application...')
    self._ManifestCheck()
    os.chdir(self.npm_path)
    _ExecuteCommand(['npm', 'install'])
    _ExecuteCommand(['npm', 'run', 'build:chromeapp:once'])
    os.chdir(self.chrome_app_src_dir)
    if self.on_local:
      print('Local bundling coming soon...')
    else:
      logging.info('Zipping the Loaner Chrome Application...')
      _ZipRelativePath(
          self.chrome_app_temp_dir, _ZIPFILENAME, self.chrome_app_temp_dir)
      if os.path.isfile(self.chrome_app_archive):
        os.remove(self.chrome_app_archive)
      shutil.move(
          os.path.join(self.chrome_app_src_dir, _ZIPFILENAME),
          self.chrome_app_archive)
      logging.info(
          'The Loaner Chrome Application zip can be found %s',
          self.chrome_app_archive)
      logging.info('Removing the temp files for the Chrome App...')
      shutil.rmtree(self.chrome_app_temp_dir) 
開發者ID:google,項目名稱:loaner,代碼行數:26,代碼來源:deploy_impl.py

示例3: run

# 需要導入模塊: from absl import app [as 別名]
# 或者: from absl.app import run [as 別名]
def run(self):
    """Runs the Grab n Go manager."""
    try:
      while True:
        utils.clear_screen()
        utils.write('Which of the following actions would you like to take?\n')
        for opt in self._options.values():
          utils.write('Action: {!r}\nDescription: {}\n'.format(
              opt.name, opt.description))
        action = utils.prompt_enum(
            '', accepted_values=list(self._options.keys()),
            case_sensitive=False).strip().lower()
        callback = self._options[action].callback
        if callback is None:
          break
        self = callback()
    finally:
      utils.write(
          'Done managing Grab n Go for Cloud Project {!r}.'.format(
              self._config.project)) 
開發者ID:google,項目名稱:loaner,代碼行數:22,代碼來源:gng_impl.py

示例4: load_constants_from_storage

# 需要導入模塊: from absl import app [as 別名]
# 或者: from absl.app import run [as 別名]
def load_constants_from_storage(self):
    """Attempts to load constants from Google Cloud Storage."""
    try:
      constants = self._storage_api.get_blob(
          self._config.constants_storage_path,
          self._config.bucket,
      )
    except storage.NotFoundError as err:
      logging.error('Constants were not found in storage: %s', err)
    else:
      for name in self._constants.keys():
        try:
          self._constants[name].value = constants[name]
        except ValueError:
          logging.warning(
              'The value %r for %r stored in Google Cloud Storage does not meet'
              ' the requirements. Using the default value...',
              constants[name], name)
        except KeyError:
          logging.info(
              'The key %r was not found in the stored constants, this may be '
              'because a new constant was added since your most recent '
              'configuration. To resolve run `configure` in the main menu.',
              name) 
開發者ID:google,項目名稱:loaner,代碼行數:26,代碼來源:gng_impl.py

示例5: main

# 需要導入模塊: from absl import app [as 別名]
# 或者: from absl.app import run [as 別名]
def main(unused_argv):
  request = inference_flags.request_from_flags()

  if not gfile.Exists(request.segmentation_output_dir):
    gfile.MakeDirs(request.segmentation_output_dir)

  bbox = bounding_box_pb2.BoundingBox()
  text_format.Parse(FLAGS.bounding_box, bbox)

  runner = inference.Runner()
  runner.start(request)
  runner.run((bbox.start.z, bbox.start.y, bbox.start.x),
             (bbox.size.z, bbox.size.y, bbox.size.x))

  counter_path = os.path.join(request.segmentation_output_dir, 'counters.txt')
  if not gfile.Exists(counter_path):
    runner.counters.dump(counter_path) 
開發者ID:google,項目名稱:ffn,代碼行數:19,代碼來源:run_inference.py

示例6: run_training_step

# 需要導入模塊: from absl import app [as 別名]
# 或者: from absl.app import run [as 別名]
def run_training_step(sess, model, fetch_summary, feed_dict):
  """Runs one training step for a single FFN FOV."""
  ops_to_run = [model.train_op, model.global_step, model.logits]

  if fetch_summary is not None:
    ops_to_run.append(fetch_summary)

  results = sess.run(ops_to_run, feed_dict)
  step, prediction = results[1:3]

  if fetch_summary is not None:
    summ = results[-1]
  else:
    summ = None

  return prediction, step, summ 
開發者ID:google,項目名稱:ffn,代碼行數:18,代碼來源:train.py

示例7: main

# 需要導入模塊: from absl import app [as 別名]
# 或者: from absl.app import run [as 別名]
def main(positional_arguments):
  # Command-line arguments like '--distortions False' are equivalent to
  # '--distortions=True False', where False is a positional argument. To prevent
  # this from silently running with distortions, we do not allow positional
  # arguments.
  assert len(positional_arguments) >= 1
  if len(positional_arguments) > 1:
    raise ValueError('Received unknown positional arguments: %s'
                     % positional_arguments[1:])

  params = benchmark_cnn.make_params_from_flags()
  with mlperf.mlperf_logger(absl_flags.FLAGS.ml_perf_compliance_logging,
                            params.model):
    params = benchmark_cnn.setup(params)
    bench = benchmark_cnn.BenchmarkCNN(params)

    tfversion = cnn_util.tensorflow_version_tuple()
    log_fn('TensorFlow:  %i.%i' % (tfversion[0], tfversion[1]))

    bench.print_info()
    bench.run() 
開發者ID:tensorflow,項目名稱:benchmarks,代碼行數:23,代碼來源:tf_cnn_benchmarks.py

示例8: process

# 需要導入模塊: from absl import app [as 別名]
# 或者: from absl.app import run [as 別名]
def process(self, value):
    self._create_graph()
    elem_str = value.SerializeToString()

    b, bucket = self._sess.run([self._filtered_data, self._bucket],
                               feed_dict={self._elem: elem_str})
    if bucket > input_extractor.BUCKET_UPPER_BOUND:
      return
    b = py_utils.NestedMap(b)

    # Flatten the batch.
    flatten = b.FlattenItems()
    if not flatten:
      return

    num_boxes = b.bboxes_3d.shape[0]

    # For each box, get the pointcloud and write it as an example.
    for bbox_id in range(num_boxes):
      tf_example = self._ToTFExampleProto(b, bbox_id)
      yield tf_example 
開發者ID:tensorflow,項目名稱:lingvo,代碼行數:23,代碼來源:create_kitti_crop_dataset.py

示例9: main

# 需要導入模塊: from absl import app [as 別名]
# 或者: from absl.app import run [as 別名]
def main(argv):
  del argv  # Unused.
  line_format = ('--masks={masks} --output_dir={output_dir}')
  name = FLAGS.experiment

  for trial in range(1, 21):
    for level in range(0, 31):
      for run in range(1, 11):
        masks = paths.masks(constants.run(trial, level))
        output = constants.run(trial, level, name, run)
        result = line_format.format(masks=masks, output_dir=output)

        if FLAGS.experiment in ('reuse', 'reuse_sign'):
          result += (' --initialization_distribution=' +
                     constants.initialization(level))

        if FLAGS.experiment == 'reuse_sign':
          presets = paths.initial(constants.run(trial, level))
          result += ' --same_sign={}'.format(presets)

        print(result) 
開發者ID:google-research,項目名稱:lottery-ticket-hypothesis,代碼行數:23,代碼來源:reinitialize_argfile.py

示例10: config_with_absl

# 需要導入模塊: from absl import app [as 別名]
# 或者: from absl.app import run [as 別名]
def config_with_absl(self):
    # Run this before calling `app.run(main)` etc
    import absl.flags as absl_FLAGS
    from absl import app, flags as absl_flags

    self.use_absl = True
    self.absl_flags = absl_flags
    absl_defs = { bool: absl_flags.DEFINE_bool,
                  int:  absl_flags.DEFINE_integer,
                  str:  absl_flags.DEFINE_string,
                  'enum': absl_flags.DEFINE_enum }

    for name, val in self.values.items():
      flag_type, meta_args, meta_kwargs = self.meta[name]
      absl_defs[flag_type](name, val, *meta_args, **meta_kwargs)

    app.call_after_init(lambda: self.complete_absl_config(absl_flags)) 
開發者ID:google,項目名稱:trax,代碼行數:19,代碼來源:config.py

示例11: create_model

# 需要導入模塊: from absl import app [as 別名]
# 或者: from absl.app import run [as 別名]
def create_model(self):
    """Creates a TF model and returns ops necessary to run training/eval."""
    features = tf.compat.v1.placeholder(tf.float32, [None, self.input_dim])
    labels = tf.compat.v1.placeholder(tf.float32, [None, self.num_classes])

    w = tf.Variable(tf.random.normal(shape=[self.input_dim, self.num_classes]))
    b = tf.Variable(tf.random.normal(shape=[self.num_classes]))

    pred = tf.nn.softmax(tf.matmul(features, w) + b)

    loss = tf.reduce_mean(-tf.reduce_sum(labels * tf.math.log(pred), axis=1))
    train_op = self.optimizer.minimize(
        loss=loss, global_step=tf.train.get_or_create_global_step())

    correct_pred = tf.equal(tf.argmax(pred, 1), tf.argmax(labels, 1))
    eval_metric_op = tf.count_nonzero(correct_pred)

    return features, labels, train_op, loss, eval_metric_op 
開發者ID:tensorflow,項目名稱:federated,代碼行數:20,代碼來源:cyclic_bag_log_reg.py

示例12: log_config

# 需要導入模塊: from absl import app [as 別名]
# 或者: from absl.app import run [as 別名]
def log_config(logger):
  """Logs the configuration of this run, so it can be used in the analysis phase."""
  logger.log('== Configuration ==')
  logger.log('task_id=%d' % FLAGS.task_id)
  logger.log('lr=%f' % FLAGS.lr)
  logger.log('vocab_size=%s' % FLAGS.vocab_size)
  logger.log('batch_size=%s' % FLAGS.batch_size)
  logger.log('bow_limit=%s' % FLAGS.bow_limit)
  logger.log('training_data=%s' % FLAGS.training_data)
  logger.log('test_data=%s' % FLAGS.test_data)
  logger.log('num_groups=%d' % FLAGS.num_groups)
  logger.log('num_days=%d' % FLAGS.num_days)
  logger.log('num_train_examples_per_day=%d' % FLAGS.num_train_examples_per_day)
  logger.log('mode=%s' % FLAGS.mode)
  logger.log('bias=%f' % FLAGS.bias)
  logger.log('replica=%d' % FLAGS.replica) 
開發者ID:tensorflow,項目名稱:federated,代碼行數:18,代碼來源:cyclic_bag_log_reg.py

示例13: main

# 需要導入模塊: from absl import app [as 別名]
# 或者: from absl.app import run [as 別名]
def main(argv):
    del argv
    utils.setup_tf()
    nbatch = FLAGS.samples // FLAGS.batch
    dataset = data.DATASETS[FLAGS.dataset]()
    groups = [('labeled', dataset.train_labeled),
              ('unlabeled', dataset.train_unlabeled),
              ('test', dataset.test.repeat())]
    groups = [(name, ds.batch(FLAGS.batch).prefetch(16).make_one_shot_iterator().get_next())
              for name, ds in groups]
    with tf.train.MonitoredSession() as sess:
        for group, train_data in groups:
            stats = np.zeros(dataset.nclass, np.int32)
            minmax = [], []
            for _ in trange(nbatch, leave=False, unit='img', unit_scale=FLAGS.batch, desc=group):
                v = sess.run(train_data)['label']
                for u in v:
                    stats[u] += 1
                minmax[0].append(v.min())
                minmax[1].append(v.max())
            print(group)
            print('  Label range', min(minmax[0]), max(minmax[1]))
            print('  Stats', ' '.join(['%.2f' % (100 * x) for x in (stats / stats.max())])) 
開發者ID:uizard-technologies,項目名稱:realmix,代碼行數:25,代碼來源:inspect_dataset.py

示例14: run_graph

# 需要導入模塊: from absl import app [as 別名]
# 或者: from absl.app import run [as 別名]
def run_graph(master, graph_spec, epoch):
  """Run graph_spec.graph with master."""
  tf.logging.info("Running graph for epoch {}...".format(epoch))
  with tf.Session(master, graph_spec.graph) as sess:
    tf.logging.info("Initializing system for epoch {}...".format(epoch))
    sess.run(tpu.initialize_system(
        embedding_config=graph_spec.embedding.config_proto))

    tf.logging.info("Running before hook for epoch {}...".format(epoch))
    graph_spec.hook_before(sess, epoch)

    tf.logging.info("Running infeed for epoch {}...".format(epoch))
    infeed_thread_fn = graph_spec.get_infeed_thread_fn(sess)
    infeed_thread = threading.Thread(target=infeed_thread_fn)
    tf.logging.info("Staring infeed thread...")
    infeed_thread.start()

    tf.logging.info("Running TPU loop for epoch {}...".format(epoch))
    graph_spec.run_tpu_loop(sess, epoch)

    tf.logging.info("Joining infeed thread...")
    infeed_thread.join()

    tf.logging.info("Running after hook for epoch {}...".format(epoch))
    graph_spec.hook_after(sess, epoch) 
開發者ID:mlperf,項目名稱:training_results_v0.5,代碼行數:27,代碼來源:ncf_main.py

示例15: __init__

# 需要導入模塊: from absl import app [as 別名]
# 或者: from absl.app import run [as 別名]
def __init__(self):
    # Create a single Session to run all image coding calls.
    self._sess = tf.Session()

    # Initializes function that converts PNG to JPEG data.
    self._png_data = tf.placeholder(dtype=tf.string)
    image = tf.image.decode_png(self._png_data, channels=3)
    self._png_to_jpeg = tf.image.encode_jpeg(image, format='rgb', quality=100)

    # Initializes function that converts CMYK JPEG data to RGB JPEG data.
    self._cmyk_data = tf.placeholder(dtype=tf.string)
    image = tf.image.decode_jpeg(self._cmyk_data, channels=0)
    self._cmyk_to_rgb = tf.image.encode_jpeg(image, format='rgb', quality=100)

    # Initializes function that decodes RGB JPEG data.
    self._decode_jpeg_data = tf.placeholder(dtype=tf.string)
    self._decode_jpeg = tf.image.decode_jpeg(self._decode_jpeg_data, channels=3) 
開發者ID:mlperf,項目名稱:training_results_v0.5,代碼行數:19,代碼來源:imagenet_to_gcs.py


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