|
| 1 | +# Copyright 2017-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 __future__ import absolute_import |
| 14 | + |
| 15 | +from sagemaker.amazon.amazon_estimator import AmazonAlgorithmEstimatorBase, registry |
| 16 | +from sagemaker.amazon.common import numpy_to_record_serializer, record_deserializer |
| 17 | +from sagemaker.amazon.hyperparameter import Hyperparameter as hp # noqa |
| 18 | +from sagemaker.amazon.validation import ge, isin |
| 19 | +from sagemaker.predictor import RealTimePredictor |
| 20 | +from sagemaker.model import Model |
| 21 | +from sagemaker.session import Session |
| 22 | + |
| 23 | + |
| 24 | +class KNN(AmazonAlgorithmEstimatorBase): |
| 25 | + repo_name = 'knn' |
| 26 | + repo_version = 1 |
| 27 | + |
| 28 | + k = hp('k', (ge(1)), 'An integer greater than 0', int) |
| 29 | + sample_size = hp('sample_size', (ge(1)), 'An integer greater than 0', int) |
| 30 | + predictor_type = hp('predictor_type', isin('classifier', 'regressor'), |
| 31 | + 'One of "classifier" or "regressor"', str) |
| 32 | + dimension_reduction_target = hp('dimension_reduction_target', (ge(1)), |
| 33 | + 'An integer greater than 0 and less than feature_dim', int) |
| 34 | + dimension_reduction_type = hp('dimension_reduction_type', isin('sign', 'fjlt'), 'One of "sign" or "fjlt"', str) |
| 35 | + index_metric = hp('index_metric', isin('COSINE', 'INNER_PRODUCT', 'L2'), |
| 36 | + 'One of "COSINE", "INNER_PRODUCT", "L2"', str) |
| 37 | + index_type = hp('index_type', isin('faiss.Flat', 'faiss.IVFFlat', 'faiss.IVFPQ'), |
| 38 | + 'One of "faiss.Flat", "faiss.IVFFlat", "faiss.IVFPQ"', str) |
| 39 | + faiss_index_ivf_nlists = hp('faiss_index_ivf_nlists', (), '"auto" or an integer greater than 0', str) |
| 40 | + faiss_index_pq_m = hp('faiss_index_pq_m', (ge(1)), 'An integer greater than 0', int) |
| 41 | + |
| 42 | + def __init__(self, role, train_instance_count, train_instance_type, k, sample_size, predictor_type, |
| 43 | + dimension_reduction_type=None, dimension_reduction_target=None, index_type=None, |
| 44 | + index_metric=None, faiss_index_ivf_nlists=None, faiss_index_pq_m=None, **kwargs): |
| 45 | + """k-nearest neighbors (KNN) is :class:`Estimator` used for classification and regression. |
| 46 | +
|
| 47 | + This Estimator may be fit via calls to |
| 48 | + :meth:`~sagemaker.amazon.amazon_estimator.AmazonAlgorithmEstimatorBase.fit`. It requires Amazon |
| 49 | + :class:`~sagemaker.amazon.record_pb2.Record` protobuf serialized data to be stored in S3. |
| 50 | + There is an utility :meth:`~sagemaker.amazon.amazon_estimator.AmazonAlgorithmEstimatorBase.record_set` that |
| 51 | + can be used to upload data to S3 and creates :class:`~sagemaker.amazon.amazon_estimator.RecordSet` to be passed |
| 52 | + to the `fit` call. |
| 53 | +
|
| 54 | + To learn more about the Amazon protobuf Record class and how to prepare bulk data in this format, please |
| 55 | + consult AWS technical documentation: https://docs.aws.amazon.com/sagemaker/latest/dg/cdf-training.html |
| 56 | +
|
| 57 | + After this Estimator is fit, model data is stored in S3. The model may be deployed to an Amazon SageMaker |
| 58 | + Endpoint by invoking :meth:`~sagemaker.amazon.estimator.EstimatorBase.deploy`. As well as deploying an Endpoint, |
| 59 | + deploy returns a :class:`~sagemaker.amazon.knn.KNNPredictor` object that can be used |
| 60 | + for inference calls using the trained model hosted in the SageMaker Endpoint. |
| 61 | +
|
| 62 | + KNN Estimators can be configured by setting hyperparameters. The available hyperparameters for |
| 63 | + KNN are documented below. |
| 64 | +
|
| 65 | + For further information on the AWS KNN algorithm, |
| 66 | + please consult AWS technical documentation: https://docs.aws.amazon.com/sagemaker/latest/dg/knn.html |
| 67 | +
|
| 68 | + Args: |
| 69 | + role (str): An AWS IAM role (either name or full ARN). The Amazon SageMaker training jobs and |
| 70 | + APIs that create Amazon SageMaker endpoints use this role to access |
| 71 | + training data and model artifacts. After the endpoint is created, |
| 72 | + the inference code might use the IAM role, if accessing AWS resource. |
| 73 | + train_instance_type (str): Type of EC2 instance to use for training, for example, 'ml.c4.xlarge'. |
| 74 | + k (int): Required. Number of nearest neighbors. |
| 75 | + sample_size(int): Required. Number of data points to be sampled from the training data set. |
| 76 | + predictor_type (str): Required. Type of inference to use on the data's labels, |
| 77 | + allowed values are 'classifier' and 'regressor'. |
| 78 | + dimension_reduction_type (str): Optional. Type of dimension reduction technique to use. |
| 79 | + Valid values: “sign”, “fjlt” |
| 80 | + dimension_reduction_target (int): Optional. Target dimension to reduce to. Required when |
| 81 | + dimension_reduction_type is specified. |
| 82 | + index_type (str): Optional. Type of index to use. Valid values are |
| 83 | + “faiss.Flat”, “faiss.IVFFlat”, “faiss.IVFPQ”. |
| 84 | + index_metric(str): Optional. Distance metric to measure between points when finding nearest neighbors. |
| 85 | + Valid values are "COSINE", "INNER_PRODUCT", "L2" |
| 86 | + faiss_index_ivf_nlists(str): Optional. Number of centroids to construct in the index if |
| 87 | + index_type is “faiss.IVFFlat” or “faiss.IVFPQ”. |
| 88 | + faiss_index_pq_m(int): Optional. Number of vector sub-components to construct in the index, |
| 89 | + if index_type is “faiss.IVFPQ”. |
| 90 | + **kwargs: base class keyword argument values. |
| 91 | + """ |
| 92 | + |
| 93 | + super(KNN, self).__init__(role, train_instance_count, train_instance_type, **kwargs) |
| 94 | + self.k = k |
| 95 | + self.sample_size = sample_size |
| 96 | + self.predictor_type = predictor_type |
| 97 | + self.dimension_reduction_type = dimension_reduction_type |
| 98 | + self.dimension_reduction_target = dimension_reduction_target |
| 99 | + self.index_type = index_type |
| 100 | + self.index_metric = index_metric |
| 101 | + self.faiss_index_ivf_nlists = faiss_index_ivf_nlists |
| 102 | + self.faiss_index_pq_m = faiss_index_pq_m |
| 103 | + if dimension_reduction_type and not dimension_reduction_target: |
| 104 | + raise ValueError('"dimension_reduction_target" is required when "dimension_reduction_type" is set.') |
| 105 | + |
| 106 | + def create_model(self): |
| 107 | + """Return a :class:`~sagemaker.amazon.KNNModel` referencing the latest |
| 108 | + s3 model data produced by this Estimator.""" |
| 109 | + |
| 110 | + return KNNModel(self.model_data, self.role, sagemaker_session=self.sagemaker_session) |
| 111 | + |
| 112 | + def _prepare_for_training(self, records, mini_batch_size=None, job_name=None): |
| 113 | + super(KNN, self)._prepare_for_training(records, mini_batch_size=mini_batch_size, job_name=job_name) |
| 114 | + |
| 115 | + |
| 116 | +class KNNPredictor(RealTimePredictor): |
| 117 | + """Performs classification or regression prediction from input vectors. |
| 118 | +
|
| 119 | + The implementation of :meth:`~sagemaker.predictor.RealTimePredictor.predict` in this |
| 120 | + `RealTimePredictor` requires a numpy ``ndarray`` as input. The array should contain the |
| 121 | + same number of columns as the feature-dimension of the data used to fit the model this |
| 122 | + Predictor performs inference on. |
| 123 | +
|
| 124 | + :func:`predict` returns a list of :class:`~sagemaker.amazon.record_pb2.Record` objects, one |
| 125 | + for each row in the input ``ndarray``. The prediction is stored in the ``"predicted_label"`` |
| 126 | + key of the ``Record.label`` field.""" |
| 127 | + |
| 128 | + def __init__(self, endpoint, sagemaker_session=None): |
| 129 | + super(KNNPredictor, self).__init__(endpoint, sagemaker_session, serializer=numpy_to_record_serializer(), |
| 130 | + deserializer=record_deserializer()) |
| 131 | + |
| 132 | + |
| 133 | +class KNNModel(Model): |
| 134 | + """Reference S3 model data created by KNN estimator. Calling :meth:`~sagemaker.model.Model.deploy` |
| 135 | + creates an Endpoint and returns :class:`KNNPredictor`.""" |
| 136 | + |
| 137 | + def __init__(self, model_data, role, sagemaker_session=None): |
| 138 | + sagemaker_session = sagemaker_session or Session() |
| 139 | + repo = '{}:{}'.format(KNN.repo_name, KNN.repo_version) |
| 140 | + image = '{}/{}'.format(registry(sagemaker_session.boto_session.region_name, KNN.repo_name), repo) |
| 141 | + super(KNNModel, self).__init__(model_data, image, role, predictor_cls=KNNPredictor, |
| 142 | + sagemaker_session=sagemaker_session) |
0 commit comments