INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Evaluate model on Dataset for a number of steps. | def export(_):
FLAGS = tf.app.flags.FLAGS
"""Evaluate model on Dataset for a number of steps."""
#with tf.Graph().as_default():
tf.reset_default_graph()
def preprocess_image(image_buffer):
"""Preprocess JPEG encoded bytes to 3D float Tensor."""
# Decode the string as an RGB JPEG.
# Note that th... |
*DEPRECATED*. Allocates first available GPU using cudaSetDevice(), or returns 0 otherwise. | def _get_gpu():
"""*DEPRECATED*. Allocates first available GPU using cudaSetDevice(), or returns 0 otherwise."""
# Note: this code executes, but Tensorflow subsequently complains that the "current context was not created by the StreamExecutor cuda_driver API"
system = platform.system()
if system == "Linux":
... |
Get list of free GPUs according to nvidia-smi.
This will retry for ``MAX_RETRIES`` times until the requested number of GPUs are available.
Args:
:num_gpu: number of GPUs desired.
:worker_index: index "hint" for allocation of available GPUs.
Returns:
Comma-delimited string of GPU ids, or raises an E... | def get_gpus(num_gpu=1, worker_index=-1):
"""Get list of free GPUs according to nvidia-smi.
This will retry for ``MAX_RETRIES`` times until the requested number of GPUs are available.
Args:
:num_gpu: number of GPUs desired.
:worker_index: index "hint" for allocation of available GPUs.
Returns:
Co... |
Get available GPUs according to utilization thresholds.
Args:
:max_gpu_utilization: percent utilization threshold to consider a GPU "free"
:min_free_memory: percent free memory to consider a GPU "free"
:num_gpu: number of requested GPUs
Returns:
A tuple of (available_gpus, minimum_free_memory), wh... | def _get_free_gpu(max_gpu_utilization=40, min_free_memory=0.5, num_gpu=1):
"""Get available GPUs according to utilization thresholds.
Args:
:max_gpu_utilization: percent utilization threshold to consider a GPU "free"
:min_free_memory: percent free memory to consider a GPU "free"
:num_gpu: number of req... |
Build an Example proto for an example.
Args:
filename: string, path to an image file, e.g., '/path/to/example.JPG'
image_buffer: string, JPEG encoding of RGB image
label: integer, identifier for the ground truth for the network
text: string, unique human-readable, e.g. 'dog'
height: integer, imag... | def _convert_to_example(filename, image_buffer, label, text, height, width):
"""Build an Example proto for an example.
Args:
filename: string, path to an image file, e.g., '/path/to/example.JPG'
image_buffer: string, JPEG encoding of RGB image
label: integer, identifier for the ground truth for the net... |
Processes and saves list of images as TFRecord in 1 thread.
Args:
coder: instance of ImageCoder to provide TensorFlow image coding utils.
thread_index: integer, unique batch to run index is within [0, len(ranges)).
ranges: list of pairs of integers specifying ranges of each batches to
analyze in pa... | def _process_image_files_batch(coder, thread_index, ranges, name, filenames,
texts, labels, num_shards):
"""Processes and saves list of images as TFRecord in 1 thread.
Args:
coder: instance of ImageCoder to provide TensorFlow image coding utils.
thread_index: integer, unique ... |
Process and save list of images as TFRecord of Example protos.
Args:
name: string, unique identifier specifying the data set
filenames: list of strings; each string is a path to an image file
texts: list of strings; each string is human readable, e.g. 'dog'
labels: list of integer; each integer ident... | def _process_image_files(name, filenames, texts, labels, num_shards):
"""Process and save list of images as TFRecord of Example protos.
Args:
name: string, unique identifier specifying the data set
filenames: list of strings; each string is a path to an image file
texts: list of strings; each string is... |
Build a list of all images files and labels in the data set.
Args:
data_dir: string, path to the root directory of images.
Assumes that the image data set resides in JPEG files located in
the following directory structure.
data_dir/dog/another-image.JPEG
data_dir/dog/my-image.jpg
... | def _find_image_files(data_dir, labels_file):
"""Build a list of all images files and labels in the data set.
Args:
data_dir: string, path to the root directory of images.
Assumes that the image data set resides in JPEG files located in
the following directory structure.
data_dir/dog/anot... |
Process a complete data set and save it as a TFRecord.
Args:
name: string, unique identifier specifying the data set.
directory: string, root path to the data set.
num_shards: integer number of shards for this data set.
labels_file: string, path to the labels file. | def _process_dataset(name, directory, num_shards, labels_file):
"""Process a complete data set and save it as a TFRecord.
Args:
name: string, unique identifier specifying the data set.
directory: string, root path to the data set.
num_shards: integer number of shards for this data set.
labels_file:... |
Generate batches of ImageNet images for evaluation.
Use this function as the inputs for evaluating a network.
Note that some (minimal) image preprocessing occurs during evaluation
including central cropping and resizing of the image to fit the network.
Args:
dataset: instance of Dataset class specifying ... | def inputs(dataset, batch_size=None, num_preprocess_threads=None):
"""Generate batches of ImageNet images for evaluation.
Use this function as the inputs for evaluating a network.
Note that some (minimal) image preprocessing occurs during evaluation
including central cropping and resizing of the image to fit ... |
Generate batches of distorted versions of ImageNet images.
Use this function as the inputs for training a network.
Distorting images provides a useful technique for augmenting the data
set during training in order to make the network invariant to aspects
of the image that do not effect the label.
Args:
... | def distorted_inputs(dataset, batch_size=None, num_preprocess_threads=None):
"""Generate batches of distorted versions of ImageNet images.
Use this function as the inputs for training a network.
Distorting images provides a useful technique for augmenting the data
set during training in order to make the netw... |
Decode a JPEG string into one 3-D float image Tensor.
Args:
image_buffer: scalar string Tensor.
scope: Optional scope for name_scope.
Returns:
3-D float Tensor with values ranging from [0, 1). | def decode_jpeg(image_buffer, scope=None):
"""Decode a JPEG string into one 3-D float image Tensor.
Args:
image_buffer: scalar string Tensor.
scope: Optional scope for name_scope.
Returns:
3-D float Tensor with values ranging from [0, 1).
"""
with tf.name_scope(values=[image_buffer], name=scope,
... |
Distort the color of the image.
Each color distortion is non-commutative and thus ordering of the color ops
matters. Ideally we would randomly permute the ordering of the color ops.
Rather then adding that level of complication, we select a distinct ordering
of color ops for each preprocessing thread.
Args:... | def distort_color(image, thread_id=0, scope=None):
"""Distort the color of the image.
Each color distortion is non-commutative and thus ordering of the color ops
matters. Ideally we would randomly permute the ordering of the color ops.
Rather then adding that level of complication, we select a distinct orderin... |
Distort one image for training a network.
Distorting images provides a useful technique for augmenting the data
set during training in order to make the network invariant to aspects
of the image that do not effect the label.
Args:
image: 3-D float Tensor of image
height: integer
width: integer
... | def distort_image(image, height, width, bbox, thread_id=0, scope=None):
"""Distort one image for training a network.
Distorting images provides a useful technique for augmenting the data
set during training in order to make the network invariant to aspects
of the image that do not effect the label.
Args:
... |
Prepare one image for evaluation.
Args:
image: 3-D float Tensor
height: integer
width: integer
scope: Optional scope for name_scope.
Returns:
3-D float Tensor of prepared image. | def eval_image(image, height, width, scope=None):
"""Prepare one image for evaluation.
Args:
image: 3-D float Tensor
height: integer
width: integer
scope: Optional scope for name_scope.
Returns:
3-D float Tensor of prepared image.
"""
with tf.name_scope(values=[image, height, width], name... |
Decode and preprocess one image for evaluation or training.
Args:
image_buffer: JPEG encoded string Tensor
bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords]
where each coordinate is [0, 1) and the coordinates are arranged as
[ymin, xmin, ymax, xmax].
train: boolean
... | def image_preprocessing(image_buffer, bbox, train, thread_id=0):
"""Decode and preprocess one image for evaluation or training.
Args:
image_buffer: JPEG encoded string Tensor
bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords]
where each coordinate is [0, 1) and the coordinates a... |
Parses an Example proto containing a training example of an image.
The output of the build_image_data.py image preprocessing script is a dataset
containing serialized Example protocol buffers. Each Example proto contains
the following fields:
image/height: 462
image/width: 581
image/colorspace: 'RGB... | def parse_example_proto(example_serialized):
"""Parses an Example proto containing a training example of an image.
The output of the build_image_data.py image preprocessing script is a dataset
containing serialized Example protocol buffers. Each Example proto contains
the following fields:
image/height: 4... |
Contruct batches of training or evaluation examples from the image dataset.
Args:
dataset: instance of Dataset class specifying the dataset.
See dataset.py for details.
batch_size: integer
train: boolean
num_preprocess_threads: integer, total number of preprocessing threads
num_readers: int... | def batch_inputs(dataset, batch_size, train, num_preprocess_threads=None,
num_readers=1):
"""Contruct batches of training or evaluation examples from the image dataset.
Args:
dataset: instance of Dataset class specifying the dataset.
See dataset.py for details.
batch_size: integer
... |
Download external libraries from PyPI to SPARK_EC2_DIR/lib/ and prepend them to our PATH. | def setup_external_libs(libs):
"""
Download external libraries from PyPI to SPARK_EC2_DIR/lib/ and prepend them to our PATH.
"""
PYPI_URL_PREFIX = "https://pypi.python.org/packages/source"
SPARK_EC2_LIB_DIR = os.path.join(SPARK_EC2_DIR, "lib")
if not os.path.exists(SPARK_EC2_LIB_DIR):
p... |
Get the EC2 instances in an existing cluster if available.
Returns a tuple of lists of EC2 instance objects for the masters and slaves. | def get_existing_cluster(conn, opts, cluster_name, die_on_error=True):
"""
Get the EC2 instances in an existing cluster if available.
Returns a tuple of lists of EC2 instance objects for the masters and slaves.
"""
print("Searching for existing cluster {c} in region {r}...".format(
c=clust... |
Check if SSH is available on a host. | def is_ssh_available(host, opts, print_ssh_output=True):
"""
Check if SSH is available on a host.
"""
s = subprocess.Popen(
ssh_command(opts) + ['-t', '-t', '-o', 'ConnectTimeout=3',
'%s@%s' % (opts.user, host), stringify_command('true')],
stdout=subprocess.P... |
Check if SSH is available on all the instances in a cluster. | def is_cluster_ssh_available(cluster_instances, opts):
"""
Check if SSH is available on all the instances in a cluster.
"""
for i in cluster_instances:
dns_name = get_dns_name(i, opts.private_ips)
if not is_ssh_available(host=dns_name, opts=opts):
return False
else:
... |
Wait for all the instances in the cluster to reach a designated state.
cluster_instances: a list of boto.ec2.instance.Instance
cluster_state: a string representing the desired state of all the instances in the cluster
value can be 'ssh-ready' or a valid value from boto.ec2.instance.InstanceState suc... | def wait_for_cluster_state(conn, opts, cluster_instances, cluster_state):
"""
Wait for all the instances in the cluster to reach a designated state.
cluster_instances: a list of boto.ec2.instance.Instance
cluster_state: a string representing the desired state of all the instances in the cluster
... |
Instruction to download and extract the tarball from Flowers website. | def download_message(self):
"""Instruction to download and extract the tarball from Flowers website."""
print('Failed to find any ImageNet %s files'% self.subset)
print('')
print('If you have already downloaded and processed the data, then make '
'sure to set --data_dir to point to the direct... |
Add supervised learning flags, as well as wide-deep model type. | def define_wide_deep_flags():
"""Add supervised learning flags, as well as wide-deep model type."""
flags_core.define_base()
flags_core.define_benchmark()
flags_core.define_performance(
num_parallel_calls=False, inter_op=True, intra_op=True,
synthetic_data=False, max_train_steps=False, dtype=False,
... |
Export to SavedModel format.
Args:
model: Estimator object
model_type: string indicating model type. "wide", "deep" or "wide_deep"
export_dir: directory to export the model.
model_column_fn: Function to generate model feature columns. | def export_model(model, model_type, export_dir, model_column_fn):
"""Export to SavedModel format.
Args:
model: Estimator object
model_type: string indicating model type. "wide", "deep" or "wide_deep"
export_dir: directory to export the model.
model_column_fn: Function to generate model feature colu... |
Define training loop. | def run_loop(name, train_input_fn, eval_input_fn, model_column_fn,
build_estimator_fn, flags_obj, tensors_to_log, early_stop=False):
"""Define training loop."""
model_helpers.apply_clean(flags.FLAGS)
model = build_estimator_fn(
model_dir=flags_obj.model_dir, model_type=flags_obj.model_type,
... |
Calculate the total loss on a single tower running the ImageNet model.
We perform 'batch splitting'. This means that we cut up a batch across
multiple GPU's. For instance, if the batch size = 32 and num_gpus = 2,
then each tower will operate on an batch of 16 images.
Args:
images: Images. 4D tensor of siz... | def _tower_loss(images, labels, num_classes, scope, reuse_variables=None):
"""Calculate the total loss on a single tower running the ImageNet model.
We perform 'batch splitting'. This means that we cut up a batch across
multiple GPU's. For instance, if the batch size = 32 and num_gpus = 2,
then each tower will... |
Train on dataset for a number of steps. | def train(dataset):
"""Train on dataset for a number of steps."""
with tf.Graph().as_default(), tf.device('/cpu:0'):
# Create a variable to count the number of train() calls. This equals the
# number of batches processed * FLAGS.num_gpus.
global_step = tf.get_variable(
'global_step', [],
... |
Adds a Batch Normalization layer.
Args:
inputs: a tensor of size [batch_size, height, width, channels]
or [batch_size, channels].
decay: decay for the moving average.
center: If True, subtract beta. If False, beta is not created and ignored.
scale: If True, multiply by gamma. If False, ga... | def batch_norm(inputs,
decay=0.999,
center=True,
scale=False,
epsilon=0.001,
moving_vars='moving_vars',
activation=None,
is_training=True,
trainable=True,
restore=True,
s... |
Converts `int_or_tuple` to height, width.
Several of the functions that follow accept arguments as either
a tuple of 2 integers or a single integer. A single integer
indicates that the 2 values of the tuple are the same.
This functions normalizes the input value by always returning a tuple.
Args:
int_... | def _two_element_tuple(int_or_tuple):
"""Converts `int_or_tuple` to height, width.
Several of the functions that follow accept arguments as either
a tuple of 2 integers or a single integer. A single integer
indicates that the 2 values of the tuple are the same.
This functions normalizes the input value by ... |
Adds a 2D convolution followed by an optional batch_norm layer.
conv2d creates a variable called 'weights', representing the convolutional
kernel, that is convolved with the input. If `batch_norm_params` is None, a
second variable called 'biases' is added to the result of the convolution
operation.
Args:
... | def conv2d(inputs,
num_filters_out,
kernel_size,
stride=1,
padding='SAME',
activation=tf.nn.relu,
stddev=0.01,
bias=0.0,
weight_decay=0,
batch_norm_params=None,
is_training=True,
trainable=True,
... |
Transform numeric labels into onehot_labels.
Args:
labels: [batch_size] target labels.
num_classes: total number of classes.
scope: Optional scope for name_scope.
Returns:
one hot encoding of the labels. | def one_hot_encoding(labels, num_classes, scope=None):
"""Transform numeric labels into onehot_labels.
Args:
labels: [batch_size] target labels.
num_classes: total number of classes.
scope: Optional scope for name_scope.
Returns:
one hot encoding of the labels.
"""
with tf.name_scope(scope, '... |
Adds a Max Pooling layer.
It is assumed by the wrapper that the pooling is only done per image and not
in depth or batch.
Args:
inputs: a tensor of size [batch_size, height, width, depth].
kernel_size: a list of length 2: [kernel_height, kernel_width] of the
pooling kernel over which the op is com... | def max_pool(inputs, kernel_size, stride=2, padding='VALID', scope=None):
"""Adds a Max Pooling layer.
It is assumed by the wrapper that the pooling is only done per image and not
in depth or batch.
Args:
inputs: a tensor of size [batch_size, height, width, depth].
kernel_size: a list of length 2: [ke... |
Returns a dropout layer applied to the input.
Args:
inputs: the tensor to pass to the Dropout layer.
keep_prob: the probability of keeping each input unit.
is_training: whether or not the model is in training mode. If so, dropout is
applied and values scaled. Otherwise, inputs is returned.
scope:... | def dropout(inputs, keep_prob=0.5, is_training=True, scope=None):
"""Returns a dropout layer applied to the input.
Args:
inputs: the tensor to pass to the Dropout layer.
keep_prob: the probability of keeping each input unit.
is_training: whether or not the model is in training mode. If so, dropout is
... |
Flattens the input while maintaining the batch_size.
Assumes that the first dimension represents the batch.
Args:
inputs: a tensor of size [batch_size, ...].
scope: Optional scope for name_scope.
Returns:
a flattened tensor with shape [batch_size, k].
Raises:
ValueError: if inputs.shape is ... | def flatten(inputs, scope=None):
"""Flattens the input while maintaining the batch_size.
Assumes that the first dimension represents the batch.
Args:
inputs: a tensor of size [batch_size, ...].
scope: Optional scope for name_scope.
Returns:
a flattened tensor with shape [batch_size, k].
Raise... |
Build a sequential Tower starting from inputs by using an op repeatedly.
It creates new scopes for each operation by increasing the counter.
Example: given repeat_op(3, _, ops.conv2d, 64, [3, 3], scope='conv1')
it will repeat the given op under the following variable_scopes:
conv1/Conv
conv1/Conv_1... | def repeat_op(repetitions, inputs, op, *args, **kwargs):
"""Build a sequential Tower starting from inputs by using an op repeatedly.
It creates new scopes for each operation by increasing the counter.
Example: given repeat_op(3, _, ops.conv2d, 64, [3, 3], scope='conv1')
it will repeat the given op under the ... |
Wraps a given RPC function by producing an awaitable function suitable to be run in the asyncio
event loop. The wrapped function catches all unhandled exceptions and reports them to the exception
future, which consumers can await upon to listen for unhandled exceptions.
The wrapped function als... | def do_rpc(self, name: str, rpc_function: Callable[..., Awaitable[None]]) -> Callable[..., Awaitable[None]]:
"""
Wraps a given RPC function by producing an awaitable function suitable to be run in the asyncio
event loop. The wrapped function catches all unhandled exceptions and reports them to t... |
registerResource registers a new resource object with a given type t and name. It returns the auto-generated
URN and the ID that will resolve after the deployment has completed. All properties will be initialized to property
objects that the registration operation will resolve at the right time (or remain unr... | def register_resource(res: 'Resource', ty: str, name: str, custom: bool, props: 'Inputs', opts: Optional['ResourceOptions']):
"""
registerResource registers a new resource object with a given type t and name. It returns the auto-generated
URN and the ID that will resolve after the deployment has completed.... |
Configure sets the current ambient settings bag to the one given. | def configure(settings: Settings):
"""
Configure sets the current ambient settings bag to the one given.
"""
if not settings or not isinstance(settings, Settings):
raise TypeError('Settings is expected to be non-None and of type Settings')
global SETTINGS # pylint: disable=global-statement
... |
Returns the current project name. | def get_project() -> Optional[str]:
"""
Returns the current project name.
"""
project = SETTINGS.project
if not project:
require_test_mode_enabled()
raise RunError('Missing project name; for test mode, please set PULUMI_NODEJS_PROJECT')
return project |
Returns the current stack name. | def get_stack() -> Optional[str]:
"""
Returns the current stack name.
"""
stack = SETTINGS.stack
if not stack:
require_test_mode_enabled()
raise RunError('Missing stack name; for test mode, please set PULUMI_NODEJS_STACK')
return stack |
Returns the current resource monitoring service client for RPC communications. | def get_monitor() -> Optional[resource_pb2_grpc.ResourceMonitorStub]:
"""
Returns the current resource monitoring service client for RPC communications.
"""
monitor = SETTINGS.monitor
if not monitor:
require_test_mode_enabled()
return monitor |
Serializes an arbitrary Input bag into a Protobuf structure, keeping track of the list
of dependent resources in the `deps` list. Serializing properties is inherently async
because it awaits any futures that are contained transitively within the input bag. | async def serialize_properties(inputs: 'Inputs',
property_deps: Dict[str, List['Resource']],
input_transformer: Optional[Callable[[str], str]] = None) -> struct_pb2.Struct:
"""
Serializes an arbitrary Input bag into a Protobuf structure, keeping trac... |
Serializes a single Input into a form suitable for remoting to the engine, awaiting
any futures required to do so. | async def serialize_property(value: 'Input[Any]',
deps: List['Resource'],
input_transformer: Optional[Callable[[str], str]] = None) -> Any:
"""
Serializes a single Input into a form suitable for remoting to the engine, awaiting
any futures required t... |
Deserializes a protobuf `struct_pb2.Struct` into a Python dictionary containing normal
Python types. | def deserialize_properties(props_struct: struct_pb2.Struct) -> Any:
"""
Deserializes a protobuf `struct_pb2.Struct` into a Python dictionary containing normal
Python types.
"""
# Check out this link for details on what sort of types Protobuf is going to generate:
# https://developers.google.com/... |
Deserializes a single protobuf value (either `Struct` or `ListValue`) into idiomatic
Python values. | def deserialize_property(value: Any) -> Any:
"""
Deserializes a single protobuf value (either `Struct` or `ListValue`) into idiomatic
Python values.
"""
if value == UNKNOWN:
return None
# ListValues are projected to lists
if isinstance(value, struct_pb2.ListValue):
return [d... |
Recursively rewrite keys of objects returned by the engine to conform with a naming
convention specified by the resource's implementation of `translate_output_property`.
If output is a `dict`, every key is translated using `translate_output_property` while every value is transformed
by recursing.
If o... | def translate_output_properties(res: 'Resource', output: Any) -> Any:
"""
Recursively rewrite keys of objects returned by the engine to conform with a naming
convention specified by the resource's implementation of `translate_output_property`.
If output is a `dict`, every key is translated using `trans... |
Resolves all outputs with resolvers exceptionally, using the given exception as the reason why the resolver has
failed to resolve.
:param resolvers: Resolvers associated with a resource's outputs.
:param exn: The exception that occured when trying (and failing) to create this resource. | def resolve_outputs_due_to_exception(resolvers: Dict[str, Resolver], exn: Exception):
"""
Resolves all outputs with resolvers exceptionally, using the given exception as the reason why the resolver has
failed to resolve.
:param resolvers: Resolvers associated with a resource's outputs.
:param exn: ... |
Returns an optional configuration value by its key, or None if it doesn't exist.
:param str key: The requested configuration key.
:return: The configuration key's value, or None if one does not exist.
:rtype: Optional[str] | def get(self, key: str) -> Optional[str]:
"""
Returns an optional configuration value by its key, or None if it doesn't exist.
:param str key: The requested configuration key.
:return: The configuration key's value, or None if one does not exist.
:rtype: Optional[str]
""... |
Returns an optional configuration value, as a bool, by its key, or None if it doesn't exist.
If the configuration value isn't a legal boolean, this function will throw an error.
:param str key: The requested configuration key.
:return: The configuration key's value, or None if one does not exis... | def get_bool(self, key: str) -> Optional[bool]:
"""
Returns an optional configuration value, as a bool, by its key, or None if it doesn't exist.
If the configuration value isn't a legal boolean, this function will throw an error.
:param str key: The requested configuration key.
... |
Returns an optional configuration value, as an int, by its key, or None if it doesn't exist.
If the configuration value isn't a legal int, this function will throw an error.
:param str key: The requested configuration key.
:return: The configuration key's value, or None if one does not exist.
... | def get_int(self, key: str) -> Optional[int]:
"""
Returns an optional configuration value, as an int, by its key, or None if it doesn't exist.
If the configuration value isn't a legal int, this function will throw an error.
:param str key: The requested configuration key.
:retur... |
Returns an optional configuration value, as a float, by its key, or None if it doesn't exist.
If the configuration value isn't a legal float, this function will throw an error.
:param str key: The requested configuration key.
:return: The configuration key's value, or None if one does not exist... | def get_float(self, key: str) -> Optional[float]:
"""
Returns an optional configuration value, as a float, by its key, or None if it doesn't exist.
If the configuration value isn't a legal float, this function will throw an error.
:param str key: The requested configuration key.
... |
Returns a configuration value by its given key. If it doesn't exist, an error is thrown.
:param str key: The requested configuration key.
:return: The configuration key's value.
:rtype: str
:raises ConfigMissingError: The configuration value did not exist. | def require(self, key: str) -> str:
"""
Returns a configuration value by its given key. If it doesn't exist, an error is thrown.
:param str key: The requested configuration key.
:return: The configuration key's value.
:rtype: str
:raises ConfigMissingError: The configur... |
Returns a configuration value, as a bool, by its given key. If it doesn't exist, or the
configuration value is not a legal bool, an error is thrown.
:param str key: The requested configuration key.
:return: The configuration key's value.
:rtype: bool
:raises ConfigMissingError:... | def require_bool(self, key: str) -> bool:
"""
Returns a configuration value, as a bool, by its given key. If it doesn't exist, or the
configuration value is not a legal bool, an error is thrown.
:param str key: The requested configuration key.
:return: The configuration key's v... |
Returns a configuration value, as an int, by its given key. If it doesn't exist, or the
configuration value is not a legal int, an error is thrown.
:param str key: The requested configuration key.
:return: The configuration key's value.
:rtype: int
:raises ConfigMissingError: T... | def require_int(self, key: str) -> int:
"""
Returns a configuration value, as an int, by its given key. If it doesn't exist, or the
configuration value is not a legal int, an error is thrown.
:param str key: The requested configuration key.
:return: The configuration key's valu... |
Returns a configuration value, as a float, by its given key. If it doesn't exist, or the
configuration value is not a legal number, an error is thrown.
:param str key: The requested configuration key.
:return: The configuration key's value.
:rtype: float
:raises ConfigMissingEr... | def require_float(self, key: str) -> float:
"""
Returns a configuration value, as a float, by its given key. If it doesn't exist, or the
configuration value is not a legal number, an error is thrown.
:param str key: The requested configuration key.
:return: The configuration ke... |
Decorator to annotate the Asset class. Registers the decorated class
as the Asset known type. | def asset(class_obj: type) -> type:
"""
Decorator to annotate the Asset class. Registers the decorated class
as the Asset known type.
"""
assert isinstance(class_obj, type), "class_obj is not a Class"
global _asset_resource_type
_asset_resource_type = class_obj
return class_obj |
Decorator to annotate the FileAsset class. Registers the decorated class
as the FileAsset known type. | def file_asset(class_obj: type) -> type:
"""
Decorator to annotate the FileAsset class. Registers the decorated class
as the FileAsset known type.
"""
assert isinstance(class_obj, type), "class_obj is not a Class"
global _file_asset_resource_type
_file_asset_resource_type = class_obj
ret... |
Decorator to annotate the StringAsset class. Registers the decorated class
as the StringAsset known type. | def string_asset(class_obj: type) -> type:
"""
Decorator to annotate the StringAsset class. Registers the decorated class
as the StringAsset known type.
"""
assert isinstance(class_obj, type), "class_obj is not a Class"
global _string_asset_resource_type
_string_asset_resource_type = class_o... |
Decorator to annotate the RemoteAsset class. Registers the decorated class
as the RemoteAsset known type. | def remote_asset(class_obj: type) -> type:
"""
Decorator to annotate the RemoteAsset class. Registers the decorated class
as the RemoteAsset known type.
"""
assert isinstance(class_obj, type), "class_obj is not a Class"
global _remote_asset_resource_type
_remote_asset_resource_type = class_o... |
Decorator to annotate the Archive class. Registers the decorated class
as the Archive known type. | def archive(class_obj: type) -> type:
"""
Decorator to annotate the Archive class. Registers the decorated class
as the Archive known type.
"""
assert isinstance(class_obj, type), "class_obj is not a Class"
global _archive_resource_type
_archive_resource_type = class_obj
return class_obj |
Decorator to annotate the AssetArchive class. Registers the decorated class
as the AssetArchive known type. | def asset_archive(class_obj: type) -> type:
"""
Decorator to annotate the AssetArchive class. Registers the decorated class
as the AssetArchive known type.
"""
assert isinstance(class_obj, type), "class_obj is not a Class"
global _asset_archive_resource_type
_asset_archive_resource_type = cl... |
Decorator to annotate the FileArchive class. Registers the decorated class
as the FileArchive known type. | def file_archive(class_obj: type) -> type:
"""
Decorator to annotate the FileArchive class. Registers the decorated class
as the FileArchive known type.
"""
assert isinstance(class_obj, type), "class_obj is not a Class"
global _file_archive_resource_type
_file_archive_resource_type = class_o... |
Decorator to annotate the RemoteArchive class. Registers the decorated class
as the RemoteArchive known type. | def remote_archive(class_obj: type) -> type:
"""
Decorator to annotate the RemoteArchive class. Registers the decorated class
as the RemoteArchive known type.
"""
assert isinstance(class_obj, type), "class_obj is not a Class"
global _remote_archive_resource_type
_remote_archive_resource_type... |
Decorator to annotate the CustomResource class. Registers the decorated class
as the CustomResource known type. | def custom_resource(class_obj: type) -> type:
"""
Decorator to annotate the CustomResource class. Registers the decorated class
as the CustomResource known type.
"""
assert isinstance(class_obj, type), "class_obj is not a Class"
global _custom_resource_type
_custom_resource_type = class_obj
... |
Logs a message to the Pulumi CLI's debug channel, associating it with a resource
and stream_id if provided.
:param str msg: The message to send to the Pulumi CLI.
:param Optional[Resource] resource: If provided, associate this message with the given resource in the Pulumi CLI.
:param Optional[int] stre... | def debug(msg: str, resource: Optional['Resource'] = None, stream_id: Optional[int] = None) -> None:
"""
Logs a message to the Pulumi CLI's debug channel, associating it with a resource
and stream_id if provided.
:param str msg: The message to send to the Pulumi CLI.
:param Optional[Resource] resou... |
Logs a message to the Pulumi CLI's info channel, associating it with a resource
and stream_id if provided.
:param str msg: The message to send to the Pulumi CLI.
:param Optional[Resource] resource: If provided, associate this message with the given resource in the Pulumi CLI.
:param Optional[int] strea... | def info(msg: str, resource: Optional['Resource'] = None, stream_id: Optional[int] = None) -> None:
"""
Logs a message to the Pulumi CLI's info channel, associating it with a resource
and stream_id if provided.
:param str msg: The message to send to the Pulumi CLI.
:param Optional[Resource] resourc... |
Logs a message to the Pulumi CLI's warning channel, associating it with a resource
and stream_id if provided.
:param str msg: The message to send to the Pulumi CLI.
:param Optional[Resource] resource: If provided, associate this message with the given resource in the Pulumi CLI.
:param Optional[int] st... | def warn(msg: str, resource: Optional['Resource'] = None, stream_id: Optional[int] = None) -> None:
"""
Logs a message to the Pulumi CLI's warning channel, associating it with a resource
and stream_id if provided.
:param str msg: The message to send to the Pulumi CLI.
:param Optional[Resource] reso... |
Logs a message to the Pulumi CLI's error channel, associating it with a resource
and stream_id if provided.
:param str msg: The message to send to the Pulumi CLI.
:param Optional[Resource] resource: If provided, associate this message with the given resource in the Pulumi CLI.
:param Optional[int] stre... | def error(msg: str, resource: Optional['Resource'] = None, stream_id: Optional[int] = None):
"""
Logs a message to the Pulumi CLI's error channel, associating it with a resource
and stream_id if provided.
:param str msg: The message to send to the Pulumi CLI.
:param Optional[Resource] resource: If ... |
Returns the environment map that will be used for config checking when variables aren't set. | def get_config_env() -> Dict[str, Any]:
"""
Returns the environment map that will be used for config checking when variables aren't set.
"""
if 'PULUMI_CONFIG' in os.environ:
env_config = os.environ['PULUMI_CONFIG']
return json.loads(env_config)
return dict() |
Returns a scrubbed environment variable key, PULUMI_CONFIG_<k>, that can be used for
setting explicit varaibles. This is unlike PULUMI_CONFIG which is just a JSON-serialized bag. | def get_config_env_key(k: str) -> str:
"""
Returns a scrubbed environment variable key, PULUMI_CONFIG_<k>, that can be used for
setting explicit varaibles. This is unlike PULUMI_CONFIG which is just a JSON-serialized bag.
"""
env_key = ''
for c in k:
if c == '_' or 'A' <= c <= 'Z' or '0... |
Returns a configuration variable's value or None if it is unset. | def get_config(k: str) -> Any:
"""
Returns a configuration variable's value or None if it is unset.
"""
# If the config has been set explicitly, use it.
if k in list(CONFIG.keys()):
return CONFIG[k]
# If there is a specific PULUMI_CONFIG_<k> environment variable, use it.
env_key = g... |
Run the given function inside of a new stack resource. This ensures that any stack export calls will end
up as output properties on the resulting stack component in the checkpoint file. This is meant for internal
runtime use only and is used by the Python SDK entrypoint program. | async def run_in_stack(func: Callable):
"""
Run the given function inside of a new stack resource. This ensures that any stack export calls will end
up as output properties on the resulting stack component in the checkpoint file. This is meant for internal
runtime use only and is used by the Python SD... |
Export a stack output with a given name and value. | def output(self, name: str, value: Any):
"""
Export a stack output with a given name and value.
"""
self.outputs[name] = value |
invoke dynamically invokes the function, tok, which is offered by a provider plugin. The inputs
can be a bag of computed values (Ts or Awaitable[T]s), and the result is a Awaitable[Any] that
resolves when the invoke finishes. | def invoke(tok: str, props: Inputs, opts: InvokeOptions = None) -> Awaitable[Any]:
"""
invoke dynamically invokes the function, tok, which is offered by a provider plugin. The inputs
can be a bag of computed values (Ts or Awaitable[T]s), and the result is a Awaitable[Any] that
resolves when the invoke ... |
Exports a named stack output.
:param str name: The name to assign to this output.
:param Any value: The value of this output. | def export(name: str, value: Any):
"""
Exports a named stack output.
:param str name: The name to assign to this output.
:param Any value: The value of this output.
"""
stack = get_root_resource()
if stack is not None:
stack.output(name, value) |
Fetches the provider for the given module member, if this resource has been provided a specific
provider for the given module member.
Returns None if no provider was provided.
:param str module_member: The requested module member.
:return: The :class:`ProviderResource` associated with ... | def get_provider(self, module_member: str) -> Optional['ProviderResource']:
"""
Fetches the provider for the given module member, if this resource has been provided a specific
provider for the given module member.
Returns None if no provider was provided.
:param str module_memb... |
Add an event handler to be executed when the specified event is fired.
Args:
event_name: An event to attach the handler to. Valid events are from :class:`~ignite.engine.Events`
or any `event_name` added by :meth:`~ignite.engine.Engine.register_events`.
handler (callable)... | def add_event_handler(self, event_name, handler, *args, **kwargs):
"""Add an event handler to be executed when the specified event is fired.
Args:
event_name: An event to attach the handler to. Valid events are from :class:`~ignite.engine.Events`
or any `event_name` added by... |
Check if the specified event has the specified handler.
Args:
handler (callable): the callable event handler.
event_name: The event the handler attached to. Set this
to ``None`` to search all events. | def has_event_handler(self, handler, event_name=None):
"""Check if the specified event has the specified handler.
Args:
handler (callable): the callable event handler.
event_name: The event the handler attached to. Set this
to ``None`` to search all events.
... |
Remove event handler `handler` from registered handlers of the engine
Args:
handler (callable): the callable event handler that should be removed
event_name: The event the handler attached to. | def remove_event_handler(self, handler, event_name):
"""Remove event handler `handler` from registered handlers of the engine
Args:
handler (callable): the callable event handler that should be removed
event_name: The event the handler attached to.
"""
if event_... |
Decorator shortcut for add_event_handler.
Args:
event_name: An event to attach the handler to. Valid events are from :class:`~ignite.engine.Events` or
any `event_name` added by :meth:`~ignite.engine.Engine.register_events`.
*args: optional args to be passed to `handler`.... | def on(self, event_name, *args, **kwargs):
"""Decorator shortcut for add_event_handler.
Args:
event_name: An event to attach the handler to. Valid events are from :class:`~ignite.engine.Events` or
any `event_name` added by :meth:`~ignite.engine.Engine.register_events`.
... |
Execute all the handlers associated with given event.
This method executes all handlers associated with the event
`event_name`. Optional positional and keyword arguments can be used to
pass arguments to **all** handlers added with this event. These
aguments updates arguments passed usin... | def _fire_event(self, event_name, *event_args, **event_kwargs):
"""Execute all the handlers associated with given event.
This method executes all handlers associated with the event
`event_name`. Optional positional and keyword arguments can be used to
pass arguments to **all** handlers ... |
Runs the process_function over the passed data.
Args:
data (Iterable): Collection of batches allowing repeated iteration (e.g., list or `DataLoader`).
max_epochs (int, optional): max epochs to run for (default: 1).
Returns:
State: output state. | def run(self, data, max_epochs=1):
"""Runs the process_function over the passed data.
Args:
data (Iterable): Collection of batches allowing repeated iteration (e.g., list or `DataLoader`).
max_epochs (int, optional): max epochs to run for (default: 1).
Returns:
... |
Calculates Intersection over Union
Args:
cm (ConfusionMatrix): instance of confusion matrix metric
ignore_index (int, optional): index to ignore, e.g. background index
Returns:
MetricsLambda
Examples:
.. code-block:: python
train_evaluator = ...
cm = Confusi... | def IoU(cm, ignore_index=None):
"""Calculates Intersection over Union
Args:
cm (ConfusionMatrix): instance of confusion matrix metric
ignore_index (int, optional): index to ignore, e.g. background index
Returns:
MetricsLambda
Examples:
.. code-block:: python
trai... |
Calculates accuracy using :class:`~ignite.metrics.ConfusionMatrix` metric.
Args:
cm (ConfusionMatrix): instance of confusion matrix metric
Returns:
MetricsLambda | def cmAccuracy(cm):
"""
Calculates accuracy using :class:`~ignite.metrics.ConfusionMatrix` metric.
Args:
cm (ConfusionMatrix): instance of confusion matrix metric
Returns:
MetricsLambda
"""
# Increase floating point precision
cm = cm.type(torch.float64)
return cm.diag().... |
Calculates precision using :class:`~ignite.metrics.ConfusionMatrix` metric.
Args:
cm (ConfusionMatrix): instance of confusion matrix metric
average (bool, optional): if True metric value is averaged over all classes
Returns:
MetricsLambda | def cmPrecision(cm, average=True):
"""
Calculates precision using :class:`~ignite.metrics.ConfusionMatrix` metric.
Args:
cm (ConfusionMatrix): instance of confusion matrix metric
average (bool, optional): if True metric value is averaged over all classes
Returns:
MetricsLambda
... |
Calculates recall using :class:`~ignite.metrics.ConfusionMatrix` metric.
Args:
cm (ConfusionMatrix): instance of confusion matrix metric
average (bool, optional): if True metric value is averaged over all classes
Returns:
MetricsLambda | def cmRecall(cm, average=True):
"""
Calculates recall using :class:`~ignite.metrics.ConfusionMatrix` metric.
Args:
cm (ConfusionMatrix): instance of confusion matrix metric
average (bool, optional): if True metric value is averaged over all classes
Returns:
MetricsLambda
"""
... |
Move tensors to relevant device. | def convert_tensor(input_, device=None, non_blocking=False):
"""Move tensors to relevant device."""
def _func(tensor):
return tensor.to(device=device, non_blocking=non_blocking) if device else tensor
return apply_to_tensor(input_, _func) |
Apply a function on a object of `input_type` or mapping, or sequence of objects of `input_type`. | def apply_to_type(input_, input_type, func):
"""Apply a function on a object of `input_type` or mapping, or sequence of objects of `input_type`.
"""
if isinstance(input_, input_type):
return func(input_)
elif isinstance(input_, string_classes):
return input_
elif isinstance(input_, c... |
Convert a tensor of indices of any shape `(N, ...)` to a
tensor of one-hot indicators of shape `(N, num_classes, ...)`. | def to_onehot(indices, num_classes):
"""Convert a tensor of indices of any shape `(N, ...)` to a
tensor of one-hot indicators of shape `(N, num_classes, ...)`.
"""
onehot = torch.zeros(indices.shape[0], num_classes, *indices.shape[1:], device=indices.device)
return onehot.scatter_(1, indices.unsquee... |
Attaches the progress bar to an engine object.
Args:
engine (Engine): engine object.
metric_names (list, optional): list of the metrics names to log as the bar progresses
output_transform (callable, optional): a function to select what you want to print from the engine's
... | def attach(self, engine, metric_names=None, output_transform=None,
event_name=Events.ITERATION_COMPLETED,
closing_event_name=Events.EPOCH_COMPLETED):
"""
Attaches the progress bar to an engine object.
Args:
engine (Engine): engine object.
me... |
Prepare batch for training: pass to a device with options. | def _prepare_batch(batch, device=None, non_blocking=False):
"""Prepare batch for training: pass to a device with options.
"""
x, y = batch
return (convert_tensor(x, device=device, non_blocking=non_blocking),
convert_tensor(y, device=device, non_blocking=non_blocking)) |
Factory function for creating an evaluator for supervised models.
Args:
model (`torch.nn.Module`): the model to train.
metrics (dict of str - :class:`~ignite.metrics.Metric`): a map of metric names to Metrics.
device (str, optional): device type specification (default: None).
Ap... | def create_supervised_evaluator(model, metrics=None,
device=None, non_blocking=False,
prepare_batch=_prepare_batch,
output_transform=lambda x, y, y_pred: (y_pred, y,)):
"""
Factory function for creating an evaluator ... |
Factory function for creating a trainer for supervised models.
Args:
model (`torch.nn.Module`): the model to train.
optimizer (`torch.optim.Optimizer`): the optimizer to use.
loss_fn (torch.nn loss function): the loss function to use.
device (str, optional): device type specificatio... | def create_supervised_trainer(model, optimizer, loss_fn,
device=None, non_blocking=False,
prepare_batch=_prepare_batch,
output_transform=lambda x, y, y_pred, loss: loss.item()):
"""
Factory function for creating a trainer ... |
Helper method to create a LR scheduler with a linear warm-up.
Args:
lr_scheduler (ParamScheduler or subclass of `torch.optim.lr_scheduler._LRScheduler`): LR scheduler after
the warm-up.
warmup_start_value (float): LR start value of the warm-up phase.
warmup_end_value (float): LR... | def create_lr_scheduler_with_warmup(lr_scheduler, warmup_start_value, warmup_end_value, warmup_duration,
save_history=False,
output_simulated_values=None):
"""
Helper method to create a LR scheduler with a linear warm-up.
Args:
... |
Method to simulate scheduled values during num_events events.
Args:
num_events (int): number of events during the simulation.
**scheduler_kwargs : parameter scheduler configuration kwargs.
Returns:
list of pairs: [event_index, value]
Examples:
.. c... | def simulate_values(cls, num_events, **scheduler_kwargs):
"""Method to simulate scheduled values during num_events events.
Args:
num_events (int): number of events during the simulation.
**scheduler_kwargs : parameter scheduler configuration kwargs.
Returns:
... |
Method to get current optimizer's parameter value | def get_param(self):
"""Method to get current optimizer's parameter value
"""
cycle_progress = self.event_index / self.cycle_size
return self.start_value + ((self.end_value - self.start_value) / 2) * (1 - math.cos(math.pi * cycle_progress)) |
Method to simulate scheduled values during num_events events.
Args:
num_events (int): number of events during the simulation.
schedulers (list of ParamScheduler): list of parameter schedulers.
durations (list of int): list of number of events that lasts a parameter scheduler... | def simulate_values(cls, num_events, schedulers, durations, param_names=None, **kwargs):
"""Method to simulate scheduled values during num_events events.
Args:
num_events (int): number of events during the simulation.
schedulers (list of ParamScheduler): list of parameter schedu... |
Method to get current optimizer's parameter value | def get_param(self):
"""Method to get current optimizer's parameter value
"""
lr_list = self.lr_scheduler.get_lr()
if len(lr_list) > 1:
raise ValueError("Optimizer passed to lr_scheduler should have a single param group, "
"but currently there are... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.