INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Select the best match in a list or dictionary of choices.
def extract(query, choices, processor=default_processor, scorer=default_scorer, limit=5): """Select the best match in a list or dictionary of choices. Find best matches in a list or dictionary of choices, return a list of tuples containing the match and its score. If a dictionary is used, also returns ...
Get a list of the best matches to a collection of choices.
def extractBests(query, choices, processor=default_processor, scorer=default_scorer, score_cutoff=0, limit=5): """Get a list of the best matches to a collection of choices. Convenience function for getting the choices with best scores. Args: query: A string to match against choices: A list...
Find the single best match above a score in a list of choices.
def extractOne(query, choices, processor=default_processor, scorer=default_scorer, score_cutoff=0): """Find the single best match above a score in a list of choices. This is a convenience method which returns the single best choice. See extract() for the full arguments list. Args: query: A str...
This convenience function takes a list of strings containing duplicates and uses fuzzy matching to identify and remove duplicates. Specifically it uses the process. extract to identify duplicates that score greater than a user defined threshold. Then it looks for the longest item in the duplicate list since we assume t...
def dedupe(contains_dupes, threshold=70, scorer=fuzz.token_set_ratio): """This convenience function takes a list of strings containing duplicates and uses fuzzy matching to identify and remove duplicates. Specifically, it uses the process.extract to identify duplicates that score greater than a user defined...
If both objects aren t either both string or unicode instances force them to unicode
def make_type_consistent(s1, s2): """If both objects aren't either both string or unicode instances force them to unicode""" if isinstance(s1, str) and isinstance(s2, str): return s1, s2 elif isinstance(s1, unicode) and isinstance(s2, unicode): return s1, s2 else: return unicod...
Process string by -- removing all but letters and numbers -- trim whitespace -- force to lower case if force_ascii == True force convert to ascii
def full_process(s, force_ascii=False): """Process string by -- removing all but letters and numbers -- trim whitespace -- force to lower case if force_ascii == True, force convert to ascii""" if force_ascii: s = asciidammit(s) # Keep only Letters and Numbers (see Un...
Return the ratio of the most similar substring as a number between 0 and 100.
def partial_ratio(s1, s2): """"Return the ratio of the most similar substring as a number between 0 and 100.""" s1, s2 = utils.make_type_consistent(s1, s2) if len(s1) <= len(s2): shorter = s1 longer = s2 else: shorter = s2 longer = s1 m = SequenceMatcher(None, s...
Return a cleaned string with token sorted.
def _process_and_sort(s, force_ascii, full_process=True): """Return a cleaned string with token sorted.""" # pull tokens ts = utils.full_process(s, force_ascii=force_ascii) if full_process else s tokens = ts.split() # sort tokens and join sorted_string = u" ".join(sorted(tokens)) return sor...
Return a measure of the sequences similarity between 0 and 100 but sorting the token before comparing.
def token_sort_ratio(s1, s2, force_ascii=True, full_process=True): """Return a measure of the sequences' similarity between 0 and 100 but sorting the token before comparing. """ return _token_sort(s1, s2, partial=False, force_ascii=force_ascii, full_process=full_process)
Return the ratio of the most similar substring as a number between 0 and 100 but sorting the token before comparing.
def partial_token_sort_ratio(s1, s2, force_ascii=True, full_process=True): """Return the ratio of the most similar substring as a number between 0 and 100 but sorting the token before comparing. """ return _token_sort(s1, s2, partial=True, force_ascii=force_ascii, full_process=full_process)
Find all alphanumeric tokens in each string... - treat them as a set - construct two strings of the form: <sorted_intersection > <sorted_remainder > - take ratios of those two strings - controls for unordered partial matches
def _token_set(s1, s2, partial=True, force_ascii=True, full_process=True): """Find all alphanumeric tokens in each string... - treat them as a set - construct two strings of the form: <sorted_intersection><sorted_remainder> - take ratios of those two strings - controls fo...
Quick ratio comparison between two strings.
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
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.
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.
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
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
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 ): Name of the local training job being run.
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 environment variables to be passed to the hosting container.
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.
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.
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.
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.
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.
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: ...
Load the gluon model. Called once when hosting service starts.
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...
Transform a request using the Gluon model. Called once per request.
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...
Set hyperparameters needed for training.
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.
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
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.
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.
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.
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
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
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. OutputDataConfig ( dict ): Identifies the location where yo...
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.
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
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.
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
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
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.
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.
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.
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.
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.
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
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.
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.
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
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
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...
Group together as many records as possible to fit in the specified size
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...
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.
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
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.
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
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.
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.
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.
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.
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
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
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
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 s3 sync and then stops reading t...
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.
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.
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
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: ...