001/*
002 * Copyright (c) 2020, 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 ai.onnx.proto.OnnxMl;
020import com.oracle.labs.mlrg.olcut.util.Pair;
021import org.tribuo.Example;
022import org.tribuo.Excuse;
023import org.tribuo.Feature;
024import org.tribuo.ImmutableFeatureMap;
025import org.tribuo.ImmutableOutputInfo;
026import org.tribuo.Model;
027import org.tribuo.ONNXExportable;
028import org.tribuo.Output;
029import org.tribuo.Prediction;
030import org.tribuo.math.LinearParameters;
031import org.tribuo.math.la.DenseMatrix;
032import org.tribuo.math.la.Matrix;
033import org.tribuo.provenance.ModelProvenance;
034import org.tribuo.util.onnx.ONNXContext;
035import org.tribuo.util.onnx.ONNXInitializer;
036import org.tribuo.util.onnx.ONNXNode;
037import org.tribuo.util.onnx.ONNXOperators;
038import org.tribuo.util.onnx.ONNXPlaceholder;
039import org.tribuo.util.onnx.ONNXRef;
040
041import java.util.ArrayList;
042import java.util.Arrays;
043import java.util.Collections;
044import java.util.Comparator;
045import java.util.HashMap;
046import java.util.List;
047import java.util.Map;
048import java.util.Optional;
049import java.util.PriorityQueue;
050
051/**
052 * A linear model trained using SGD.
053 * <p>
054 * It's an {@link AbstractSGDModel} containing a {@link LinearParameters}, with
055 * the bias folded into the features.
056 * <p>
057 * See:
058 * <pre>
059 * Bottou L.
060 * "Large-Scale Machine Learning with Stochastic Gradient Descent"
061 * Proceedings of COMPSTAT, 2010.
062 * </pre>
063 */
064public abstract class AbstractLinearSGDModel<T extends Output<T>> extends AbstractSGDModel<T> {
065    private static final long serialVersionUID = 1L;
066
067    /**
068     * Constructs a linear model trained via SGD.
069     * @param name The model name.
070     * @param provenance The model provenance.
071     * @param featureIDMap The feature domain.
072     * @param outputIDInfo The output domain.
073     * @param parameters The model parameters.
074     * @param generatesProbabilities Does this model generate probabilities?
075     */
076    protected AbstractLinearSGDModel(String name, ModelProvenance provenance,
077                                     ImmutableFeatureMap featureIDMap, ImmutableOutputInfo<T> outputIDInfo,
078                                     LinearParameters parameters, boolean generatesProbabilities) {
079        super(name, provenance, featureIDMap, outputIDInfo, parameters, generatesProbabilities, true);
080    }
081
082    @Override
083    public Map<String, List<Pair<String, Double>>> getTopFeatures(int n) {
084        DenseMatrix baseWeights = (DenseMatrix) modelParameters.get()[0];
085        int maxFeatures = n < 0 ? featureIDMap.size() + 1 : n;
086
087        Comparator<Pair<String,Double>> comparator = Comparator.comparingDouble(p -> Math.abs(p.getB()));
088
089        //
090        // Use a priority queue to find the top N features.
091        int numClasses = baseWeights.getDimension1Size();
092        int numFeatures = baseWeights.getDimension2Size()-1; //Removing the bias feature.
093        Map<String, List<Pair<String,Double>>> map = new HashMap<>();
094        for (int i = 0; i < numClasses; i++) {
095            PriorityQueue<Pair<String,Double>> q = new PriorityQueue<>(maxFeatures, comparator);
096
097            for (int j = 0; j < numFeatures; j++) {
098                Pair<String,Double> curr = new Pair<>(featureIDMap.get(j).getName(), baseWeights.get(i,j));
099
100                if (q.size() < maxFeatures) {
101                    q.offer(curr);
102                } else if (comparator.compare(curr, q.peek()) > 0) {
103                    q.poll();
104                    q.offer(curr);
105                }
106            }
107            Pair<String,Double> curr = new Pair<>(BIAS_FEATURE, baseWeights.get(i,numFeatures));
108
109            if (q.size() < maxFeatures) {
110                q.offer(curr);
111            } else if (comparator.compare(curr, q.peek()) > 0) {
112                q.poll();
113                q.offer(curr);
114            }
115            List<Pair<String,Double>> b = new ArrayList<>();
116            while (q.size() > 0) {
117                b.add(q.poll());
118            }
119
120            Collections.reverse(b);
121            map.put(getDimensionName(i), b);
122        }
123        return map;
124    }
125
126    @Override
127    public Optional<Excuse<T>> getExcuse(Example<T> example) {
128        DenseMatrix baseWeights = (DenseMatrix) modelParameters.get()[0];
129        Prediction<T> prediction = predict(example);
130        Map<String, List<Pair<String, Double>>> weightMap = new HashMap<>();
131        int numClasses = baseWeights.getDimension1Size();
132        int numFeatures = baseWeights.getDimension2Size()-1;
133
134        for (int i = 0; i < numClasses; i++) {
135            List<Pair<String, Double>> classScores = new ArrayList<>();
136            for (Feature f : example) {
137                int id = featureIDMap.getID(f.getName());
138                if (id > -1) {
139                    double score = baseWeights.get(i,id) * f.getValue();
140                    classScores.add(new Pair<>(f.getName(), score));
141                }
142            }
143            classScores.add(new Pair<>(Model.BIAS_FEATURE, baseWeights.get(i,numFeatures)));
144            classScores.sort((Pair<String, Double> o1, Pair<String, Double> o2) -> o2.getB().compareTo(o1.getB()));
145            weightMap.put(getDimensionName(i), classScores);
146        }
147
148        return Optional.of(new Excuse<>(example, prediction, weightMap));
149    }
150
151    /**
152     * Gets the name of the indexed output dimension.
153     * @param index The output dimension index.
154     * @return The name of the requested output dimension.
155     */
156    protected abstract String getDimensionName(int index);
157
158    /**
159     * Returns a copy of the weights.
160     * @return A copy of the weights.
161     */
162    public DenseMatrix getWeightsCopy() {
163        return ((DenseMatrix)modelParameters.get()[0]).copy();
164    }
165
166    /**
167     * Takes the unnormalized ONNX output of this model and applies an appropriate normalizer from the concrete class.
168     * @param input Unnormalized ONNX leaf node.
169     * @return Normalized ONNX leaf node.
170     */
171    protected abstract ONNXNode onnxOutput(ONNXNode input);
172
173    /**
174     * @return Name to write into the ONNX Model.
175     */
176    protected abstract String onnxModelName();
177
178    /**
179     * Writes this {@link org.tribuo.Model} into {@link OnnxMl.GraphProto.Builder} inside the input's
180     * {@link ONNXContext}.
181     * @param input The input to the model graph.
182     * @return the output node of the model graph.
183     */
184    public ONNXNode writeONNXGraph(ONNXRef<?> input) {
185        ONNXContext onnx = input.onnxContext();
186
187        Matrix weightMatrix = (Matrix) modelParameters.get()[0];
188
189        ONNXInitializer weights = onnx.floatTensor("linear_sgd_weights", Arrays.asList(featureIDMap.size(), outputIDInfo.size()), fb -> {
190            for (int j = 0; j < weightMatrix.getDimension2Size() - 1; j++) {
191                for (int i = 0; i < weightMatrix.getDimension1Size(); i++) {
192                    fb.put((float) weightMatrix.get(i, j));
193                }
194            }
195        });
196        ONNXInitializer bias = onnx.floatTensor("linear_sgd_bias", Collections.singletonList(outputIDInfo.size()), fb -> {
197            for (int i = 0; i < weightMatrix.getDimension1Size(); i++) {
198                fb.put((float)weightMatrix.get(i,weightMatrix.getDimension2Size()-1));
199            }
200        });
201
202        return onnxOutput(input.apply(ONNXOperators.GEMM, Arrays.asList(weights, bias)));
203    }
204
205    /**
206     * Exports this {@link org.tribuo.Model} as an ONNX protobuf.
207     * @param domain A reverse-DNS name to namespace the model (e.g., org.tribuo.classification.sgd.linear).
208     * @param modelVersion A version number for this model.
209     * @return The ONNX ModelProto representing this Tribuo Model.
210     */
211    public OnnxMl.ModelProto exportONNXModel(String domain, long modelVersion) {
212        ONNXContext onnx = new ONNXContext();
213        onnx.setName(onnxModelName());
214        ONNXPlaceholder input = onnx.floatInput("input", featureIDMap.size());
215        ONNXPlaceholder output = onnx.floatOutput("output", outputIDInfo.size());
216        writeONNXGraph(input).assignTo(output);
217        return ONNXExportable.buildModel(onnx, domain, modelVersion, this);
218    }
219
220}