INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Quick ratio comparison between two strings.
Runs full_process from utils on both strings
Short circuits if either of the strings is empty after processing.
:param s1:
:param s2:
:param force_ascii: Allow only ASCII characters (Default: True)
:full_process: Process inputs, used here to avoid do... | def QRatio(s1, s2, force_ascii=True, full_process=True):
"""
Quick ratio comparison between two strings.
Runs full_process from utils on both strings
Short circuits if either of the strings is empty after processing.
:param s1:
:param s2:
:param force_ascii: Allow only ASCII characters (De... |
Unicode quick ratio
Calls QRatio with force_ascii set to False
:param s1:
:param s2:
:return: similarity ratio | def UQRatio(s1, s2, full_process=True):
"""
Unicode quick ratio
Calls QRatio with force_ascii set to False
:param s1:
:param s2:
:return: similarity ratio
"""
return QRatio(s1, s2, force_ascii=False, full_process=full_process) |
Return a measure of the sequences' similarity between 0 and 100, using different algorithms.
**Steps in the order they occur**
#. Run full_process from utils on both strings
#. Short circuit if this makes either string empty
#. Take the ratio of the two processed strings (fuzz.ratio)
#. Run checks... | def WRatio(s1, s2, force_ascii=True, full_process=True):
"""
Return a measure of the sequences' similarity between 0 and 100, using different algorithms.
**Steps in the order they occur**
#. Run full_process from utils on both strings
#. Short circuit if this makes either string empty
#. Take ... |
Return a measure of the sequences' similarity between 0 and 100,
using different algorithms. Same as WRatio but preserving unicode. | def UWRatio(s1, s2, full_process=True):
"""Return a measure of the sequences' similarity between 0 and 100,
using different algorithms. Same as WRatio but preserving unicode.
"""
return WRatio(s1, s2, force_ascii=False, full_process=full_process) |
Clean function to know how much time took the execution of one statement | def print_result_from_timeit(stmt='pass', setup='pass', number=1000000):
"""
Clean function to know how much time took the execution of one statement
"""
units = ["s", "ms", "us", "ns"]
duration = timeit(stmt, setup, number=int(number))
avg_duration = duration / float(number)
thousands = int... |
Deploy this ``Model`` to an ``Endpoint`` and optionally return a ``Predictor``.
Create a SageMaker ``Model`` and ``EndpointConfig``, and deploy an ``Endpoint`` from this ``Model``.
If ``self.predictor_cls`` is not None, this method returns a the result of invoking
``self.predictor_cls`` on the ... | def deploy(self, initial_instance_count, instance_type, endpoint_name=None, tags=None):
"""Deploy this ``Model`` to an ``Endpoint`` and optionally return a ``Predictor``.
Create a SageMaker ``Model`` and ``EndpointConfig``, and deploy an ``Endpoint`` from this ``Model``.
If ``self.predictor_cls... |
Create a SageMaker Model Entity
Args:
instance_type (str): The EC2 instance type that this Model will be used for, this is only
used to determine if the image needs GPU support or not.
accelerator_type (str): Type of Elastic Inference accelerator to attach to an endpoint... | def _create_sagemaker_pipeline_model(self, instance_type):
"""Create a SageMaker Model Entity
Args:
instance_type (str): The EC2 instance type that this Model will be used for, this is only
used to determine if the image needs GPU support or not.
accelerator_type... |
Delete the SageMaker model backing this pipeline model. This does not delete the list of SageMaker models used
in multiple containers to build the inference pipeline. | def delete_model(self):
"""Delete the SageMaker model backing this pipeline model. This does not delete the list of SageMaker models used
in multiple containers to build the inference pipeline.
"""
if self.name is None:
raise ValueError('The SageMaker model must be created ... |
Stream the output of a process to stdout
This function takes an existing process that will be polled for output. Only stdout
will be polled and sent to sys.stdout.
Args:
process(subprocess.Popen): a process that has been started with
stdout=PIPE and stderr=STDOUT
Returns (int): pr... | def _stream_output(process):
"""Stream the output of a process to stdout
This function takes an existing process that will be polled for output. Only stdout
will be polled and sent to sys.stdout.
Args:
process(subprocess.Popen): a process that has been started with
stdout=PIPE and ... |
Run a training job locally using docker-compose.
Args:
input_data_config (dict): The Input Data Configuration, this contains data such as the
channels to be used for training.
hyperparameters (dict): The HyperParameters for the training job.
job_name (str): Na... | def train(self, input_data_config, output_data_config, hyperparameters, job_name):
"""Run a training job locally using docker-compose.
Args:
input_data_config (dict): The Input Data Configuration, this contains data such as the
channels to be used for training.
hy... |
Host a local endpoint using docker-compose.
Args:
primary_container (dict): dictionary containing the container runtime settings
for serving. Expected keys:
- 'ModelDataUrl' pointing to a file or s3:// location.
- 'Environment' a dictionary of environm... | def serve(self, model_dir, environment):
"""Host a local endpoint using docker-compose.
Args:
primary_container (dict): dictionary containing the container runtime settings
for serving. Expected keys:
- 'ModelDataUrl' pointing to a file or s3:// location.
... |
Stop the serving container.
The serving container runs in async mode to allow the SDK to do other tasks. | def stop_serving(self):
"""Stop the serving container.
The serving container runs in async mode to allow the SDK to do other tasks.
"""
if self.container:
self.container.down()
self.container.join()
self._cleanup()
# for serving we can delete ... |
Get the model artifacts from all the container nodes.
Used after training completes to gather the data from all the individual containers. As the
official SageMaker Training Service, it will override duplicate files if multiple containers have
the same file names.
Args:
com... | def retrieve_artifacts(self, compose_data, output_data_config, job_name):
"""Get the model artifacts from all the container nodes.
Used after training completes to gather the data from all the individual containers. As the
official SageMaker Training Service, it will override duplicate files if... |
Write the config files for the training containers.
This method writes the hyperparameters, resources and input data configuration files.
Args:
host (str): Host to write the configuration for
hyperparameters (dict): Hyperparameters for training.
input_data_config (d... | def write_config_files(self, host, hyperparameters, input_data_config):
"""Write the config files for the training containers.
This method writes the hyperparameters, resources and input data configuration files.
Args:
host (str): Host to write the configuration for
hyp... |
Writes a config file describing a training/hosting environment.
This method generates a docker compose configuration file, it has an entry for each container
that will be created (based on self.hosts). it calls
:meth:~sagemaker.local_session.SageMakerContainer._create_docker_host to generate t... | def _generate_compose_file(self, command, additional_volumes=None, additional_env_vars=None):
"""Writes a config file describing a training/hosting environment.
This method generates a docker compose configuration file, it has an entry for each container
that will be created (based on self.hos... |
Generate a list of :class:`~sagemaker.local_session.Volume` required for the container to start.
It takes a folder with the necessary files for training and creates a list of opt volumes that
the Container needs to start.
Args:
host (str): container for which the volumes will be ge... | def _build_optml_volumes(self, host, subdirs):
"""Generate a list of :class:`~sagemaker.local_session.Volume` required for the container to start.
It takes a folder with the necessary files for training and creates a list of opt volumes that
the Container needs to start.
Args:
... |
Transform a request using the Gluon model. Called once per request.
:param net: The Gluon model.
:param data: The request payload.
:param input_content_type: The request content type.
:param output_content_type: The (desired) response content type.
:return: response payload and content type. | def transform_fn(net, data, input_content_type, output_content_type):
"""
Transform a request using the Gluon model. Called once per request.
:param net: The Gluon model.
:param data: The request payload.
:param input_content_type: The request content type.
:param output_content_type: The (desi... |
Load the gluon model. Called once when hosting service starts.
:param: model_dir The directory where model files are stored.
:return: a model (in this case a Gluon network) | def model_fn(model_dir):
"""
Load the gluon model. Called once when hosting service starts.
:param: model_dir The directory where model files are stored.
:return: a model (in this case a Gluon network)
"""
symbol = mx.sym.load('%s/model.json' % model_dir)
outputs = mx.symbol.softmax(data=sy... |
Set hyperparameters needed for training.
Args:
* records (:class:`~RecordSet`): The records to train this ``Estimator`` on.
* mini_batch_size (int or None): The size of each mini-batch to use when training. If ``None``, a
default value will be used.
* job_nam... | def _prepare_for_training(self, records, mini_batch_size=None, job_name=None):
"""Set hyperparameters needed for training.
Args:
* records (:class:`~RecordSet`): The records to train this ``Estimator`` on.
* mini_batch_size (int or None): The size of each mini-batch to use when ... |
Return the ECR URI of an image.
Args:
region (str): AWS region where the image is uploaded.
framework (str): framework used by the image.
instance_type (str): SageMaker instance type. Used to determine device type (cpu/gpu/family-specific optimized).
framework_version (str): The ver... | def create_image_uri(region, framework, instance_type, framework_version, py_version=None,
account='520713654638', accelerator_type=None, optimized_families=None):
"""Return the ECR URI of an image.
Args:
region (str): AWS region where the image is uploaded.
framework (str)... |
Validate that the source directory exists and it contains the user script
Args:
script (str): Script filename.
directory (str): Directory containing the source file.
Raises:
ValueError: If ``directory`` does not exist, is not a directory, or does not contain ``script``. | def validate_source_dir(script, directory):
"""Validate that the source directory exists and it contains the user script
Args:
script (str): Script filename.
directory (str): Directory containing the source file.
Raises:
ValueError: If ``directory`` does not exist, is not a direct... |
Package source files and upload a compress tar file to S3. The S3 location will be
``s3://<bucket>/s3_key_prefix/sourcedir.tar.gz``.
If directory is an S3 URI, an UploadedCode object will be returned, but nothing will be
uploaded to S3 (this allow reuse of code already in S3).
If directory is None, th... | def tar_and_upload_dir(session, bucket, s3_key_prefix, script,
directory=None, dependencies=None, kms_key=None):
"""Package source files and upload a compress tar file to S3. The S3 location will be
``s3://<bucket>/s3_key_prefix/sourcedir.tar.gz``.
If directory is an S3 URI, an Uploa... |
Extract the framework and Python version from the image name.
Args:
image_name (str): Image URI, which should be one of the following forms:
legacy:
'<account>.dkr.ecr.<region>.amazonaws.com/sagemaker-<fw>-<py_ver>-<device>:<container_version>'
legacy:
'<acco... | def framework_name_from_image(image_name):
"""Extract the framework and Python version from the image name.
Args:
image_name (str): Image URI, which should be one of the following forms:
legacy:
'<account>.dkr.ecr.<region>.amazonaws.com/sagemaker-<fw>-<py_ver>-<device>:<containe... |
Extract the framework version from the image tag.
Args:
image_tag (str): Image tag, which should take the form '<framework_version>-<device>-<py_version>'
Returns:
str: The framework version. | def framework_version_from_tag(image_tag):
"""Extract the framework version from the image tag.
Args:
image_tag (str): Image tag, which should take the form '<framework_version>-<device>-<py_version>'
Returns:
str: The framework version.
"""
tag_pattern = re.compile('^(.*)-(cpu|gpu... |
Returns an (s3 bucket, key name/prefix) tuple from a url with an s3 scheme
Args:
url (str):
Returns:
tuple: A tuple containing:
str: S3 bucket name
str: S3 key | def parse_s3_url(url):
"""Returns an (s3 bucket, key name/prefix) tuple from a url with an s3 scheme
Args:
url (str):
Returns:
tuple: A tuple containing:
str: S3 bucket name
str: S3 key
"""
parsed_url = urlparse(url)
if parsed_url.scheme != "s3":
... |
Returns the s3 key prefix for uploading code during model deployment
The location returned is a potential concatenation of 2 parts
1. code_location_key_prefix if it exists
2. model_name or a name derived from the image
Args:
code_location_key_prefix (str): the s3 key prefix from code_l... | def model_code_key_prefix(code_location_key_prefix, model_name, image):
"""Returns the s3 key prefix for uploading code during model deployment
The location returned is a potential concatenation of 2 parts
1. code_location_key_prefix if it exists
2. model_name or a name derived from the image
... |
Create a training job in Local Mode
Args:
TrainingJobName (str): local training job name.
AlgorithmSpecification (dict): Identifies the training algorithm to use.
InputDataConfig (dict): Describes the training dataset and the location where it is stored.
OutputDat... | def create_training_job(self, TrainingJobName, AlgorithmSpecification, OutputDataConfig,
ResourceConfig, InputDataConfig=None, **kwargs):
"""
Create a training job in Local Mode
Args:
TrainingJobName (str): local training job name.
AlgorithmSpe... |
Describe a local training job.
Args:
TrainingJobName (str): Training job name to describe.
Returns: (dict) DescribeTrainingJob Response. | def describe_training_job(self, TrainingJobName):
"""Describe a local training job.
Args:
TrainingJobName (str): Training job name to describe.
Returns: (dict) DescribeTrainingJob Response.
"""
if TrainingJobName not in LocalSagemakerClient._training_jobs:
... |
Create a Local Model Object
Args:
ModelName (str): the Model Name
PrimaryContainer (dict): a SageMaker primary container definition | def create_model(self, ModelName, PrimaryContainer, *args, **kwargs): # pylint: disable=unused-argument
"""Create a Local Model Object
Args:
ModelName (str): the Model Name
PrimaryContainer (dict): a SageMaker primary container definition
"""
LocalSagemakerClien... |
Initialize this Local SageMaker Session. | def _initialize(self, boto_session, sagemaker_client, sagemaker_runtime_client):
"""Initialize this Local SageMaker Session."""
self.boto_session = boto_session or boto3.Session()
self._region_name = self.boto_session.region_name
if self._region_name is None:
raise ValueErr... |
Return a container definition with framework configuration set in model environment variables.
Args:
instance_type (str): The EC2 instance type to deploy this Model to. For example, 'ml.p2.xlarge'.
accelerator_type (str): The Elastic Inference accelerator type to deploy to the instance ... | def prepare_container_def(self, instance_type, accelerator_type=None):
"""Return a container definition with framework configuration set in model environment variables.
Args:
instance_type (str): The EC2 instance type to deploy this Model to. For example, 'ml.p2.xlarge'.
acceler... |
Upload the training ``array`` and ``labels`` arrays to ``num_shards`` s3 objects,
stored in "s3://``bucket``/``key_prefix``/". | def upload_numpy_to_s3_shards(num_shards, s3, bucket, key_prefix, array, labels=None):
"""Upload the training ``array`` and ``labels`` arrays to ``num_shards`` s3 objects,
stored in "s3://``bucket``/``key_prefix``/"."""
shards = _build_shards(num_shards, array)
if labels is not None:
label_shard... |
Return docker registry for the given AWS region
Note: Not all the algorithms listed below have an Amazon Estimator implemented. For full list of
pre-implemented Estimators, look at:
https://github.com/aws/sagemaker-python-sdk/tree/master/src/sagemaker/amazon | def registry(region_name, algorithm=None):
"""Return docker registry for the given AWS region
Note: Not all the algorithms listed below have an Amazon Estimator implemented. For full list of
pre-implemented Estimators, look at:
https://github.com/aws/sagemaker-python-sdk/tree/master/src/sagemaker/amaz... |
Return algorithm image URI for the given AWS region, repository name, and repository version | def get_image_uri(region_name, repo_name, repo_version=1):
"""Return algorithm image URI for the given AWS region, repository name, and repository version"""
repo = '{}:{}'.format(repo_name, repo_version)
return '{}/{}'.format(registry(region_name, repo_name), repo) |
Convert the job description to init params that can be handled by the class constructor
Args:
job_details: the returned job details from a describe_training_job API call.
model_channel_name (str): Name of the channel where pre-trained model data will be downloaded.
Returns:
... | def _prepare_init_params_from_job_description(cls, job_details, model_channel_name=None):
"""Convert the job description to init params that can be handled by the class constructor
Args:
job_details: the returned job details from a describe_training_job API call.
model_channel_n... |
Set hyperparameters needed for training.
Args:
* records (:class:`~RecordSet`): The records to train this ``Estimator`` on.
* mini_batch_size (int or None): The size of each mini-batch to use when training. If ``None``, a
default value will be used.
* job_nam... | def _prepare_for_training(self, records, mini_batch_size=None, job_name=None):
"""Set hyperparameters needed for training.
Args:
* records (:class:`~RecordSet`): The records to train this ``Estimator`` on.
* mini_batch_size (int or None): The size of each mini-batch to use when ... |
Fit this Estimator on serialized Record objects, stored in S3.
``records`` should be an instance of :class:`~RecordSet`. This defines a collection of
S3 data files to train this ``Estimator`` on.
Training data is expected to be encoded as dense or sparse vectors in the "values" feature
... | def fit(self, records, mini_batch_size=None, wait=True, logs=True, job_name=None):
"""Fit this Estimator on serialized Record objects, stored in S3.
``records`` should be an instance of :class:`~RecordSet`. This defines a collection of
S3 data files to train this ``Estimator`` on.
Trai... |
Build a :class:`~RecordSet` from a numpy :class:`~ndarray` matrix and label vector.
For the 2D ``ndarray`` ``train``, each row is converted to a :class:`~Record` object.
The vector is stored in the "values" entry of the ``features`` property of each Record.
If ``labels`` is not None, each corre... | def record_set(self, train, labels=None, channel="train"):
"""Build a :class:`~RecordSet` from a numpy :class:`~ndarray` matrix and label vector.
For the 2D ``ndarray`` ``train``, each row is converted to a :class:`~Record` object.
The vector is stored in the "values" entry of the ``features`` ... |
Return an Instance of :class:`sagemaker.local.data.DataSource` that can handle
the provided data_source URI.
data_source can be either file:// or s3://
Args:
data_source (str): a valid URI that points to a data source.
sagemaker_session (:class:`sagemaker.session.Session`): a SageMaker Ses... | def get_data_source_instance(data_source, sagemaker_session):
"""Return an Instance of :class:`sagemaker.local.data.DataSource` that can handle
the provided data_source URI.
data_source can be either file:// or s3://
Args:
data_source (str): a valid URI that points to a data source.
sa... |
Return an Instance of :class:`sagemaker.local.data.Splitter` according to
the specified `split_type`.
Args:
split_type (str): either 'Line' or 'RecordIO'. Can be left as None to signal no data split
will happen.
Returns
:class:`sagemaker.local.data.Splitter`: an Instance of a S... | def get_splitter_instance(split_type):
"""Return an Instance of :class:`sagemaker.local.data.Splitter` according to
the specified `split_type`.
Args:
split_type (str): either 'Line' or 'RecordIO'. Can be left as None to signal no data split
will happen.
Returns
:class:`sage... |
Return an Instance of :class:`sagemaker.local.data.BatchStrategy` according to `strategy`
Args:
strategy (str): Either 'SingleRecord' or 'MultiRecord'
splitter (:class:`sagemaker.local.data.Splitter): splitter to get the data from.
Returns
:class:`sagemaker.local.data.BatchStrategy`: a... | def get_batch_strategy_instance(strategy, splitter):
"""Return an Instance of :class:`sagemaker.local.data.BatchStrategy` according to `strategy`
Args:
strategy (str): Either 'SingleRecord' or 'MultiRecord'
splitter (:class:`sagemaker.local.data.Splitter): splitter to get the data from.
Re... |
Retrieve the list of absolute paths to all the files in this data source.
Returns:
List[str] List of absolute paths. | def get_file_list(self):
"""Retrieve the list of absolute paths to all the files in this data source.
Returns:
List[str] List of absolute paths.
"""
if os.path.isdir(self.root_path):
return [os.path.join(self.root_path, f) for f in os.listdir(self.root_path)
... |
Retrieve the absolute path to the root directory of this data source.
Returns:
str: absolute path to the root directory of this data source. | def get_root_dir(self):
"""Retrieve the absolute path to the root directory of this data source.
Returns:
str: absolute path to the root directory of this data source.
"""
if os.path.isdir(self.root_path):
return self.root_path
else:
return os... |
Split a file into records using a specific strategy
This RecordIOSplitter splits the data into individual RecordIO records.
Args:
file (str): path to the file to split
Returns: generator for the individual records that were split from the file | def split(self, file):
"""Split a file into records using a specific strategy
This RecordIOSplitter splits the data into individual RecordIO records.
Args:
file (str): path to the file to split
Returns: generator for the individual records that were split from the file
... |
Group together as many records as possible to fit in the specified size
This SingleRecordStrategy will not group any record and will return them one by one as
long as they are within the maximum size.
Args:
file (str): file path to read the records from.
size (int): max... | def pad(self, file, size=6):
"""Group together as many records as possible to fit in the specified size
This SingleRecordStrategy will not group any record and will return them one by one as
long as they are within the maximum size.
Args:
file (str): file path to read the r... |
Group together as many records as possible to fit in the specified size
Args:
file (str): file path to read the records from.
size (int): maximum size in MB that each group of records will be fitted to.
passing 0 means unlimited size.
Returns:
genera... | def pad(self, file, size=6):
"""Group together as many records as possible to fit in the specified size
Args:
file (str): file path to read the records from.
size (int): maximum size in MB that each group of records will be fitted to.
passing 0 means unlimited si... |
Return hyperparameters used by your custom Chainer code during training. | def hyperparameters(self):
"""Return hyperparameters used by your custom Chainer code during training."""
hyperparameters = super(Chainer, self).hyperparameters()
additional_hyperparameters = {Chainer._use_mpi: self.use_mpi,
Chainer._num_processes: self.num... |
Create a SageMaker ``ChainerModel`` object that can be deployed to an ``Endpoint``.
Args:
role (str): The ``ExecutionRoleArn`` IAM Role ARN for the ``Model``, which is also used during
transform jobs. If not specified, the role from the Estimator will be used.
model_serv... | def create_model(self, model_server_workers=None, role=None, vpc_config_override=VPC_CONFIG_DEFAULT):
"""Create a SageMaker ``ChainerModel`` object that can be deployed to an ``Endpoint``.
Args:
role (str): The ``ExecutionRoleArn`` IAM Role ARN for the ``Model``, which is also used during
... |
Convert the job description to init params that can be handled by the class constructor
Args:
job_details: the returned job details from a describe_training_job API call.
model_channel_name (str): Name of the channel where pre-trained model data will be downloaded.
Returns:
... | def _prepare_init_params_from_job_description(cls, job_details, model_channel_name=None):
"""Convert the job description to init params that can be handled by the class constructor
Args:
job_details: the returned job details from a describe_training_job API call.
model_channel_n... |
Writes a numpy array to a dense tensor | def write_numpy_to_dense_tensor(file, array, labels=None):
"""Writes a numpy array to a dense tensor"""
# Validate shape of array and labels, resolve array and label types
if not len(array.shape) == 2:
raise ValueError("Array must be a Matrix")
if labels is not None:
if not len(labels.s... |
Writes a scipy sparse matrix to a sparse tensor | def write_spmatrix_to_sparse_tensor(file, array, labels=None):
"""Writes a scipy sparse matrix to a sparse tensor"""
if not issparse(array):
raise TypeError("Array must be sparse")
# Validate shape of array and labels, resolve array and label types
if not len(array.shape) == 2:
raise V... |
Eagerly read a collection of amazon Record protobuf objects from file. | def read_records(file):
"""Eagerly read a collection of amazon Record protobuf objects from file."""
records = []
for record_data in read_recordio(file):
record = Record()
record.ParseFromString(record_data)
records.append(record)
return records |
Writes a single data point as a RecordIO record to the given file. | def _write_recordio(f, data):
"""Writes a single data point as a RecordIO record to the given file."""
length = len(data)
f.write(struct.pack('I', _kmagic))
f.write(struct.pack('I', length))
pad = (((length + 3) >> 2) << 2) - length
f.write(data)
f.write(padding[pad]) |
Return a dict created by ``sagemaker.container_def()`` for deploying this model to a specified instance type.
Subclasses can override this to provide custom container definitions for
deployment to a specific instance type. Called by ``deploy()``.
Args:
instance_type (str): The EC2 ... | def prepare_container_def(self, instance_type, accelerator_type=None): # pylint: disable=unused-argument
"""Return a dict created by ``sagemaker.container_def()`` for deploying this model to a specified instance type.
Subclasses can override this to provide custom container definitions for
dep... |
Create a SageMaker Model Entity
Args:
instance_type (str): The EC2 instance type that this Model will be used for, this is only
used to determine if the image needs GPU support or not.
accelerator_type (str): Type of Elastic Inference accelerator to attach to an endpoint... | def _create_sagemaker_model(self, instance_type, accelerator_type=None, tags=None):
"""Create a SageMaker Model Entity
Args:
instance_type (str): The EC2 instance type that this Model will be used for, this is only
used to determine if the image needs GPU support or not.
... |
Compile this ``Model`` with SageMaker Neo.
Args:
target_instance_family (str): Identifies the device that you want to run your model after compilation, for
example: ml_c5. Allowed strings are: ml_c5, ml_m5, ml_c4, ml_m4, jetsontx1, jetsontx2, ml_p2, ml_p3,
deeplens, ... | def compile(self, target_instance_family, input_shape, output_path, role,
tags=None, job_name=None, compile_max_run=5 * 60, framework=None, framework_version=None):
"""Compile this ``Model`` with SageMaker Neo.
Args:
target_instance_family (str): Identifies the device that y... |
Deploy this ``Model`` to an ``Endpoint`` and optionally return a ``Predictor``.
Create a SageMaker ``Model`` and ``EndpointConfig``, and deploy an ``Endpoint`` from this ``Model``.
If ``self.predictor_cls`` is not None, this method returns a the result of invoking
``self.predictor_cls`` on the ... | def deploy(self, initial_instance_count, instance_type, accelerator_type=None, endpoint_name=None,
update_endpoint=False, tags=None, kms_key=None):
"""Deploy this ``Model`` to an ``Endpoint`` and optionally return a ``Predictor``.
Create a SageMaker ``Model`` and ``EndpointConfig``, and ... |
Return a ``Transformer`` that uses this Model.
Args:
instance_count (int): Number of EC2 instances to use.
instance_type (str): Type of EC2 instance to use, for example, 'ml.c4.xlarge'.
strategy (str): The strategy used to decide how to batch records in a single request (def... | def transformer(self, instance_count, instance_type, strategy=None, assemble_with=None, output_path=None,
output_kms_key=None, accept=None, env=None, max_concurrent_transforms=None,
max_payload=None, tags=None, volume_kms_key=None):
"""Return a ``Transformer`` that uses t... |
Return a container definition with framework configuration set in model environment variables.
This also uploads user-supplied code to S3.
Args:
instance_type (str): The EC2 instance type to deploy this Model to. For example, 'ml.p2.xlarge'.
accelerator_type (str): The Elastic ... | def prepare_container_def(self, instance_type, accelerator_type=None): # pylint disable=unused-argument
"""Return a container definition with framework configuration set in model environment variables.
This also uploads user-supplied code to S3.
Args:
instance_type (str): The EC2 ... |
Create a SageMaker Model Entity
Args:
*args: Arguments coming from the caller. This class
does not require any so they are ignored. | def _create_sagemaker_model(self, *args): # pylint: disable=unused-argument
"""Create a SageMaker Model Entity
Args:
*args: Arguments coming from the caller. This class
does not require any so they are ignored.
"""
if self.algorithm_arn:
# When M... |
Return the inference from the specified endpoint.
Args:
data (object): Input data for which you want the model to provide inference.
If a serializer was specified when creating the RealTimePredictor, the result of the
serializer is sent as input data. Otherwise the d... | def predict(self, data, initial_args=None):
"""Return the inference from the specified endpoint.
Args:
data (object): Input data for which you want the model to provide inference.
If a serializer was specified when creating the RealTimePredictor, the result of the
... |
Delete the Amazon SageMaker endpoint backing this predictor. Also delete the endpoint configuration attached
to it if delete_endpoint_config is True.
Args:
delete_endpoint_config (bool, optional): Flag to indicate whether to delete endpoint configuration together
with endpoi... | def delete_endpoint(self, delete_endpoint_config=True):
"""Delete the Amazon SageMaker endpoint backing this predictor. Also delete the endpoint configuration attached
to it if delete_endpoint_config is True.
Args:
delete_endpoint_config (bool, optional): Flag to indicate whether to... |
Deletes the Amazon SageMaker models backing this predictor. | def delete_model(self):
"""Deletes the Amazon SageMaker models backing this predictor.
"""
request_failed = False
failed_models = []
for model_name in self._model_names:
try:
self.sagemaker_session.delete_model(model_name)
except Exception... |
A pandas dataframe with lots of interesting results about this object.
Created by calling SageMaker List and Describe APIs and converting them into
a convenient tabular summary.
Args:
force_refresh (bool): Set to True to fetch the latest data from SageMaker API. | def dataframe(self, force_refresh=False):
"""A pandas dataframe with lots of interesting results about this object.
Created by calling SageMaker List and Describe APIs and converting them into
a convenient tabular summary.
Args:
force_refresh (bool): Set to True to fetch the... |
Clear the object of all local caches of API methods. | def clear_cache(self):
"""Clear the object of all local caches of API methods.
"""
super(HyperparameterTuningJobAnalytics, self).clear_cache()
self._tuning_job_describe_result = None
self._training_job_summaries = None |
Return a pandas dataframe with all the training jobs, along with their
hyperparameters, results, and metadata. This also includes a column to indicate
if a training job was the best seen so far. | def _fetch_dataframe(self):
"""Return a pandas dataframe with all the training jobs, along with their
hyperparameters, results, and metadata. This also includes a column to indicate
if a training job was the best seen so far.
"""
def reshape(training_summary):
# Helpe... |
A dictionary describing the ranges of all tuned hyperparameters.
The keys are the names of the hyperparameter, and the values are the ranges. | def tuning_ranges(self):
"""A dictionary describing the ranges of all tuned hyperparameters.
The keys are the names of the hyperparameter, and the values are the ranges.
"""
out = {}
for _, ranges in self.description()['HyperParameterTuningJobConfig']['ParameterRanges'].items():
... |
Call ``DescribeHyperParameterTuningJob`` for the hyperparameter tuning job.
Args:
force_refresh (bool): Set to True to fetch the latest data from SageMaker API.
Returns:
dict: The Amazon SageMaker response for ``DescribeHyperParameterTuningJob``. | def description(self, force_refresh=False):
"""Call ``DescribeHyperParameterTuningJob`` for the hyperparameter tuning job.
Args:
force_refresh (bool): Set to True to fetch the latest data from SageMaker API.
Returns:
dict: The Amazon SageMaker response for ``DescribeHyp... |
A (paginated) list of everything from ``ListTrainingJobsForTuningJob``.
Args:
force_refresh (bool): Set to True to fetch the latest data from SageMaker API.
Returns:
dict: The Amazon SageMaker response for ``ListTrainingJobsForTuningJob``. | def training_job_summaries(self, force_refresh=False):
"""A (paginated) list of everything from ``ListTrainingJobsForTuningJob``.
Args:
force_refresh (bool): Set to True to fetch the latest data from SageMaker API.
Returns:
dict: The Amazon SageMaker response for ``List... |
Clear the object of all local caches of API methods, so
that the next time any properties are accessed they will be refreshed from
the service. | def clear_cache(self):
"""Clear the object of all local caches of API methods, so
that the next time any properties are accessed they will be refreshed from
the service.
"""
super(TrainingJobAnalytics, self).clear_cache()
self._data = defaultdict(list)
self._time_... |
Return a dictionary with two datetime objects, start_time and end_time,
covering the interval of the training job | def _determine_timeinterval(self):
"""Return a dictionary with two datetime objects, start_time and end_time,
covering the interval of the training job
"""
description = self._sage_client.describe_training_job(TrainingJobName=self.name)
start_time = self._start_time or descriptio... |
Fetch all the values of a named metric, and add them to _data | def _fetch_metric(self, metric_name):
"""Fetch all the values of a named metric, and add them to _data
"""
request = {
'Namespace': self.CLOUDWATCH_NAMESPACE,
'MetricName': metric_name,
'Dimensions': [
{
'Name': 'TrainingJob... |
Store a single metric in the _data dict which can be
converted to a dataframe. | def _add_single_metric(self, timestamp, metric_name, value):
"""Store a single metric in the _data dict which can be
converted to a dataframe.
"""
# note that this method is built this way to make it possible to
# support live-refreshing charts in Bokeh at some point in the futur... |
Helper method to discover the metrics defined for a training job. | def _metric_names_for_training_job(self):
"""Helper method to discover the metrics defined for a training job.
"""
training_description = self._sage_client.describe_training_job(TrainingJobName=self._training_job_name)
metric_definitions = training_description['AlgorithmSpecification'][... |
Append a timestamp to the provided string.
This function assures that the total length of the resulting string is not
longer than the specified max length, trimming the input parameter if necessary.
Args:
base (str): String used as prefix to generate the unique name.
max_length (int): Maxi... | def name_from_base(base, max_length=63, short=False):
"""Append a timestamp to the provided string.
This function assures that the total length of the resulting string is not
longer than the specified max length, trimming the input parameter if necessary.
Args:
base (str): String used as prefi... |
Extract the base name of the image to use as the 'algorithm name' for the job.
Args:
image (str): Image name.
Returns:
str: Algorithm name, as extracted from the image name. | def base_name_from_image(image):
"""Extract the base name of the image to use as the 'algorithm name' for the job.
Args:
image (str): Image name.
Returns:
str: Algorithm name, as extracted from the image name.
"""
m = re.match("^(.+/)?([^:/]+)(:[^:]+)?$", image)
algo_name = m.g... |
Return a timestamp with millisecond precision. | def sagemaker_timestamp():
"""Return a timestamp with millisecond precision."""
moment = time.time()
moment_ms = repr(moment).split('.')[1][:3]
return time.strftime("%Y-%m-%d-%H-%M-%S-{}".format(moment_ms), time.gmtime(moment)) |
Print the function name and arguments for debugging. | def debug(func):
"""Print the function name and arguments for debugging."""
@wraps(func)
def wrapper(*args, **kwargs):
print("{} args: {} kwargs: {}".format(func.__name__, args, kwargs))
return func(*args, **kwargs)
return wrapper |
Convert the input to a string, unless it is a unicode string in Python 2.
Unicode strings are supported as native strings in Python 3, but ``str()`` cannot be
invoked on unicode strings in Python 2, so we need to check for that case when
converting user-specified values to strings.
Args:
value... | def to_str(value):
"""Convert the input to a string, unless it is a unicode string in Python 2.
Unicode strings are supported as native strings in Python 3, but ``str()`` cannot be
invoked on unicode strings in Python 2, so we need to check for that case when
converting user-specified values to strings... |
Returns the name used in the API given a full ARN for a training job
or hyperparameter tuning job. | def extract_name_from_job_arn(arn):
"""Returns the name used in the API given a full ARN for a training job
or hyperparameter tuning job.
"""
slash_pos = arn.find('/')
if slash_pos == -1:
raise ValueError("Cannot parse invalid ARN: %s" % arn)
return arn[(slash_pos + 1):] |
Returns a string contains last modified time and the secondary training job status message.
Args:
job_description: Returned response from DescribeTrainingJob call
prev_description: Previous job description from DescribeTrainingJob call
Returns:
str: Job status string to be printed. | def secondary_training_status_message(job_description, prev_description):
"""Returns a string contains last modified time and the secondary training job status message.
Args:
job_description: Returned response from DescribeTrainingJob call
prev_description: Previous job description from Describ... |
Download a folder from S3 to a local path
Args:
bucket_name (str): S3 bucket name
prefix (str): S3 prefix within the bucket that will be downloaded. Can be a single file.
target (str): destination path where the downloaded items will be placed
sagemaker_session (:class:`sagemaker.se... | def download_folder(bucket_name, prefix, target, sagemaker_session):
"""Download a folder from S3 to a local path
Args:
bucket_name (str): S3 bucket name
prefix (str): S3 prefix within the bucket that will be downloaded. Can be a single file.
target (str): destination path where the dow... |
Create a tar file containing all the source_files
Args:
source_files (List[str]): List of file paths that will be contained in the tar file
Returns:
(str): path to created tar file | def create_tar_file(source_files, target=None):
"""Create a tar file containing all the source_files
Args:
source_files (List[str]): List of file paths that will be contained in the tar file
Returns:
(str): path to created tar file
"""
if target:
filename = target
els... |
Download a Single File from S3 into a local path
Args:
bucket_name (str): S3 bucket name
path (str): file path within the bucket
target (str): destination directory for the downloaded file.
sagemaker_session (:class:`sagemaker.session.Session`): a sagemaker session to interact with ... | def download_file(bucket_name, path, target, sagemaker_session):
"""Download a Single File from S3 into a local path
Args:
bucket_name (str): S3 bucket name
path (str): file path within the bucket
target (str): destination directory for the downloaded file.
sagemaker_session (:c... |
Sync to_directory with from_directory by copying each file in
to_directory with new contents. Files in to_directory will be
overwritten by files of the same name in from_directory. We need to
keep two copies of the log directory because otherwise TensorBoard
picks up temp files from `aws... | def _sync_directories(from_directory, to_directory):
"""Sync to_directory with from_directory by copying each file in
to_directory with new contents. Files in to_directory will be
overwritten by files of the same name in from_directory. We need to
keep two copies of the log directory bec... |
Create a TensorBoard process.
Returns:
tuple: A tuple containing:
int: The port number.
process: The TensorBoard process.
Raises:
OSError: If no ports between 6006 and 6105 are available for starting TensorBoard. | def create_tensorboard_process(self):
"""Create a TensorBoard process.
Returns:
tuple: A tuple containing:
int: The port number.
process: The TensorBoard process.
Raises:
OSError: If no ports between 6006 and 6105 are available for starti... |
Run TensorBoard process. | def run(self):
"""Run TensorBoard process."""
port, tensorboard_process = self.create_tensorboard_process()
LOGGER.info('TensorBoard 0.1.7 at http://localhost:{}'.format(port))
while not self.estimator.checkpoint_path:
self.event.wait(1)
with self._temporary_director... |
Train a model using the input training dataset.
See :func:`~sagemaker.estimator.EstimatorBase.fit` for more details.
Args:
inputs (str or dict or sagemaker.session.s3_input): Information about the training data.
This can be one of three types:
* (str) - the... | def fit(self, inputs=None, wait=True, logs=True, job_name=None, run_tensorboard_locally=False):
"""Train a model using the input training dataset.
See :func:`~sagemaker.estimator.EstimatorBase.fit` for more details.
Args:
inputs (str or dict or sagemaker.session.s3_input): Informat... |
Convert the job description to init params that can be handled by the class constructor
Args:
job_details: the returned job details from a describe_training_job API call.
Returns:
dictionary: The transformed init_params | def _prepare_init_params_from_job_description(cls, job_details, model_channel_name=None):
"""Convert the job description to init params that can be handled by the class constructor
Args:
job_details: the returned job details from a describe_training_job API call.
Returns:
... |
Create a SageMaker ``TensorFlowModel`` object that can be deployed to an ``Endpoint``.
Args:
role (str): The ``ExecutionRoleArn`` IAM Role ARN for the ``Model``, which is also used during
transform jobs. If not specified, the role from the Estimator will be used.
model_s... | def create_model(self, model_server_workers=None, role=None,
vpc_config_override=VPC_CONFIG_DEFAULT, endpoint_type=None):
"""Create a SageMaker ``TensorFlowModel`` object that can be deployed to an ``Endpoint``.
Args:
role (str): The ``ExecutionRoleArn`` IAM Role ARN fo... |
Return hyperparameters used by your custom TensorFlow code during model training. | def hyperparameters(self):
"""Return hyperparameters used by your custom TensorFlow code during model training."""
hyperparameters = super(TensorFlow, self).hyperparameters()
self.checkpoint_path = self.checkpoint_path or self._default_s3_path('checkpoints')
mpi_enabled = False
... |
Extracts subnets and security group ids as lists from a VpcConfig dict
Args:
vpc_config (dict): a VpcConfig dict containing 'Subnets' and 'SecurityGroupIds'
do_sanitize (bool): whether to sanitize the VpcConfig dict before extracting values
Returns:
Tuple of lists as (subnets, security... | def from_dict(vpc_config, do_sanitize=False):
"""
Extracts subnets and security group ids as lists from a VpcConfig dict
Args:
vpc_config (dict): a VpcConfig dict containing 'Subnets' and 'SecurityGroupIds'
do_sanitize (bool): whether to sanitize the VpcConfig dict before extracting values
... |
Checks that an instance of VpcConfig has the expected keys and values, removes unexpected keys,
and raises ValueErrors if any expectations are violated
Args:
vpc_config (dict): a VpcConfig dict containing 'Subnets' and 'SecurityGroupIds'
Returns:
A valid VpcConfig dict containing only 'Sub... | def sanitize(vpc_config):
"""
Checks that an instance of VpcConfig has the expected keys and values, removes unexpected keys,
and raises ValueErrors if any expectations are violated
Args:
vpc_config (dict): a VpcConfig dict containing 'Subnets' and 'SecurityGroupIds'
Returns:
A val... |
Return the SageMaker hyperparameters for training this KMeans Estimator | def hyperparameters(self):
"""Return the SageMaker hyperparameters for training this KMeans Estimator"""
hp_dict = dict(force_dense='True') # KMeans requires this hp to fit on Record objects
hp_dict.update(super(KMeans, self).hyperparameters())
return hp_dict |
Creates a new tuner by copying the request fields from the provided parent to the new instance of
``HyperparameterTuner`` followed by addition of warm start configuration with the type as
"IdenticalDataAndAlgorithm" and ``parents`` as the union of provided list of ``additional_parents`` and the
... | def create_identical_dataset_and_algorithm_tuner(parent, additional_parents=None, sagemaker_session=None):
"""Creates a new tuner by copying the request fields from the provided parent to the new instance of
``HyperparameterTuner`` followed by addition of warm start configuration with the type as
"I... |
Creates a new ``HyperParameterTuner`` by copying the request fields from the provided parent to the new instance
of ``HyperparameterTuner`` followed by addition of warm start configuration with the type as "TransferLearning"
and ``parents`` as the union of provided list of ``additional_parents`` and the... | def create_transfer_learning_tuner(parent, additional_parents=None, estimator=None, sagemaker_session=None):
"""Creates a new ``HyperParameterTuner`` by copying the request fields from the provided parent to the new instance
of ``HyperparameterTuner`` followed by addition of warm start configuration with th... |
Creates an instance of ``WarmStartConfig`` class, from warm start configuration response from
DescribeTrainingJob.
Args:
warm_start_config (dict): The expected format of the ``warm_start_config`` contains two first-class
fields:
* "type": Type of warm start tuner... | def from_job_desc(cls, warm_start_config):
"""Creates an instance of ``WarmStartConfig`` class, from warm start configuration response from
DescribeTrainingJob.
Args:
warm_start_config (dict): The expected format of the ``warm_start_config`` contains two first-class
fiel... |
Converts the ``self`` instance to the desired input request format.
Returns:
dict: Containing the "WarmStartType" and "ParentHyperParameterTuningJobs" as the first class fields.
Examples:
>>> warm_start_config = WarmStartConfig(warm_start_type=WarmStartTypes.TransferLearning,pa... | def to_input_req(self):
"""Converts the ``self`` instance to the desired input request format.
Returns:
dict: Containing the "WarmStartType" and "ParentHyperParameterTuningJobs" as the first class fields.
Examples:
>>> warm_start_config = WarmStartConfig(warm_start_type... |
Start a hyperparameter tuning job.
Args:
inputs: Information about the training data. Please refer to the ``fit()`` method of
the associated estimator, as this can take any of the following forms:
* (str) - The S3 location where training data is saved.
... | def fit(self, inputs=None, job_name=None, include_cls_metadata=False, **kwargs):
"""Start a hyperparameter tuning job.
Args:
inputs: Information about the training data. Please refer to the ``fit()`` method of
the associated estimator, as this can take any of the following f... |
Attach to an existing hyperparameter tuning job.
Create a HyperparameterTuner bound to an existing hyperparameter tuning job. After attaching, if there exists a
best training job (or any other completed training job), that can be deployed to create
an Amazon SageMaker Endpoint and return a ``Pr... | def attach(cls, tuning_job_name, sagemaker_session=None, job_details=None, estimator_cls=None):
"""Attach to an existing hyperparameter tuning job.
Create a HyperparameterTuner bound to an existing hyperparameter tuning job. After attaching, if there exists a
best training job (or any other com... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.