001/* 002 * Copyright (c) 2015-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.classification.mnb; 018 019import com.oracle.labs.mlrg.olcut.config.Config; 020import com.oracle.labs.mlrg.olcut.provenance.Provenance; 021import com.oracle.labs.mlrg.olcut.util.Pair; 022import org.tribuo.Dataset; 023import org.tribuo.Example; 024import org.tribuo.Feature; 025import org.tribuo.ImmutableFeatureMap; 026import org.tribuo.ImmutableOutputInfo; 027import org.tribuo.Model; 028import org.tribuo.Trainer; 029import org.tribuo.WeightedExamples; 030import org.tribuo.classification.Label; 031import org.tribuo.math.la.DenseSparseMatrix; 032import org.tribuo.math.la.SparseVector; 033import org.tribuo.provenance.ModelProvenance; 034import org.tribuo.provenance.TrainerProvenance; 035import org.tribuo.provenance.impl.TrainerProvenanceImpl; 036 037import java.time.OffsetDateTime; 038import java.util.HashMap; 039import java.util.Map; 040 041/** 042 * A {@link Trainer} which trains a multinomial Naive Bayes model with Laplace smoothing. 043 * <p> 044 * All feature values must be non-negative. 045 * <p> 046 * See: 047 * <pre> 048 * Wang S, Manning CD. 049 * "Baselines and Bigrams: Simple, Good Sentiment and Topic Classification" 050 * Proceedings of the 50th Annual Meeting of the Association for Computational Linguistics, 2012. 051 * </pre> 052 */ 053public class MultinomialNaiveBayesTrainer implements Trainer<Label>, WeightedExamples { 054 055 @Config(description="Smoothing parameter.") 056 private double alpha = 1.0; 057 058 private int trainInvocationCount = 0; 059 060 /** 061 * Constructs a multinomial naive bayes trainer using a smoothing value of 1.0. 062 */ 063 public MultinomialNaiveBayesTrainer() { 064 this(1.0); 065 } 066 067 /** 068 * Constructs a multinomial naive bayes trainer with the specified smoothing value. 069 * @param alpha The smoothing value. 070 */ 071 //TODO support different alphas for different features? 072 public MultinomialNaiveBayesTrainer(double alpha) { 073 if(alpha <= 0.0) { 074 throw new IllegalArgumentException("alpha parameter must be > 0"); 075 } 076 this.alpha = alpha; 077 } 078 079 @Override 080 public Model<Label> train(Dataset<Label> examples, Map<String, Provenance> runProvenance) { 081 return train(examples, runProvenance, INCREMENT_INVOCATION_COUNT); 082 } 083 084 @Override 085 public Model<Label> train(Dataset<Label> examples, Map<String, Provenance> runProvenance, int invocationCount) { 086 if (examples.getOutputInfo().getUnknownCount() > 0) { 087 throw new IllegalArgumentException("The supplied Dataset contained unknown Outputs, and this Trainer is supervised."); 088 } 089 ImmutableOutputInfo<Label> labelInfos = examples.getOutputIDInfo(); 090 ImmutableFeatureMap featureInfos = examples.getFeatureIDMap(); 091 092 Map<Integer, Map<Integer, Double>> labelWeights = new HashMap<>(); 093 094 for (Pair<Integer,Label> label : labelInfos) { 095 labelWeights.put(label.getA(), new HashMap<>()); 096 } 097 098 for (Example<Label> ex : examples) { 099 int idx = labelInfos.getID(ex.getOutput()); 100 Map<Integer, Double> featureMap = labelWeights.get(idx); 101 double curWeight = ex.getWeight(); 102 for (Feature feat : ex) { 103 if (feat.getValue() < 0.0) { 104 throw new IllegalStateException("Multinomial Naive Bayes requires non-negative features. Found feature " + feat.toString()); 105 } 106 featureMap.merge(featureInfos.getID(feat.getName()), curWeight*feat.getValue(), Double::sum); 107 } 108 } 109 if(invocationCount != INCREMENT_INVOCATION_COUNT) { 110 setInvocationCount(invocationCount); 111 } 112 TrainerProvenance trainerProvenance = getProvenance(); 113 ModelProvenance provenance = new ModelProvenance(MultinomialNaiveBayesModel.class.getName(), OffsetDateTime.now(), examples.getProvenance(), trainerProvenance, runProvenance); 114 trainInvocationCount++; 115 116 SparseVector[] labelVectors = new SparseVector[labelInfos.size()]; 117 118 for(int i = 0; i < labelInfos.size(); i++) { 119 SparseVector sv = SparseVector.createSparseVector(featureInfos.size(), labelWeights.get(i)); 120 double unsmoothedZ = sv.oneNorm(); 121 sv.foreachInPlace(d -> Math.log((d + alpha) / (unsmoothedZ + (featureInfos.size() * alpha)))); 122 labelVectors[i] = sv; 123 } 124 125 DenseSparseMatrix labelWordProbs = DenseSparseMatrix.createFromSparseVectors(labelVectors); 126 127 return new MultinomialNaiveBayesModel("", provenance, featureInfos, labelInfos, labelWordProbs, alpha); 128 } 129 130 @Override 131 public int getInvocationCount() { 132 return trainInvocationCount; 133 } 134 135 @Override 136 public void setInvocationCount(int invocationCount) { 137 if(invocationCount < 0){ 138 throw new IllegalArgumentException("The supplied invocationCount is less than zero."); 139 } 140 141 this.trainInvocationCount = invocationCount; 142 } 143 144 @Override 145 public String toString() { 146 return "MultinomialNaiveBayesTrainer(alpha=" + alpha + ")"; 147 } 148 149 @Override 150 public TrainerProvenance getProvenance() { 151 return new TrainerProvenanceImpl(this); 152 } 153}