001/* 002 * Copyright (c) 2015-2020, 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.libsvm; 018 019import com.oracle.labs.mlrg.olcut.config.ArgumentException; 020import com.oracle.labs.mlrg.olcut.config.ConfigurationManager; 021import com.oracle.labs.mlrg.olcut.config.Options; 022import com.oracle.labs.mlrg.olcut.config.UsageException; 023import org.tribuo.Model; 024import org.tribuo.Trainer; 025import org.tribuo.classification.Label; 026import org.tribuo.classification.TrainTestHelper; 027import org.tribuo.classification.ensemble.ClassificationEnsembleOptions; 028import org.tribuo.data.DataOptions; 029 030import java.io.IOException; 031import java.util.logging.Logger; 032 033/** 034 * Build and run a LibSVM classifier for a standard dataset. 035 */ 036public class TrainTest { 037 038 private static final Logger logger = Logger.getLogger(TrainTest.class.getName()); 039 040 /** 041 * Command line options. 042 */ 043 public static class TrainTestOptions implements Options { 044 @Override 045 public String getOptionsDescription() { 046 return "Trains and tests a LibSVM model on the specified datasets."; 047 } 048 049 /** 050 * The data loading options. 051 */ 052 public DataOptions general; 053 /** 054 * The LibSVM options. 055 */ 056 public LibSVMOptions libsvmOptions; 057 /** 058 * The ensemble options. 059 */ 060 public ClassificationEnsembleOptions ensembleOptions; 061 } 062 063 /** 064 * Runs a TrainTest CLI. 065 * @param args the command line arguments 066 * @throws IOException if there is any error reading the examples. 067 */ 068 public static void main(String[] args) throws IOException { 069 TrainTestOptions o = new TrainTestOptions(); 070 try (ConfigurationManager cm = new ConfigurationManager(args, o)) { 071 Trainer<Label> trainer = o.libsvmOptions.getTrainer(); 072 trainer = o.ensembleOptions.wrapTrainer(trainer); 073 Model<Label> model = TrainTestHelper.run(cm, o.general, trainer); 074 if (model instanceof LibSVMClassificationModel) { 075 logger.info("Used " + ((LibSVMClassificationModel) model).getNumberOfSupportVectors() + " support vectors"); 076 } 077 } catch (UsageException e) { 078 System.out.println(e.getUsage()); 079 } catch (ArgumentException e) { 080 System.out.println("Invalid argument: " + e.getMessage()); 081 } 082 } 083}