| 206 | } |
| 207 | |
| 208 | @Override |
| 209 | public void trainC(final ClassificationDataSet dataSet, final ExecutorService threadPool) |
| 210 | { |
| 211 | predicting = dataSet.getPredicting(); |
| 212 | learners = new ArrayList(rounds); |
| 213 | //Used to make the main thread wait for the working threads to finish before submiting a new job so we dont waist too much memory then we can use at once |
| 214 | final Semaphore waitForThread = new Semaphore(SystemInfo.LogicalCores); |
| 215 | //Used to make the main thread wait for the working threads to finish before returning |
| 216 | final CountDownLatch waitForFinish = new CountDownLatch(rounds); |
| 217 | |
| 218 | //Creat a synchrnozied view so we can add safely |
| 219 | final List synchronizedLearners = Collections.synchronizedList(learners); |
| 220 | final int[] sampleCounts = new int[dataSet.getSampleSize()]; |
| 221 | for(int i = 0; i < rounds; i++) |
| 222 | { |
| 223 | sampleWithReplacement(sampleCounts, sampleCounts.length+extraSamples, random); |
| 224 | final ClassificationDataSet sampleSet = getSampledDataSet(dataSet, sampleCounts); |
| 225 | |
| 226 | final Classifier learner = baseClassifier.clone(); |
| 227 | if(simultaniousTraining && threadPool != null) |
| 228 | { |
| 229 | try |
| 230 | { |
| 231 | //Wait for an available thread |
| 232 | waitForThread.acquire(); |
| 233 | threadPool.submit(new Runnable() { |
| 234 | |
| 235 | @Override |
| 236 | public void run() |
| 237 | { |
| 238 | learner.trainC(sampleSet); |
| 239 | synchronizedLearners.add(learner); |
| 240 | waitForThread.release();//Finish, allow another one to pass through |
| 241 | waitForFinish.countDown(); |
| 242 | } |
| 243 | }); |
| 244 | } |
| 245 | catch (InterruptedException ex) |
| 246 | { |
| 247 | Logger.getLogger(Bagging.class.getName()).log(Level.SEVERE, null, ex); |
| 248 | System.err.println(ex.getMessage()); |
| 249 | } |
| 250 | |
| 251 | } |
| 252 | else |
| 253 | { |
| 254 | if(threadPool != null) |
| 255 | learner.trainC(sampleSet, threadPool); |
| 256 | else |
| 257 | learner.trainC(sampleSet); |
| 258 | learners.add(learner); |
| 259 | } |
| 260 | } |
| 261 | |
| 262 | if (simultaniousTraining && threadPool != null) |
| 263 | try |
| 264 | { |
| 265 | waitForFinish.await(); |