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.common.nearest; 018 019import com.oracle.labs.mlrg.olcut.config.Config; 020import com.oracle.labs.mlrg.olcut.config.PropertyException; 021import com.oracle.labs.mlrg.olcut.provenance.Provenance; 022import com.oracle.labs.mlrg.olcut.util.Pair; 023import org.tribuo.Dataset; 024import org.tribuo.Example; 025import org.tribuo.ImmutableFeatureMap; 026import org.tribuo.ImmutableOutputInfo; 027import org.tribuo.Model; 028import org.tribuo.Output; 029import org.tribuo.Trainer; 030import org.tribuo.common.nearest.KNNModel.Backend; 031import org.tribuo.ensemble.EnsembleCombiner; 032import org.tribuo.math.distance.DistanceType; 033import org.tribuo.math.la.DenseVector; 034import org.tribuo.math.la.SGDVector; 035import org.tribuo.math.la.SparseVector; 036import org.tribuo.math.neighbour.NeighboursQueryFactory; 037import org.tribuo.math.neighbour.NeighboursQueryFactoryType; 038import org.tribuo.math.neighbour.bruteforce.NeighboursBruteForceFactory; 039import org.tribuo.provenance.ModelProvenance; 040import org.tribuo.provenance.TrainerProvenance; 041import org.tribuo.provenance.impl.TrainerProvenanceImpl; 042 043import java.time.OffsetDateTime; 044import java.util.Map; 045 046/** 047 * A {@link Trainer} for k-nearest neighbour models. 048 */ 049public class KNNTrainer<T extends Output<T>> implements Trainer<T> { 050 051 /** 052 * The available distance functions. 053 * @deprecated 054 * This Enum is deprecated in version 4.3, replaced by {@link DistanceType} 055 */ 056 @Deprecated 057 public enum Distance { 058 /** 059 * L1 (or Manhattan) distance. 060 */ 061 L1(DistanceType.L1), 062 /** 063 * L2 (or Euclidean) distance. 064 */ 065 L2(DistanceType.L2), 066 /** 067 * Cosine similarity used as a distance measure. 068 */ 069 COSINE(DistanceType.COSINE); 070 071 private final DistanceType distanceType; 072 073 Distance(DistanceType distanceType) { 074 this.distanceType = distanceType; 075 } 076 077 /** 078 * Returns the {@link DistanceType} mapping for the enumeration's value. 079 * 080 * @return distanceType The {@link DistanceType} value. 081 */ 082 public DistanceType getDistanceType() { 083 return distanceType; 084 } 085 } 086 087 @Deprecated 088 @Config(description="The distance function used to measure nearest neighbours. This is now deprecated.") 089 private Distance distance; 090 091 @Config(description = "The distance function used to measure nearest neighbours.") 092 private org.tribuo.math.distance.Distance dist; 093 094 @Config(mandatory = true, description="The number of nearest neighbours to check.") 095 private int k; 096 097 @Config(mandatory = true, description="The combination function to aggregate the nearest neighbours.") 098 private EnsembleCombiner<T> combiner; 099 100 @Config(description="The number of threads to use for inference.") 101 private int numThreads = 1; 102 103 @Config(description="The threading model to use.") 104 private Backend backend = Backend.THREADPOOL; 105 106 @Config(description = "The nearest neighbour implementation factory to use.") 107 private NeighboursQueryFactory neighboursQueryFactory; 108 109 private int trainInvocationCount = 0; 110 111 /** 112 * For olcut. 113 */ 114 private KNNTrainer() {} 115 116 /** 117 * Creates a K-NN trainer using the supplied parameters. 118 * @param k The number of nearest neighbours to consider. 119 * @param dist The distance function. 120 * @param numThreads The number of threads to use. 121 * @param combiner The combination function to aggregate the k predictions. 122 * @param backend The computational backend. 123 * @param nqFactoryType The nearest neighbour implementation factory to use. 124 */ 125 public KNNTrainer(int k, org.tribuo.math.distance.Distance dist, int numThreads, EnsembleCombiner<T> combiner, 126 Backend backend, NeighboursQueryFactoryType nqFactoryType) { 127 this.k = k; 128 this.dist = dist; 129 this.numThreads = numThreads; 130 this.combiner = combiner; 131 this.backend = backend; 132 this.neighboursQueryFactory = NeighboursQueryFactoryType.getNeighboursQueryFactory(nqFactoryType, dist, numThreads); 133 postConfig(); 134 } 135 136 /** 137 * Creates a K-NN trainer using the supplied parameters. {@link #neighboursQueryFactory} defaults to 138 * {@link NeighboursBruteForceFactory}. 139 * @deprecated 140 * This Constructor is deprecated in version 4.3. 141 * 142 * @param k The number of nearest neighbours to consider. 143 * @param distance The distance function. 144 * @param numThreads The number of threads to use. 145 * @param combiner The combination function to aggregate the k predictions. 146 * @param backend The computational backend. 147 */ 148 @Deprecated 149 public KNNTrainer(int k, Distance distance, int numThreads, EnsembleCombiner<T> combiner, Backend backend) { 150 this(k, distance.getDistanceType().getDistance(), numThreads, combiner, backend, NeighboursQueryFactoryType.BRUTE_FORCE); 151 } 152 153 /** 154 * Creates a K-NN trainer using the supplied parameters. 155 * 156 * @param k The number of nearest neighbours to consider. 157 * @param numThreads The number of threads to use. 158 * @param combiner The combination function to aggregate the k predictions. 159 * @param backend The computational backend. 160 * @param neighboursQueryFactory The nearest neighbour implementation factory to use. 161 */ 162 public KNNTrainer(int k, int numThreads, EnsembleCombiner<T> combiner, 163 Backend backend, NeighboursQueryFactory neighboursQueryFactory) { 164 this.k = k; 165 this.dist = neighboursQueryFactory.getDistance(); 166 this.numThreads = numThreads; 167 this.combiner = combiner; 168 this.backend = backend; 169 this.neighboursQueryFactory = neighboursQueryFactory; 170 postConfig(); 171 } 172 173 /** 174 * Used by the OLCUT configuration system, and should not be called by external code. 175 */ 176 @Override 177 public synchronized void postConfig() { 178 if (k < 1) { 179 throw new PropertyException("","k","k must be greater than 0"); 180 } 181 182 if (this.distance != null) { 183 if (this.dist != null) { 184 throw new PropertyException("dist", "Both dist and distanceType must not both be set."); 185 } else { 186 this.dist = this.distance.getDistanceType().getDistance(); 187 this.distance = null; 188 } 189 } 190 191 if (neighboursQueryFactory == null) { 192 int numberThreads = (this.numThreads <= 0) ? 1 : this.numThreads; 193 this.neighboursQueryFactory = new NeighboursBruteForceFactory(dist, numberThreads); 194 } else { 195 if (!this.dist.equals(neighboursQueryFactory.getDistance())) { 196 throw new PropertyException("neighboursQueryFactory", "distType and its field on the " + 197 "NeighboursQueryFactory must be equal."); 198 } 199 } 200 } 201 202 @Override 203 public Model<T> train(Dataset<T> examples, Map<String, Provenance> runProvenance) { 204 return(train(examples, runProvenance, INCREMENT_INVOCATION_COUNT)); 205 } 206 207 @Override 208 public Model<T> train(Dataset<T> examples, Map<String, Provenance> runProvenance, int invocationCount) { 209 ImmutableFeatureMap featureIDMap = examples.getFeatureIDMap(); 210 ImmutableOutputInfo<T> labelIDMap = examples.getOutputIDInfo(); 211 212 @SuppressWarnings("unchecked") // generic array creation 213 Pair<SGDVector,T>[] vectors = new Pair[examples.size()]; 214 215 int i = 0; 216 for (Example<T> e : examples) { 217 if (e.size() == featureIDMap.size()) { 218 vectors[i] = new Pair<>(DenseVector.createDenseVector(e, featureIDMap, false),e.getOutput()); 219 } else { 220 vectors[i] = new Pair<>(SparseVector.createSparseVector(e,featureIDMap,false),e.getOutput()); 221 } 222 i++; 223 } 224 225 if(invocationCount != INCREMENT_INVOCATION_COUNT){ 226 setInvocationCount(invocationCount); 227 } 228 trainInvocationCount++; 229 230 ModelProvenance provenance = new ModelProvenance(KNNModel.class.getName(), OffsetDateTime.now(), examples.getProvenance(), getProvenance(), runProvenance); 231 232 return new KNNModel<>(k+"nn",provenance, featureIDMap, labelIDMap, false, k, dist, 233 numThreads, combiner, vectors, backend, neighboursQueryFactory); 234 } 235 236 @Override 237 public String toString() { 238 return "KNNTrainer(k="+k+",distance="+dist+",combiner="+combiner.toString()+",numThreads="+numThreads+")"; 239 } 240 241 @Override 242 public int getInvocationCount() { 243 return trainInvocationCount; 244 } 245 246 @Override 247 public void setInvocationCount(int invocationCount) { 248 if(invocationCount < 0){ 249 throw new IllegalArgumentException("The supplied invocationCount is less than zero."); 250 } 251 252 this.trainInvocationCount = invocationCount; 253 } 254 255 @Override 256 public TrainerProvenance getProvenance() { 257 return new TrainerProvenanceImpl(this); 258 } 259}