001/*
002 * Copyright (c) 2015, 2022, 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.classification.mnb;
018
019import com.google.protobuf.Any;
020import com.google.protobuf.InvalidProtocolBufferException;
021import com.oracle.labs.mlrg.olcut.util.Pair;
022import org.tribuo.Example;
023import org.tribuo.Excuse;
024import org.tribuo.Feature;
025import org.tribuo.ImmutableFeatureMap;
026import org.tribuo.ImmutableOutputInfo;
027import org.tribuo.Model;
028import org.tribuo.Prediction;
029import org.tribuo.classification.Label;
030import org.tribuo.classification.mnb.protos.MultinomialNaiveBayesProto;
031import org.tribuo.impl.ModelDataCarrier;
032import org.tribuo.math.la.DenseSparseMatrix;
033import org.tribuo.math.la.DenseVector;
034import org.tribuo.math.la.SparseVector;
035import org.tribuo.math.la.Tensor;
036import org.tribuo.math.la.VectorTuple;
037import org.tribuo.math.util.ExpNormalizer;
038import org.tribuo.math.util.VectorNormalizer;
039import org.tribuo.protos.core.ModelProto;
040import org.tribuo.provenance.ModelProvenance;
041
042import java.util.ArrayList;
043import java.util.Comparator;
044import java.util.HashMap;
045import java.util.LinkedHashMap;
046import java.util.List;
047import java.util.Map;
048import java.util.Optional;
049
050/**
051 * A {@link Model} for multinomial Naive Bayes with Laplace smoothing.
052 * <p>
053 * All feature values must be non-negative, otherwise it will throw IllegalArgumentException.
054 * <p>
055 * See:
056 * <pre>
057 * Wang S, Manning CD.
058 * "Baselines and Bigrams: Simple, Good Sentiment and Topic Classification"
059 * Proceedings of the 50th Annual Meeting of the Association for Computational Linguistics, 2012.
060 * </pre>
061 */
062public class MultinomialNaiveBayesModel extends Model<Label> {
063    private static final long serialVersionUID = 1L;
064
065    /**
066     * Protobuf serialization version.
067     */
068    public static final int CURRENT_VERSION = 0;
069
070    private final DenseSparseMatrix labelWordProbs;
071    private final double alpha;
072
073    private static final VectorNormalizer normalizer = new ExpNormalizer();
074
075    MultinomialNaiveBayesModel(String name, ModelProvenance description, ImmutableFeatureMap featureInfos, ImmutableOutputInfo<Label> labelInfos, DenseSparseMatrix labelWordProbs, double alpha) {
076        super(name, description, featureInfos, labelInfos, true);
077        this.labelWordProbs = labelWordProbs;
078        this.alpha = alpha;
079    }
080
081    /**
082     * Deserialization factory.
083     * @param version The serialized object version.
084     * @param className The class name.
085     * @param message The serialized data.
086     * @throws InvalidProtocolBufferException If the protobuf could not be parsed from the {@code message}.
087     * @return The deserialized object.
088     */
089    public static MultinomialNaiveBayesModel deserializeFromProto(int version, String className, Any message) throws InvalidProtocolBufferException {
090        if (version < 0 || version > CURRENT_VERSION) {
091            throw new IllegalArgumentException("Unknown version " + version + ", this class supports at most version " + CURRENT_VERSION);
092        }
093        MultinomialNaiveBayesProto proto = message.unpack(MultinomialNaiveBayesProto.class);
094
095        ModelDataCarrier<?> carrier = ModelDataCarrier.deserialize(proto.getMetadata());
096        if (!carrier.outputDomain().getOutput(0).getClass().equals(Label.class)) {
097            throw new IllegalStateException("Invalid protobuf, output domain is not a label domain, found " + carrier.outputDomain().getClass());
098        }
099        @SuppressWarnings("unchecked") // guarded by getClass
100        ImmutableOutputInfo<Label> outputDomain = (ImmutableOutputInfo<Label>) carrier.outputDomain();
101
102        Tensor weights = Tensor.deserialize(proto.getLabelWordProbs());
103        if (!(weights instanceof DenseSparseMatrix)) {
104            throw new IllegalStateException("Invalid protobuf, label word probs must be a sparse matrix, found " + weights.getClass());
105        }
106        DenseSparseMatrix labelWordProbs = (DenseSparseMatrix) weights;
107        if (labelWordProbs.getDimension1Size() != carrier.outputDomain().size()) {
108            throw new IllegalStateException("Invalid protobuf, labelWordProbs not the right size, expected " + carrier.outputDomain().size() + ", found " + labelWordProbs.getDimension1Size());
109        }
110        if (labelWordProbs.getDimension2Size() != carrier.featureDomain().size()) {
111            throw new IllegalStateException("Invalid protobuf, labelWordProbs not the right size, expected " + carrier.featureDomain().size() + ", found " + labelWordProbs.getDimension2Size());
112        }
113
114        double alpha = proto.getAlpha();
115
116        if (alpha < 0.0) {
117            throw new IllegalStateException("Invalid protobuf, alpha must be non-negative, found " + alpha);
118        }
119
120        return new MultinomialNaiveBayesModel(carrier.name(),carrier.provenance(),carrier.featureDomain(),outputDomain,labelWordProbs,alpha);
121    }
122
123    @Override
124    public Prediction<Label> predict(Example<Label> example) {
125        SparseVector exVector = SparseVector.createSparseVector(example, featureIDMap, false);
126
127        if (exVector.minValue() < 0.0) {
128            throw new IllegalArgumentException("Example has negative feature values, example = " + example.toString());
129        }
130        if (exVector.numActiveElements() == 0) {
131            throw new IllegalArgumentException("No features found in Example " + example.toString());
132        }
133
134        /* Since we keep the label by feature matrix sparse, we need to manually
135         * add the weights contributed by smoothing unobserved features. We need to
136         * add in the portion of the inner product for the indices that are active
137         * in the example but are not active in the labelWordProbs matrix (but are
138         * still non-zero due to smoothing).
139         */
140        double[] alphaOffsets = new double[outputIDInfo.size()];
141        int vocabSize = labelWordProbs.getDimension2Size();
142        if (alpha > 0.0) {
143            for (int i = 0; i < outputIDInfo.size(); i++) {
144                double unobservedProb = Math.log(alpha / (labelWordProbs.getRow(i).oneNorm() + (vocabSize * alpha)));
145                int[] mismatchedIndices = exVector.difference(labelWordProbs.getRow(i));
146                double inExampleFactor = 0.0;
147                for (int idx = 0; idx < mismatchedIndices.length; idx++) {
148                    // TODO - exVector.get is slow as it does a binary search into the vector.
149                    inExampleFactor += exVector.get(mismatchedIndices[idx]) * unobservedProb;
150                }
151                alphaOffsets[i] = inExampleFactor;
152            }
153        }
154
155        DenseVector prediction = labelWordProbs.leftMultiply(exVector);
156        prediction.intersectAndAddInPlace(DenseVector.createDenseVector(alphaOffsets));
157        prediction.normalize(normalizer);
158        Map<String,Label> distribution = new LinkedHashMap<>();
159        Label maxLabel = null;
160        double maxScore = Double.NEGATIVE_INFINITY;
161        for(VectorTuple vt : prediction) {
162            String name = outputIDInfo.getOutput(vt.index).getLabel();
163            Label label = new Label(name, vt.value);
164            if (vt.value > maxScore) {
165                maxScore = vt.value;
166                maxLabel = label;
167            }
168            distribution.put(name,label);
169        }
170        Prediction<Label> p = new Prediction<>(maxLabel, distribution, exVector.numActiveElements(), example, true);
171        return p;
172    }
173
174    @Override
175    public Map<String, List<Pair<String, Double>>> getTopFeatures(int n) {
176        int maxFeatures = n < 0 ? featureIDMap.size() : n;
177        Map<String, List<Pair<String, Double>>> topFeatures = new HashMap<>();
178
179        for (Pair<Integer,Label> label : outputIDInfo) {
180            List<Pair<String, Double>> features = new ArrayList<>(labelWordProbs.numActiveElements(label.getA()));
181            for(VectorTuple vt : labelWordProbs.getRow(label.getA())) {
182                features.add(new Pair<>(featureIDMap.get(vt.index).getName(), vt.value));
183            }
184            features.sort(Comparator.comparing(x -> -x.getB()));
185            if(maxFeatures < featureIDMap.size()) {
186                features = features.subList(0, maxFeatures);
187            }
188            topFeatures.put(label.getB().getLabel(), features);
189        }
190        return topFeatures;
191    }
192
193    @Override
194    public Optional<Excuse<Label>> getExcuse(Example<Label> example) {
195        Map<String, List<Pair<String, Double>>> explanation = new HashMap<>();
196        for (Pair<Integer,Label> label : outputIDInfo) {
197            List<Pair<String, Double>> scores = new ArrayList<>();
198            for(Feature f : example) {
199                int id = featureIDMap.getID(f.getName());
200                if (id > -1) {
201                    scores.add(new Pair<>(f.getName(),labelWordProbs.getRow(label.getA()).get(id)));
202                }
203            }
204            explanation.put(label.getB().getLabel(), scores);
205        }
206        return Optional.of(new Excuse<>(example, predict(example), explanation));
207    }
208
209    @Override
210    protected MultinomialNaiveBayesModel copy(String newName, ModelProvenance newProvenance) {
211        return new MultinomialNaiveBayesModel(newName,newProvenance,featureIDMap,outputIDInfo,new DenseSparseMatrix(labelWordProbs),alpha);
212    }
213
214    @Override
215    public ModelProto serialize() {
216        ModelDataCarrier<Label> carrier = createDataCarrier();
217
218        MultinomialNaiveBayesProto.Builder modelBuilder = MultinomialNaiveBayesProto.newBuilder();
219        modelBuilder.setMetadata(carrier.serialize());
220        modelBuilder.setLabelWordProbs(labelWordProbs.serialize());
221        modelBuilder.setAlpha(alpha);
222
223        ModelProto.Builder builder = ModelProto.newBuilder();
224        builder.setSerializedData(Any.pack(modelBuilder.build()));
225        builder.setClassName(MultinomialNaiveBayesModel.class.getName());
226        builder.setVersion(CURRENT_VERSION);
227
228        return builder.build();
229    }
230}