Search in sources :

Example 1 with ImmutableDataset

use of org.tribuo.ImmutableDataset in project tribuo by oracle.

the class TestXGBoost method loadDataset.

private Dataset<Label> loadDataset(XGBoostModel<Label> model, Path path) throws IOException {
    TextFeatureExtractor<Label> extractor = new TextFeatureExtractorImpl<>(new BasicPipeline(new BreakIteratorTokenizer(Locale.US), 2));
    TextDataSource<Label> src = new SimpleTextDataSource<>(path, new LabelFactory(), extractor);
    return new ImmutableDataset<>(src, model.getFeatureIDMap(), model.getOutputIDInfo(), false);
}
Also used : LabelFactory(org.tribuo.classification.LabelFactory) TextFeatureExtractorImpl(org.tribuo.data.text.impl.TextFeatureExtractorImpl) BasicPipeline(org.tribuo.data.text.impl.BasicPipeline) Label(org.tribuo.classification.Label) ImmutableDataset(org.tribuo.ImmutableDataset) BreakIteratorTokenizer(org.tribuo.util.tokens.impl.BreakIteratorTokenizer) SimpleTextDataSource(org.tribuo.data.text.impl.SimpleTextDataSource)

Example 2 with ImmutableDataset

use of org.tribuo.ImmutableDataset in project tribuo by oracle.

the class DataOptions method load.

/**
 * Loads the training and testing data from {@link #trainingPath} and {@link #testingPath}
 * according to the other parameters specified in this class.
 * @param outputFactory The output factory to use to process the inputs.
 * @param <T> The dataset output type.
 * @return A pair containing the training and testing datasets. The training dataset is element 'A' and the
 * testing dataset is element 'B'.
 * @throws IOException If the paths could not be loaded.
 */
public <T extends Output<T>> Pair<Dataset<T>, Dataset<T>> load(OutputFactory<T> outputFactory) throws IOException {
    logger.info(String.format("Loading data from %s", trainingPath));
    Dataset<T> train;
    Dataset<T> test;
    char separator;
    switch(inputFormat) {
        case SERIALIZED:
            // 
            // Load Tribuo serialised datasets.
            logger.info("Deserialising dataset from " + trainingPath);
            try (ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(trainingPath.toFile())));
                ObjectInputStream oits = new ObjectInputStream(new BufferedInputStream(new FileInputStream(testingPath.toFile())))) {
                @SuppressWarnings("unchecked") Dataset<T> tmp = (Dataset<T>) ois.readObject();
                train = tmp;
                if (minCount > 0) {
                    logger.info("Found " + train.getFeatureIDMap().size() + " features");
                    logger.info("Removing features that occur fewer than " + minCount + " times.");
                    train = new MinimumCardinalityDataset<>(train, minCount);
                }
                logger.info(String.format("Loaded %d training examples for %s", train.size(), train.getOutputs().toString()));
                logger.info("Found " + train.getFeatureIDMap().size() + " features, and " + train.getOutputInfo().size() + " response dimensions");
                @SuppressWarnings("unchecked") Dataset<T> deserTest = (Dataset<T>) oits.readObject();
                test = new ImmutableDataset<>(deserTest, deserTest.getSourceProvenance(), deserTest.getOutputFactory(), train.getFeatureIDMap(), train.getOutputIDInfo(), true);
            } catch (ClassNotFoundException e) {
                throw new IllegalArgumentException("Unknown class in serialised files", e);
            }
            break;
        case LIBSVM:
            // 
            // Load the libsvm text-based data format.
            LibSVMDataSource<T> trainSVMSource = new LibSVMDataSource<>(trainingPath, outputFactory);
            train = new MutableDataset<>(trainSVMSource);
            boolean zeroIndexed = trainSVMSource.isZeroIndexed();
            int maxFeatureID = trainSVMSource.getMaxFeatureID();
            if (minCount > 0) {
                logger.info("Removing features that occur fewer than " + minCount + " times.");
                train = new MinimumCardinalityDataset<>(train, minCount);
            }
            logger.info(String.format("Loaded %d training examples for %s", train.size(), train.getOutputs().toString()));
            logger.info("Found " + train.getFeatureIDMap().size() + " features, and " + train.getOutputInfo().size() + " response dimensions");
            test = new ImmutableDataset<>(new LibSVMDataSource<>(testingPath, outputFactory, zeroIndexed, maxFeatureID), train.getFeatureIDMap(), train.getOutputIDInfo(), false);
            break;
        case TEXT:
            // 
            // Using a simple Java break iterator to generate ngram features.
            TextFeatureExtractor<T> extractor;
            if (hashDim > 0) {
                extractor = new TextFeatureExtractorImpl<>(new TokenPipeline(new BreakIteratorTokenizer(Locale.US), ngram, termCounting, hashDim));
            } else {
                extractor = new TextFeatureExtractorImpl<>(new TokenPipeline(new BreakIteratorTokenizer(Locale.US), ngram, termCounting));
            }
            TextDataSource<T> trainSource = new SimpleTextDataSource<>(trainingPath, outputFactory, extractor);
            train = new MutableDataset<>(trainSource);
            if (minCount > 0) {
                logger.info("Removing features that occur fewer than " + minCount + " times.");
                train = new MinimumCardinalityDataset<>(train, minCount);
            }
            logger.info(String.format("Loaded %d training examples for %s", train.size(), train.getOutputs().toString()));
            logger.info("Found " + train.getFeatureIDMap().size() + " features, and " + train.getOutputInfo().size() + " response dimensions");
            TextDataSource<T> testSource = new SimpleTextDataSource<>(testingPath, outputFactory, extractor);
            test = new ImmutableDataset<>(testSource, train.getFeatureIDMap(), train.getOutputIDInfo(), false);
            break;
        case CSV:
            // Load the data using the simple CSV loader
            if (csvResponseName == null) {
                throw new IllegalArgumentException("Please supply a response column name");
            }
            separator = delimiter.value;
            CSVLoader<T> loader = new CSVLoader<>(separator, outputFactory);
            train = new MutableDataset<>(loader.loadDataSource(trainingPath, csvResponseName));
            logger.info(String.format("Loaded %d training examples for %s", train.size(), train.getOutputs().toString()));
            logger.info("Found " + train.getFeatureIDMap().size() + " features, and " + train.getOutputInfo().size() + " response dimensions");
            test = new MutableDataset<>(loader.loadDataSource(testingPath, csvResponseName));
            break;
        case COLUMNAR:
            if (rowProcessor == null) {
                throw new IllegalArgumentException("Please supply a RowProcessor");
            }
            OutputFactory<?> rowOutputFactory = rowProcessor.getResponseProcessor().getOutputFactory();
            if (!rowOutputFactory.equals(outputFactory)) {
                throw new IllegalArgumentException("The RowProcessor doesn't use the same kind of OutputFactory as the one supplied. RowProcessor has " + rowOutputFactory.getClass().getSimpleName() + ", supplied " + outputFactory.getClass().getName());
            }
            // checked by the if statement above
            @SuppressWarnings("unchecked") RowProcessor<T> typedRowProcessor = (RowProcessor<T>) rowProcessor;
            separator = delimiter.value;
            train = new MutableDataset<>(new CSVDataSource<>(trainingPath, typedRowProcessor, true, separator, csvQuoteChar));
            logger.info(String.format("Loaded %d training examples for %s", train.size(), train.getOutputs().toString()));
            logger.info("Found " + train.getFeatureIDMap().size() + " features, and " + train.getOutputInfo().size() + " response dimensions");
            test = new MutableDataset<>(new CSVDataSource<>(testingPath, typedRowProcessor, true, separator, csvQuoteChar));
            break;
        default:
            throw new IllegalArgumentException("Unsupported input format " + inputFormat);
    }
    logger.info(String.format("Loaded %d testing examples", test.size()));
    if (scaleFeatures) {
        logger.info("Fitting feature scaling");
        TransformationMap map = new TransformationMap(Collections.singletonList(new LinearScalingTransformation()));
        TransformerMap transformers = train.createTransformers(map, scaleIncZeros);
        logger.info("Applying scaling to training dataset");
        train = transformers.transformDataset(train);
        logger.info("Applying scaling to testing dataset");
        test = transformers.transformDataset(test);
    }
    return new Pair<>(train, test);
}
Also used : TransformerMap(org.tribuo.transform.TransformerMap) CSVDataSource(org.tribuo.data.csv.CSVDataSource) SimpleTextDataSource(org.tribuo.data.text.impl.SimpleTextDataSource) TransformationMap(org.tribuo.transform.TransformationMap) LinearScalingTransformation(org.tribuo.transform.transformations.LinearScalingTransformation) BufferedInputStream(java.io.BufferedInputStream) LibSVMDataSource(org.tribuo.datasource.LibSVMDataSource) RowProcessor(org.tribuo.data.columnar.RowProcessor) Pair(com.oracle.labs.mlrg.olcut.util.Pair) CSVLoader(org.tribuo.data.csv.CSVLoader) ImmutableDataset(org.tribuo.ImmutableDataset) Dataset(org.tribuo.Dataset) MinimumCardinalityDataset(org.tribuo.dataset.MinimumCardinalityDataset) MutableDataset(org.tribuo.MutableDataset) FileInputStream(java.io.FileInputStream) BreakIteratorTokenizer(org.tribuo.util.tokens.impl.BreakIteratorTokenizer) TokenPipeline(org.tribuo.data.text.impl.TokenPipeline) ObjectInputStream(java.io.ObjectInputStream)

Example 3 with ImmutableDataset

use of org.tribuo.ImmutableDataset in project tribuo by oracle.

the class TestLibLinearModel method loadDataset.

private Dataset<Label> loadDataset(LibLinearClassificationModel model, Path path) throws IOException {
    TextFeatureExtractor<Label> extractor = new TextFeatureExtractorImpl<>(new BasicPipeline(new BreakIteratorTokenizer(Locale.US), 2));
    TextDataSource<Label> src = new SimpleTextDataSource<>(path, new LabelFactory(), extractor);
    return new ImmutableDataset<>(src, model.getFeatureIDMap(), model.getOutputIDInfo(), false);
}
Also used : LabelFactory(org.tribuo.classification.LabelFactory) TextFeatureExtractorImpl(org.tribuo.data.text.impl.TextFeatureExtractorImpl) BasicPipeline(org.tribuo.data.text.impl.BasicPipeline) Label(org.tribuo.classification.Label) ImmutableDataset(org.tribuo.ImmutableDataset) BreakIteratorTokenizer(org.tribuo.util.tokens.impl.BreakIteratorTokenizer) SimpleTextDataSource(org.tribuo.data.text.impl.SimpleTextDataSource)

Example 4 with ImmutableDataset

use of org.tribuo.ImmutableDataset in project tribuo by oracle.

the class MNISTDemo method main.

public static void main(String[] args) throws IOException {
    // 
    // Use the labs format logging.
    LabsLogFormatter.setAllLogFormatters();
    LabelFactory labelFactory = new LabelFactory();
    logger.info("Loading training data.");
    // 
    // Load the libsvm text-based data format.
    LibSVMDataSource<Label> trainSource = new LibSVMDataSource<>(new File(args[0]).toPath(), labelFactory);
    MutableDataset<Label> train = new MutableDataset<>(trainSource);
    boolean zeroIndexed = trainSource.isZeroIndexed();
    int maxFeatureID = trainSource.getMaxFeatureID();
    logger.info(String.format("Loaded %d training examples for %s", train.size(), train.getOutputs().toString()));
    logger.info("Found " + train.getFeatureIDMap().size() + " features, and " + train.getOutputInfo().size() + " response dimensions");
    LibSVMDataSource<Label> testSource = new LibSVMDataSource<>(new File(args[1]).toPath(), labelFactory, zeroIndexed, maxFeatureID);
    ImmutableDataset<Label> test = new ImmutableDataset<>(testSource, train.getFeatureIDMap(), train.getOutputIDInfo(), false);
    logger.info(String.format("Loaded %d testing examples", test.size()));
    // public XGBoostClassificationTrainer(int numTrees, double eta, double gamma, int maxDepth, double minChildWeight, double subsample, double featureSubsample, double lambda, double alpha, long seed) {
    XGBoostClassificationTrainer trainer = new XGBoostClassificationTrainer(50);
    Model<Label> model = trainer.train(train);
    logger.info("Finished training model");
    // SparseTrainer<Regressor> limeTrainer = new LARSLassoTrainer(numFeatures);
    SparseTrainer<Regressor> limeTrainer = new CARTJointRegressionTrainer((int) (Math.log(numFeatures) / Math.log(2)));
    LIMEBase lime = new LIMEBase(new SplittableRandom(1), model, limeTrainer, 200);
    LIMEExplanation e = lime.explain(test.getData().get(0));
    logger.info("Finished lime");
    logger.info("Explanation = " + e.toString());
    LabelEvaluator labelEvaluator = new LabelEvaluator();
    LabelEvaluation evaluation = labelEvaluator.evaluate(model, test);
    logger.info("Finished evaluating model");
    System.out.println(labelEvaluator.toString());
    System.out.println();
    ConfusionMatrix<Label> matrix = evaluation.getConfusionMatrix();
    System.out.println(matrix.toString());
}
Also used : Label(org.tribuo.classification.Label) LabelEvaluator(org.tribuo.classification.evaluation.LabelEvaluator) CARTJointRegressionTrainer(org.tribuo.regression.rtree.CARTJointRegressionTrainer) LabelFactory(org.tribuo.classification.LabelFactory) LabelEvaluation(org.tribuo.classification.evaluation.LabelEvaluation) XGBoostClassificationTrainer(org.tribuo.classification.xgboost.XGBoostClassificationTrainer) LibSVMDataSource(org.tribuo.datasource.LibSVMDataSource) ImmutableDataset(org.tribuo.ImmutableDataset) Regressor(org.tribuo.regression.Regressor) File(java.io.File) MutableDataset(org.tribuo.MutableDataset) SplittableRandom(java.util.SplittableRandom)

Example 5 with ImmutableDataset

use of org.tribuo.ImmutableDataset in project tribuo by oracle.

the class TestLibSVM method testOnnxSerialization.

@Test
public void testOnnxSerialization() throws IOException, OrtException {
    Pair<Dataset<Label>, Dataset<Label>> binary = LabelledDataGenerator.binarySparseTrainTest();
    Map<Label, Integer> mapping = new HashMap<>();
    mapping.put(new Label("Foo"), 0);
    mapping.put(new Label("Bar"), 1);
    ImmutableOutputInfo<Label> newInfo = new LabelFactory().constructInfoForExternalModel(mapping);
    ImmutableDataset<Label> newTrain = ImmutableDataset.copyDataset(binary.getA(), binary.getA().getFeatureIDMap(), newInfo);
    ImmutableDataset<Label> newTest = ImmutableDataset.copyDataset(binary.getB(), binary.getA().getFeatureIDMap(), newInfo);
    testOnnxSerialization(new Pair<>(newTrain, newTest), C_LINEAR);
    testOnnxSerialization(binary, C_LINEAR);
    testOnnxSerialization(binary, C_RBF);
    testOnnxSerialization(binary, NU_LINEAR);
    testOnnxSerialization(binary, NU_RBF);
    SVMParameters<Label> params = new SVMParameters<>(new SVMClassificationType(SVMMode.NU_SVC), KernelType.RBF);
    params.setProbability();
    LibSVMClassificationTrainer probTrainer = new LibSVMClassificationTrainer(params);
    testOnnxSerialization(binary, probTrainer);
}
Also used : HashMap(java.util.HashMap) ImmutableDataset(org.tribuo.ImmutableDataset) Dataset(org.tribuo.Dataset) Label(org.tribuo.classification.Label) SVMParameters(org.tribuo.common.libsvm.SVMParameters) LabelFactory(org.tribuo.classification.LabelFactory) Test(org.junit.jupiter.api.Test)

Aggregations

ImmutableDataset (org.tribuo.ImmutableDataset)7 Label (org.tribuo.classification.Label)6 LabelFactory (org.tribuo.classification.LabelFactory)6 SimpleTextDataSource (org.tribuo.data.text.impl.SimpleTextDataSource)5 BreakIteratorTokenizer (org.tribuo.util.tokens.impl.BreakIteratorTokenizer)5 Dataset (org.tribuo.Dataset)3 BasicPipeline (org.tribuo.data.text.impl.BasicPipeline)3 TextFeatureExtractorImpl (org.tribuo.data.text.impl.TextFeatureExtractorImpl)3 LibSVMDataSource (org.tribuo.datasource.LibSVMDataSource)3 Pair (com.oracle.labs.mlrg.olcut.util.Pair)2 BufferedInputStream (java.io.BufferedInputStream)2 FileInputStream (java.io.FileInputStream)2 ObjectInputStream (java.io.ObjectInputStream)2 MutableDataset (org.tribuo.MutableDataset)2 CSVLoader (org.tribuo.data.csv.CSVLoader)2 TokenPipeline (org.tribuo.data.text.impl.TokenPipeline)2 File (java.io.File)1 Path (java.nio.file.Path)1 HashMap (java.util.HashMap)1 SplittableRandom (java.util.SplittableRandom)1