本文整理汇总了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()
示例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)
示例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))
示例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)
示例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)
示例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
示例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()
示例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
示例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)
示例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))
示例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
示例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)
示例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())]))
示例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)
示例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)