001/*
002 * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.tribuo.common.sgd;
018
019import org.tribuo.Example;
020import org.tribuo.ImmutableFeatureMap;
021import org.tribuo.ImmutableOutputInfo;
022import org.tribuo.Model;
023import org.tribuo.Output;
024import org.tribuo.math.FeedForwardParameters;
025import org.tribuo.math.la.DenseVector;
026import org.tribuo.math.la.SGDVector;
027import org.tribuo.math.la.SparseVector;
028import org.tribuo.provenance.ModelProvenance;
029
030/**
031 * A model trained using SGD.
032 * <p>
033 * See:
034 * <pre>
035 * Bottou L.
036 * "Large-Scale Machine Learning with Stochastic Gradient Descent"
037 * Proceedings of COMPSTAT, 2010.
038 * </pre>
039 */
040public abstract class AbstractSGDModel<T extends Output<T>> extends Model<T> {
041    private static final long serialVersionUID = 1L;
042
043    /**
044     * The weights for this model.
045     */
046    // Note this is not final to allow backwards compatibility for 4.0 models which need to rewrite the field on load.
047    protected FeedForwardParameters modelParameters;
048
049    // Defaults to true for backwards compatibility with 4.0 models, not final due to this defaulting.
050    protected boolean addBias = true;
051
052    /**
053     * Constructs a linear model trained via SGD.
054     * @param name The model name.
055     * @param provenance The model provenance.
056     * @param featureIDMap The feature domain.
057     * @param outputIDInfo The output domain.
058     * @param weights The model weights.
059     * @param generatesProbabilities Does this model generate probabilities?
060     * @param addBias Should the model add a bias feature to the feature vector?
061     */
062    protected AbstractSGDModel(String name, ModelProvenance provenance,
063                               ImmutableFeatureMap featureIDMap, ImmutableOutputInfo<T> outputIDInfo,
064                               FeedForwardParameters weights, boolean generatesProbabilities, boolean addBias) {
065        super(name, provenance, featureIDMap, outputIDInfo, generatesProbabilities);
066        this.modelParameters = weights;
067        this.addBias = addBias;
068    }
069
070    /**
071     * Generates the dense vector prediction from the supplied example.
072     * @param example The example to use for prediction.
073     * @return The prediction and the number of features involved.
074     */
075    protected PredAndActive predictSingle(Example<T> example) {
076        SGDVector features;
077        if (example.size() == featureIDMap.size()) {
078            features = DenseVector.createDenseVector(example, featureIDMap, addBias);
079        } else {
080            features = SparseVector.createSparseVector(example, featureIDMap, addBias);
081        }
082        int minNumFeatures = addBias ? 1 : 0;
083        if (features.numActiveElements() == minNumFeatures) {
084            throw new IllegalArgumentException("No features found in Example " + example.toString());
085        }
086        return new PredAndActive(modelParameters.predict(features),features.numActiveElements());
087    }
088
089    /**
090     * Returns a copy of the model parameters.
091     * @return A copy of the model parameters.
092     */
093    public FeedForwardParameters getModelParameters() {
094        return modelParameters.copy();
095    }
096
097    /**
098     * A nominal tuple used to capture the prediction and the number of active features used by the model.
099     */
100    protected static final class PredAndActive {
101        /**
102         * The vector prediction.
103         */
104        public final DenseVector prediction;
105        /**
106         * The number of active features used in the prediction.
107         */
108        public final int numActiveFeatures;
109
110        PredAndActive(DenseVector prediction, int numActiveFeatures) {
111            this.prediction = prediction;
112            this.numActiveFeatures = numActiveFeatures;
113        }
114    }
115}