|
| 1 | +# Copyright 2017 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 gt, isint, isnumber |
| 17 | +from sagemaker.predictor import RealTimePredictor |
| 18 | +from sagemaker.model import Model |
| 19 | +from sagemaker.session import Session |
| 20 | + |
| 21 | + |
| 22 | +class LDA(AmazonAlgorithmEstimatorBase): |
| 23 | + |
| 24 | + repo = 'lda:1' |
| 25 | + |
| 26 | + num_topics = hp('num_topics', (gt(0), isint), 'An integer greater than zero') |
| 27 | + alpha0 = hp('alpha0', isnumber, "A float value") |
| 28 | + max_restarts = hp('max_restarts', (gt(0), isint), 'An integer greater than zero') |
| 29 | + max_iterations = hp('max_iterations', (gt(0), isint), 'An integer greater than zero') |
| 30 | + tol = hp('tol', (gt(0), isnumber), "A positive float") |
| 31 | + |
| 32 | + def __init__(self, role, train_instance_type, num_topics, |
| 33 | + alpha0=None, max_restarts=None, max_iterations=None, tol=None, **kwargs): |
| 34 | + """Latent Dirichlet Allocation (LDA) is :class:`Estimator` used for unsupervised learning. |
| 35 | +
|
| 36 | + Amazon SageMaker Latent Dirichlet Allocation is an unsupervised learning algorithm that attempts to describe |
| 37 | + a set of observations as a mixture of distinct categories. LDA is most commonly used to discover |
| 38 | + a user-specified number of topics shared by documents within a text corpus. |
| 39 | + Here each observation is a document, the features are the presence (or occurrence count) of each word, and |
| 40 | + the categories are the topics. |
| 41 | +
|
| 42 | + This Estimator may be fit via calls to |
| 43 | + :meth:`~sagemaker.amazon.amazon_estimator.AmazonAlgorithmEstimatorBase.fit`. It requires Amazon |
| 44 | + :class:`~sagemaker.amazon.record_pb2.Record` protobuf serialized data to be stored in S3. |
| 45 | + There is an utility :meth:`~sagemaker.amazon.amazon_estimator.AmazonAlgorithmEstimatorBase.record_set` that |
| 46 | + can be used to upload data to S3 and creates :class:`~sagemaker.amazon.amazon_estimator.RecordSet` to be passed |
| 47 | + to the `fit` call. |
| 48 | +
|
| 49 | + To learn more about the Amazon protobuf Record class and how to prepare bulk data in this format, please |
| 50 | + consult AWS technical documentation: https://docs.aws.amazon.com/sagemaker/latest/dg/cdf-training.html |
| 51 | +
|
| 52 | + After this Estimator is fit, model data is stored in S3. The model may be deployed to an Amazon SageMaker |
| 53 | + Endpoint by invoking :meth:`~sagemaker.amazon.estimator.EstimatorBase.deploy`. As well as deploying an Endpoint, |
| 54 | + deploy returns a :class:`~sagemaker.amazon.lda.LDAPredictor` object that can be used |
| 55 | + for inference calls using the trained model hosted in the SageMaker Endpoint. |
| 56 | +
|
| 57 | + LDA Estimators can be configured by setting hyperparameters. The available hyperparameters for |
| 58 | + LDA are documented below. |
| 59 | +
|
| 60 | + For further information on the AWS LDA algorithm, |
| 61 | + please consult AWS technical documentation: https://docs.aws.amazon.com/sagemaker/latest/dg/lda.html |
| 62 | +
|
| 63 | + Args: |
| 64 | + role (str): An AWS IAM role (either name or full ARN). The Amazon SageMaker training jobs and |
| 65 | + APIs that create Amazon SageMaker endpoints use this role to access |
| 66 | + training data and model artifacts. After the endpoint is created, |
| 67 | + the inference code might use the IAM role, if accessing AWS resource. |
| 68 | + train_instance_type (str): Type of EC2 instance to use for training, for example, 'ml.c4.xlarge'. |
| 69 | + num_topics (int): The number of topics for LDA to find within the data. |
| 70 | + alpha0 (float): Initial guess for the concentration parameter |
| 71 | + max_restarts (int): The number of restarts to perform during the Alternating Least Squares (ALS) |
| 72 | + spectral decomposition phase of the algorithm. |
| 73 | + max_iterations (int): The maximum number of iterations to perform during the ALS phase of the algorithm. |
| 74 | + tol (float): Target error tolerance for the ALS phase of the algorithm. |
| 75 | + **kwargs: base class keyword argument values. |
| 76 | + """ |
| 77 | + |
| 78 | + # this algorithm only supports single instance training |
| 79 | + super(LDA, self).__init__(role, 1, train_instance_type, **kwargs) |
| 80 | + self.num_topics = num_topics |
| 81 | + self.alpha0 = alpha0 |
| 82 | + self.max_restarts = max_restarts |
| 83 | + self.max_iterations = max_iterations |
| 84 | + self.tol = tol |
| 85 | + |
| 86 | + def create_model(self): |
| 87 | + """Return a :class:`~sagemaker.amazon.FactorizationMachinesModel` referencing the latest |
| 88 | + s3 model data produced by this Estimator.""" |
| 89 | + |
| 90 | + return LDAModel(self.model_data, self.role, sagemaker_session=self.sagemaker_session) |
| 91 | + |
| 92 | + def fit(self, records, mini_batch_size, **kwargs): |
| 93 | + # mini_batch_size is required |
| 94 | + if mini_batch_size is None: |
| 95 | + raise ValueError("mini_batch_size must be set") |
| 96 | + if not isinstance(mini_batch_size, int) or mini_batch_size < 1: |
| 97 | + raise ValueError("mini_batch_size must be positive integer") |
| 98 | + |
| 99 | + super(LDA, self).fit(records, mini_batch_size, **kwargs) |
| 100 | + |
| 101 | + |
| 102 | +class LDAPredictor(RealTimePredictor): |
| 103 | + """Transforms input vectors to lower-dimesional representations. |
| 104 | +
|
| 105 | + The implementation of :meth:`~sagemaker.predictor.RealTimePredictor.predict` in this |
| 106 | + `RealTimePredictor` requires a numpy ``ndarray`` as input. The array should contain the |
| 107 | + same number of columns as the feature-dimension of the data used to fit the model this |
| 108 | + Predictor performs inference on. |
| 109 | +
|
| 110 | + :meth:`predict()` returns a list of :class:`~sagemaker.amazon.record_pb2.Record` objects, one |
| 111 | + for each row in the input ``ndarray``. The lower dimension vector result is stored in the ``projection`` |
| 112 | + key of the ``Record.label`` field.""" |
| 113 | + |
| 114 | + def __init__(self, endpoint, sagemaker_session=None): |
| 115 | + super(LDAPredictor, self).__init__(endpoint, sagemaker_session, serializer=numpy_to_record_serializer(), |
| 116 | + deserializer=record_deserializer()) |
| 117 | + |
| 118 | + |
| 119 | +class LDAModel(Model): |
| 120 | + """Reference LDA s3 model data. Calling :meth:`~sagemaker.model.Model.deploy` creates an Endpoint and return |
| 121 | + a Predictor that transforms vectors to a lower-dimensional representation.""" |
| 122 | + |
| 123 | + def __init__(self, model_data, role, sagemaker_session=None): |
| 124 | + sagemaker_session = sagemaker_session or Session() |
| 125 | + image = registry(sagemaker_session.boto_session.region_name, LDA.__name__) + "/" + LDA.repo |
| 126 | + super(LDAModel, self).__init__(model_data, image, role, predictor_cls=LDAPredictor, |
| 127 | + sagemaker_session=sagemaker_session) |
0 commit comments