|
| 1 | +# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"). You |
| 4 | +# may not use this file except in compliance with the License. A copy of |
| 5 | +# the License is located at |
| 6 | +# |
| 7 | +# http://aws.amazon.com/apache2.0/ |
| 8 | +# |
| 9 | +# or in the "license" file accompanying this file. This file is |
| 10 | +# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF |
| 11 | +# ANY KIND, either express or implied. See the License for the specific |
| 12 | +# language governing permissions and limitations under the License. |
| 13 | +from sagemaker.amazon.amazon_estimator import AmazonAlgorithmEstimatorBase, registry |
| 14 | +from sagemaker.amazon.common import numpy_to_record_serializer, record_deserializer |
| 15 | +from sagemaker.amazon.hyperparameter import Hyperparameter as hp # noqa |
| 16 | +from sagemaker.amazon.validation import ge, le |
| 17 | +from sagemaker.predictor import RealTimePredictor |
| 18 | +from sagemaker.model import Model |
| 19 | +from sagemaker.session import Session |
| 20 | + |
| 21 | + |
| 22 | +class RandomCutForest(AmazonAlgorithmEstimatorBase): |
| 23 | + |
| 24 | + repo_name = 'randomcutforest' |
| 25 | + repo_version = 1 |
| 26 | + MINI_BATCH_SIZE = 1000 |
| 27 | + |
| 28 | + eval_metrics = hp(name='eval_metrics', |
| 29 | + validation_message='A comma separated list of "accuracy" or "precision_recall_fscore"', |
| 30 | + data_type=list) |
| 31 | + |
| 32 | + num_trees = hp('num_trees', (ge(50), le(1000)), 'An integer in [50, 1000]', int) |
| 33 | + num_samples_per_tree = hp('num_samples_per_tree', (ge(1), le(2048)), 'An integer in [1, 2048]', int) |
| 34 | + feature_dim = hp("feature_dim", (ge(1), le(10000)), 'An integer in [1, 10000]', int) |
| 35 | + |
| 36 | + def __init__(self, role, train_instance_count, train_instance_type, |
| 37 | + num_samples_per_tree=None, num_trees=None, eval_metrics=None, **kwargs): |
| 38 | + """RandomCutForest is :class:`Estimator` used for anomaly detection. |
| 39 | +
|
| 40 | + This Estimator may be fit via calls to |
| 41 | + :meth:`~sagemaker.amazon.amazon_estimator.AmazonAlgorithmEstimatorBase.fit`. It requires Amazon |
| 42 | + :class:`~sagemaker.amazon.record_pb2.Record` protobuf serialized data to be stored in S3. |
| 43 | + There is an utility :meth:`~sagemaker.amazon.amazon_estimator.AmazonAlgorithmEstimatorBase.record_set` that |
| 44 | + can be used to upload data to S3 and creates :class:`~sagemaker.amazon.amazon_estimator.RecordSet` to be passed |
| 45 | + to the `fit` call. |
| 46 | +
|
| 47 | + To learn more about the Amazon protobuf Record class and how to prepare bulk data in this format, please |
| 48 | + consult AWS technical documentation: https://docs.aws.amazon.com/sagemaker/latest/dg/cdf-training.html |
| 49 | +
|
| 50 | + After this Estimator is fit, model data is stored in S3. The model may be deployed to an Amazon SageMaker |
| 51 | + Endpoint by invoking :meth:`~sagemaker.amazon.estimator.EstimatorBase.deploy`. As well as deploying an |
| 52 | + Endpoint, deploy returns a :class:`~sagemaker.amazon.ntm.RandomCutForestPredictor` object that can be used |
| 53 | + for inference calls using the trained model hosted in the SageMaker Endpoint. |
| 54 | +
|
| 55 | + RandomCutForest Estimators can be configured by setting hyperparameters. The available hyperparameters for |
| 56 | + RandomCutForest are documented below. |
| 57 | +
|
| 58 | + For further information on the AWS Random Cut Forest algorithm, |
| 59 | + please consult AWS technical documentation: https://docs.aws.amazon.com/sagemaker/latest/dg/randomcutforest.html |
| 60 | +
|
| 61 | + Args: |
| 62 | + role (str): An AWS IAM role (either name or full ARN). The Amazon SageMaker training jobs and |
| 63 | + APIs that create Amazon SageMaker endpoints use this role to access |
| 64 | + training data and model artifacts. After the endpoint is created, |
| 65 | + the inference code might use the IAM role, if accessing AWS resource. |
| 66 | + train_instance_count (int): Number of Amazon EC2 instances to use for training. |
| 67 | + train_instance_type (str): Type of EC2 instance to use for training, for example, 'ml.c4.xlarge'. |
| 68 | + num_samples_per_tree (int): Optional. The number of samples used to build each tree in the forest. |
| 69 | + The total number of samples drawn from the train dataset is num_trees * num_samples_per_tree. |
| 70 | + num_trees (int): Optional. The number of trees used in the forest. |
| 71 | + eval_metrics(list): Optional. JSON list of metrics types to be used for reporting the score for the model. |
| 72 | + Allowed values are "accuracy", "precision_recall_fscore": positive and negative precision, recall, |
| 73 | + and f1 scores. If test data is provided, the score shall be reported in terms of all requested metrics. |
| 74 | + **kwargs: base class keyword argument values. |
| 75 | + """ |
| 76 | + |
| 77 | + super(RandomCutForest, self).__init__(role, train_instance_count, train_instance_type, **kwargs) |
| 78 | + self.num_samples_per_tree = num_samples_per_tree |
| 79 | + self.num_trees = num_trees |
| 80 | + self.eval_metrics = eval_metrics |
| 81 | + |
| 82 | + def create_model(self): |
| 83 | + """Return a :class:`~sagemaker.amazon.RandomCutForestModel` referencing the latest |
| 84 | + s3 model data produced by this Estimator.""" |
| 85 | + |
| 86 | + return RandomCutForestModel(self.model_data, self.role, sagemaker_session=self.sagemaker_session) |
| 87 | + |
| 88 | + def fit(self, records, mini_batch_size=None, **kwargs): |
| 89 | + if mini_batch_size is None: |
| 90 | + mini_batch_size = RandomCutForest.MINI_BATCH_SIZE |
| 91 | + elif mini_batch_size != RandomCutForest.MINI_BATCH_SIZE: |
| 92 | + raise ValueError("Random Cut Forest uses a fixed mini_batch_size of {}" |
| 93 | + .format(RandomCutForest.MINI_BATCH_SIZE)) |
| 94 | + super(RandomCutForest, self).fit(records, mini_batch_size, **kwargs) |
| 95 | + |
| 96 | + |
| 97 | +class RandomCutForestPredictor(RealTimePredictor): |
| 98 | + """Assigns an anomaly score to each of the datapoints provided. |
| 99 | +
|
| 100 | + The implementation of :meth:`~sagemaker.predictor.RealTimePredictor.predict` in this |
| 101 | + `RealTimePredictor` requires a numpy ``ndarray`` as input. The array should contain the |
| 102 | + same number of columns as the feature-dimension of the data used to fit the model this |
| 103 | + Predictor performs inference on. |
| 104 | +
|
| 105 | + :meth:`predict()` returns a list of :class:`~sagemaker.amazon.record_pb2.Record` objects, |
| 106 | + one for each row in the input. Each row's score is stored in the key ``score`` of the |
| 107 | + ``Record.label`` field.""" |
| 108 | + |
| 109 | + def __init__(self, endpoint, sagemaker_session=None): |
| 110 | + super(RandomCutForestPredictor, self).__init__(endpoint, sagemaker_session, |
| 111 | + serializer=numpy_to_record_serializer(), |
| 112 | + deserializer=record_deserializer()) |
| 113 | + |
| 114 | + |
| 115 | +class RandomCutForestModel(Model): |
| 116 | + """Reference RandomCutForest s3 model data. Calling :meth:`~sagemaker.model.Model.deploy` creates an |
| 117 | + Endpoint and returns a Predictor that calculates anomaly scores for datapoints.""" |
| 118 | + |
| 119 | + def __init__(self, model_data, role, sagemaker_session=None): |
| 120 | + sagemaker_session = sagemaker_session or Session() |
| 121 | + repo = '{}:{}'.format(RandomCutForest.repo_name, RandomCutForest.repo_version) |
| 122 | + image = '{}/{}'.format(registry(sagemaker_session.boto_session.region_name, |
| 123 | + RandomCutForest.repo_name), repo) |
| 124 | + super(RandomCutForestModel, self).__init__(model_data, image, role, |
| 125 | + predictor_cls=RandomCutForestPredictor, |
| 126 | + sagemaker_session=sagemaker_session) |
0 commit comments