Example usage for weka.classifiers.functions PLSClassifier buildClassifier

List of usage examples for weka.classifiers.functions PLSClassifier buildClassifier

Introduction

In this page you can find the example usage for weka.classifiers.functions PLSClassifier buildClassifier.

Prototype

@Override
public void buildClassifier(Instances data) throws Exception 

Source Link

Document

builds the classifier

Usage

From source file:org.jaqpot.algorithm.resource.WekaPLS.java

License:Open Source License

@POST
@Path("training")
public Response training(TrainingRequest request) {
    try {//from   w  w w .ja  va  2s  .  com
        if (request.getDataset().getDataEntry().isEmpty()
                || request.getDataset().getDataEntry().get(0).getValues().isEmpty()) {
            return Response.status(Response.Status.BAD_REQUEST).entity(
                    ErrorReportFactory.badRequest("Dataset is empty", "Cannot train model on empty dataset"))
                    .build();
        }
        List<String> features = request.getDataset().getDataEntry().stream().findFirst().get().getValues()
                .keySet().stream().collect(Collectors.toList());

        Instances data = InstanceUtils.createFromDataset(request.getDataset(), request.getPredictionFeature());
        Map<String, Object> parameters = request.getParameters() != null ? request.getParameters()
                : new HashMap<>();

        Integer components = Integer.parseInt(parameters.getOrDefault("components", _components).toString());
        String algorithm = parameters.getOrDefault("algorithm", _algorithm).toString();

        PLSClassifier classifier = new PLSClassifier();
        classifier.setOptions(new String[] { "-C", components.toString(), "-A", algorithm });
        classifier.buildClassifier(data);

        WekaModel model = new WekaModel();
        model.setClassifier(classifier);

        TrainingResponse response = new TrainingResponse();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutput out = new ObjectOutputStream(baos);
        out.writeObject(model);
        String base64Model = Base64.getEncoder().encodeToString(baos.toByteArray());
        response.setRawModel(base64Model);
        List<String> independentFeatures = features.stream()
                .filter(feature -> !feature.equals(request.getPredictionFeature()))
                .collect(Collectors.toList());
        response.setIndependentFeatures(independentFeatures);
        //            response.setPmmlModel(pmml);
        response.setAdditionalInfo(request.getPredictionFeature());
        response.setPredictedFeatures(
                Arrays.asList("Weka PLS prediction of " + request.getPredictionFeature()));

        return Response.ok(response).build();
    } catch (Exception ex) {
        LOG.log(Level.SEVERE, null, ex);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build();
    }
}

From source file:org.jaqpot.algorithms.resource.WekaPLS.java

License:Open Source License

@POST
@Path("training")
public Response training(TrainingRequest request) {
    try {// w  ww. ja v a2s  .  c  o  m
        if (request.getDataset().getDataEntry().isEmpty()
                || request.getDataset().getDataEntry().get(0).getValues().isEmpty()) {
            return Response.status(Response.Status.BAD_REQUEST)
                    .entity("Dataset is empty. Cannot train model on empty dataset.").build();
        }
        List<String> features = request.getDataset().getDataEntry().stream().findFirst().get().getValues()
                .keySet().stream().collect(Collectors.toList());

        Instances data = InstanceUtils.createFromDataset(request.getDataset(), request.getPredictionFeature());
        Map<String, Object> parameters = request.getParameters() != null ? request.getParameters()
                : new HashMap<>();

        Integer components = Integer.parseInt(parameters.getOrDefault("components", _components).toString());
        String algorithm = parameters.getOrDefault("algorithm", _algorithm).toString();

        PLSClassifier classifier = new PLSClassifier();
        classifier.setOptions(new String[] { "-C", components.toString(), "-A", algorithm });
        classifier.buildClassifier(data);

        WekaModel model = new WekaModel();
        model.setClassifier(classifier);

        TrainingResponse response = new TrainingResponse();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutput out = new ObjectOutputStream(baos);
        out.writeObject(model);
        String base64Model = Base64.getEncoder().encodeToString(baos.toByteArray());
        response.setRawModel(base64Model);
        List<String> independentFeatures = features.stream()
                .filter(feature -> !feature.equals(request.getPredictionFeature()))
                .collect(Collectors.toList());
        response.setIndependentFeatures(independentFeatures);
        //            response.setPmmlModel(pmml);
        response.setAdditionalInfo(request.getPredictionFeature());
        response.setPredictedFeatures(
                Arrays.asList("Weka PLS prediction of " + request.getPredictionFeature()));

        return Response.ok(response).build();
    } catch (Exception ex) {
        LOG.log(Level.SEVERE, null, ex);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build();
    }
}

From source file:org.opentox.jaqpot3.qsar.trainer.PLSTrainer.java

License:Open Source License

@Override
public Model train(Instances data) throws JaqpotException {
    Model model = new Model(Configuration.getBaseUri().augment("model", getUuid().toString()));

    data.setClass(data.attribute(targetUri.toString()));

    Boolean targetURIIncluded = false;
    for (Feature tempFeature : independentFeatures) {
        if (StringUtils.equals(tempFeature.getUri().toString(), targetUri.toString())) {
            targetURIIncluded = true;// w ww . ja v  a2s . c o m
            break;
        }
    }
    if (!targetURIIncluded) {
        independentFeatures.add(new Feature(targetUri));
    }
    model.setIndependentFeatures(independentFeatures);

    /*
     * Train the PLS filter
     */
    PLSFilter pls = new PLSFilter();
    try {
        pls.setInputFormat(data);
        pls.setOptions(new String[] { "-C", Integer.toString(numComponents), "-A", pls_algorithm, "-P",
                preprocessing, "-U", doUpdateClass });
        PLSFilter.useFilter(data, pls);
    } catch (Exception ex) {
        Logger.getLogger(PLSTrainer.class.getName()).log(Level.SEVERE, null, ex);
    }

    PLSModel actualModel = new PLSModel(pls);
    try {

        PLSClassifier cls = new PLSClassifier();
        cls.setFilter(pls);
        cls.buildClassifier(data);

        // evaluate classifier and print some statistics
        Evaluation eval = new Evaluation(data);
        eval.evaluateModel(cls, data);
        String stats = eval.toSummaryString("", false);

        ActualModel am = new ActualModel(actualModel);
        am.setStatistics(stats);

        model.setActualModel(am);
    } catch (NotSerializableException ex) {
        Logger.getLogger(PLSTrainer.class.getName()).log(Level.SEVERE, null, ex);
        throw new JaqpotException(ex);
    } catch (Exception ex) {
        Logger.getLogger(PLSTrainer.class.getName()).log(Level.SEVERE, null, ex);
        throw new JaqpotException(ex);
    }

    model.setDataset(datasetUri);
    model.setAlgorithm(Algorithms.plsFilter());
    model.getMeta().addTitle("PLS Model for " + datasetUri);

    Set<Parameter> parameters = new HashSet<Parameter>();
    Parameter targetPrm = new Parameter(Configuration.getBaseUri().augment("parameter", RANDOM.nextLong()),
            "target", new LiteralValue(targetUri.toString(), XSDDatatype.XSDstring))
                    .setScope(Parameter.ParameterScope.MANDATORY);
    Parameter nComponentsPrm = new Parameter(Configuration.getBaseUri().augment("parameter", RANDOM.nextLong()),
            "numComponents", new LiteralValue(numComponents, XSDDatatype.XSDpositiveInteger))
                    .setScope(Parameter.ParameterScope.MANDATORY);
    Parameter preprocessingPrm = new Parameter(
            Configuration.getBaseUri().augment("parameter", RANDOM.nextLong()), "preprocessing",
            new LiteralValue(preprocessing, XSDDatatype.XSDstring)).setScope(Parameter.ParameterScope.OPTIONAL);
    Parameter algorithmPrm = new Parameter(Configuration.getBaseUri().augment("parameter", RANDOM.nextLong()),
            "algorithm", new LiteralValue(pls_algorithm, XSDDatatype.XSDstring))
                    .setScope(Parameter.ParameterScope.OPTIONAL);
    Parameter doUpdatePrm = new Parameter(Configuration.getBaseUri().augment("parameter", RANDOM.nextLong()),
            "doUpdateClass", new LiteralValue(doUpdateClass, XSDDatatype.XSDboolean))
                    .setScope(Parameter.ParameterScope.OPTIONAL);

    parameters.add(targetPrm);
    parameters.add(nComponentsPrm);
    parameters.add(preprocessingPrm);
    parameters.add(doUpdatePrm);
    parameters.add(algorithmPrm);
    model.setParameters(parameters);

    for (int i = 0; i < numComponents; i++) {
        Feature f = publishFeature(model, "", "PLS-" + i, datasetUri, featureService);
        model.addPredictedFeatures(f);
    }

    //save the instances being predicted to abstract trainer for calculating DoA
    predictedInstances = data;
    //in pls target is not excluded

    return model;
}