Search in sources :

Example 1 with Progress

use of edu.neu.ccs.pyramid.util.Progress in project pyramid by cheng-li.

the class App2 method report.

static void report(Config config, String dataName, Logger logger) throws Exception {
    logger.info("generating reports for data set " + dataName);
    String output = config.getString("output.folder");
    String modelName = "model_app3";
    File analysisFolder = new File(new File(output, "reports_app3"), dataName + "_reports");
    analysisFolder.mkdirs();
    FileUtils.cleanDirectory(analysisFolder);
    IMLGradientBoosting boosting = IMLGradientBoosting.deserialize(new File(output, modelName));
    String predictTarget = config.getString("predict.target");
    PluginPredictor<IMLGradientBoosting> pluginPredictorTmp = null;
    switch(predictTarget) {
        case "subsetAccuracy":
            pluginPredictorTmp = new SubsetAccPredictor(boosting);
            break;
        case "hammingLoss":
            pluginPredictorTmp = new HammingPredictor(boosting);
            break;
        case "instanceFMeasure":
            pluginPredictorTmp = new InstanceF1Predictor(boosting);
            break;
        case "macroFMeasure":
            TunedMarginalClassifier tunedMarginalClassifier = (TunedMarginalClassifier) Serialization.deserialize(new File(output, "predictor_macro_f"));
            pluginPredictorTmp = new MacroF1Predictor(boosting, tunedMarginalClassifier);
            break;
        default:
            throw new IllegalArgumentException("unknown prediction target measure " + predictTarget);
    }
    // just to make Lambda expressions happy
    final PluginPredictor<IMLGradientBoosting> pluginPredictor = pluginPredictorTmp;
    MultiLabelClfDataSet dataSet = loadData(config, dataName);
    MLMeasures mlMeasures = new MLMeasures(pluginPredictor, dataSet);
    mlMeasures.getMacroAverage().setLabelTranslator(boosting.getLabelTranslator());
    logger.info("performance on dataset " + dataName);
    logger.info(mlMeasures.toString());
    boolean simpleCSV = true;
    if (simpleCSV) {
        logger.info("start generating simple CSV report");
        double probThreshold = config.getDouble("report.classProbThreshold");
        File csv = new File(analysisFolder, "report.csv");
        List<String> strs = IntStream.range(0, dataSet.getNumDataPoints()).parallel().mapToObj(i -> IMLGBInspector.simplePredictionAnalysis(boosting, pluginPredictor, dataSet, i, probThreshold)).collect(Collectors.toList());
        try (BufferedWriter bw = new BufferedWriter(new FileWriter(csv))) {
            for (int i = 0; i < dataSet.getNumDataPoints(); i++) {
                String str = strs.get(i);
                bw.write(str);
            }
        }
        logger.info("finish generating simple CSV report");
    }
    boolean rulesToJson = config.getBoolean("report.showPredictionDetail");
    if (rulesToJson) {
        logger.info("start writing rules to json");
        int ruleLimit = config.getInt("report.rule.limit");
        int numDocsPerFile = config.getInt("report.numDocsPerFile");
        int numFiles = (int) Math.ceil((double) dataSet.getNumDataPoints() / numDocsPerFile);
        double probThreshold = config.getDouble("report.classProbThreshold");
        int labelSetLimit = config.getInt("report.labelSetLimit");
        IntStream.range(0, numFiles).forEach(i -> {
            int start = i * numDocsPerFile;
            int end = start + numDocsPerFile;
            List<MultiLabelPredictionAnalysis> partition = IntStream.range(start, Math.min(end, dataSet.getNumDataPoints())).parallel().mapToObj(a -> IMLGBInspector.analyzePrediction(boosting, pluginPredictor, dataSet, a, ruleLimit, labelSetLimit, probThreshold)).collect(Collectors.toList());
            ObjectMapper mapper = new ObjectMapper();
            String file = "report_" + (i + 1) + ".json";
            try {
                mapper.writeValue(new File(analysisFolder, file), partition);
            } catch (IOException e) {
                e.printStackTrace();
            }
            logger.info("progress = " + Progress.percentage(i + 1, numFiles));
        });
        logger.info("finish writing rules to json");
    }
    boolean dataInfoToJson = true;
    if (dataInfoToJson) {
        logger.info("start writing data info to json");
        Set<String> modelLabels = IntStream.range(0, boosting.getNumClasses()).mapToObj(i -> boosting.getLabelTranslator().toExtLabel(i)).collect(Collectors.toSet());
        Set<String> dataSetLabels = DataSetUtil.gatherLabels(dataSet).stream().map(i -> dataSet.getLabelTranslator().toExtLabel(i)).collect(Collectors.toSet());
        JsonGenerator jsonGenerator = new JsonFactory().createGenerator(new File(analysisFolder, "data_info.json"), JsonEncoding.UTF8);
        jsonGenerator.writeStartObject();
        jsonGenerator.writeStringField("dataSet", dataName);
        jsonGenerator.writeNumberField("numClassesInModel", boosting.getNumClasses());
        jsonGenerator.writeNumberField("numClassesInDataSet", dataSetLabels.size());
        jsonGenerator.writeNumberField("numClassesInModelDataSetCombined", dataSet.getNumClasses());
        Set<String> modelNotDataLabels = SetUtil.complement(modelLabels, dataSetLabels);
        Set<String> dataNotModelLabels = SetUtil.complement(dataSetLabels, modelLabels);
        jsonGenerator.writeNumberField("numClassesInDataSetButNotModel", dataNotModelLabels.size());
        jsonGenerator.writeNumberField("numClassesInModelButNotDataSet", modelNotDataLabels.size());
        jsonGenerator.writeArrayFieldStart("classesInDataSetButNotModel");
        for (String label : dataNotModelLabels) {
            jsonGenerator.writeObject(label);
        }
        jsonGenerator.writeEndArray();
        jsonGenerator.writeArrayFieldStart("classesInModelButNotDataSet");
        for (String label : modelNotDataLabels) {
            jsonGenerator.writeObject(label);
        }
        jsonGenerator.writeEndArray();
        jsonGenerator.writeNumberField("labelCardinality", dataSet.labelCardinality());
        jsonGenerator.writeEndObject();
        jsonGenerator.close();
        logger.info("finish writing data info to json");
    }
    boolean modelConfigToJson = true;
    if (modelConfigToJson) {
        logger.info("start writing model config to json");
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.writeValue(new File(analysisFolder, "model_config.json"), config);
        logger.info("finish writing model config to json");
    }
    boolean dataConfigToJson = true;
    if (dataConfigToJson) {
        logger.info("start writing data config to json");
        File dataConfigFile = Paths.get(config.getString("input.folder"), "data_sets", dataName, "data_config.json").toFile();
        if (dataConfigFile.exists()) {
            FileUtils.copyFileToDirectory(dataConfigFile, analysisFolder);
        }
        logger.info("finish writing data config to json");
    }
    boolean performanceToJson = true;
    if (performanceToJson) {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.writeValue(new File(analysisFolder, "performance.json"), mlMeasures);
    }
    boolean individualPerformance = true;
    if (individualPerformance) {
        logger.info("start writing individual label performance to json");
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.writeValue(new File(analysisFolder, "individual_performance.json"), mlMeasures.getMacroAverage());
        logger.info("finish writing individual label performance to json");
    }
    logger.info("reports generated");
}
Also used : IntStream(java.util.stream.IntStream) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) SimpleFormatter(java.util.logging.SimpleFormatter) PluginPredictor(edu.neu.ccs.pyramid.multilabel_classification.PluginPredictor) edu.neu.ccs.pyramid.multilabel_classification.imlgb(edu.neu.ccs.pyramid.multilabel_classification.imlgb) ArrayList(java.util.ArrayList) Terminator(edu.neu.ccs.pyramid.optimization.Terminator) FileHandler(java.util.logging.FileHandler) FeatureDistribution(edu.neu.ccs.pyramid.feature_selection.FeatureDistribution) JsonEncoding(com.fasterxml.jackson.core.JsonEncoding) Config(edu.neu.ccs.pyramid.configuration.Config) MultiLabelPredictionAnalysis(edu.neu.ccs.pyramid.multilabel_classification.MultiLabelPredictionAnalysis) EarlyStopper(edu.neu.ccs.pyramid.optimization.EarlyStopper) BufferedWriter(java.io.BufferedWriter) edu.neu.ccs.pyramid.eval(edu.neu.ccs.pyramid.eval) Collection(java.util.Collection) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) TunedMarginalClassifier(edu.neu.ccs.pyramid.multilabel_classification.thresholding.TunedMarginalClassifier) FileWriter(java.io.FileWriter) Set(java.util.Set) FileUtils(org.apache.commons.io.FileUtils) IOException(java.io.IOException) StopWatch(org.apache.commons.lang3.time.StopWatch) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) File(java.io.File) Progress(edu.neu.ccs.pyramid.util.Progress) List(java.util.List) JsonFactory(com.fasterxml.jackson.core.JsonFactory) Feature(edu.neu.ccs.pyramid.feature.Feature) MacroFMeasureTuner(edu.neu.ccs.pyramid.multilabel_classification.thresholding.MacroFMeasureTuner) Serialization(edu.neu.ccs.pyramid.util.Serialization) Paths(java.nio.file.Paths) edu.neu.ccs.pyramid.dataset(edu.neu.ccs.pyramid.dataset) Vector(org.apache.mahout.math.Vector) TopFeatures(edu.neu.ccs.pyramid.feature.TopFeatures) SetUtil(edu.neu.ccs.pyramid.util.SetUtil) MultiLabelPredictionAnalysis(edu.neu.ccs.pyramid.multilabel_classification.MultiLabelPredictionAnalysis) FileWriter(java.io.FileWriter) JsonFactory(com.fasterxml.jackson.core.JsonFactory) BufferedWriter(java.io.BufferedWriter) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) TunedMarginalClassifier(edu.neu.ccs.pyramid.multilabel_classification.thresholding.TunedMarginalClassifier) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IOException(java.io.IOException) File(java.io.File)

Aggregations

JsonEncoding (com.fasterxml.jackson.core.JsonEncoding)1 JsonFactory (com.fasterxml.jackson.core.JsonFactory)1 JsonGenerator (com.fasterxml.jackson.core.JsonGenerator)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 Config (edu.neu.ccs.pyramid.configuration.Config)1 edu.neu.ccs.pyramid.dataset (edu.neu.ccs.pyramid.dataset)1 edu.neu.ccs.pyramid.eval (edu.neu.ccs.pyramid.eval)1 Feature (edu.neu.ccs.pyramid.feature.Feature)1 TopFeatures (edu.neu.ccs.pyramid.feature.TopFeatures)1 FeatureDistribution (edu.neu.ccs.pyramid.feature_selection.FeatureDistribution)1 MultiLabelPredictionAnalysis (edu.neu.ccs.pyramid.multilabel_classification.MultiLabelPredictionAnalysis)1 PluginPredictor (edu.neu.ccs.pyramid.multilabel_classification.PluginPredictor)1 edu.neu.ccs.pyramid.multilabel_classification.imlgb (edu.neu.ccs.pyramid.multilabel_classification.imlgb)1 MacroFMeasureTuner (edu.neu.ccs.pyramid.multilabel_classification.thresholding.MacroFMeasureTuner)1 TunedMarginalClassifier (edu.neu.ccs.pyramid.multilabel_classification.thresholding.TunedMarginalClassifier)1 EarlyStopper (edu.neu.ccs.pyramid.optimization.EarlyStopper)1 Terminator (edu.neu.ccs.pyramid.optimization.Terminator)1 Progress (edu.neu.ccs.pyramid.util.Progress)1 Serialization (edu.neu.ccs.pyramid.util.Serialization)1 SetUtil (edu.neu.ccs.pyramid.util.SetUtil)1