Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

IGNITE-11003: Added support of Random Forest #5924

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.apache.ignite.examples.ml.inference.spark.modelparser;

import java.io.FileNotFoundException;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.Ignition;
import org.apache.ignite.examples.ml.tutorial.TitanicUtils;
import org.apache.ignite.ml.composition.ModelsComposition;
import org.apache.ignite.ml.math.functions.IgniteBiFunction;
import org.apache.ignite.ml.math.primitives.vector.Vector;
import org.apache.ignite.ml.math.primitives.vector.VectorUtils;
import org.apache.ignite.ml.selection.scoring.evaluator.BinaryClassificationEvaluator;
import org.apache.ignite.ml.selection.scoring.metric.Accuracy;
import org.apache.ignite.ml.sparkmodelparser.SparkModelParser;
import org.apache.ignite.ml.sparkmodelparser.SupportedSparkModels;

/**
* Run Random Forest model loaded from snappy.parquet file.
* The snappy.parquet file was generated by Spark MLLib model.write.overwrite().save(..) operator.
* <p>
* You can change the test data used in this example and re-run it to explore this algorithm further.</p>
*/
public class RandomForestFromSparkExample {
/** Path to Spark Random Forest model. */
public static final String SPARK_MDL_PATH = "examples/src/main/resources/models/spark/serialized/rf/data" +
"/part-00000-290bdb9d-bc1b-411c-8811-c3205434f5fc-c000.snappy.parquet";

/** Run example. */
public static void main(String[] args) throws FileNotFoundException {
System.out.println();
System.out.println(">>> Random Forest model loaded from Spark through serialization over partitioned dataset usage example started.");
// Start ignite grid.
try (Ignite ignite = Ignition.start("examples/config/example-ignite.xml")) {
System.out.println(">>> Ignite grid started.");

IgniteCache<Integer, Object[]> dataCache = TitanicUtils.readPassengers(ignite);

IgniteBiFunction<Integer, Object[], Vector> featureExtractor = (k, v) -> {
double[] data = new double[] {(double)v[0], (double)v[5], (double)v[6]};
data[0] = Double.isNaN(data[0]) ? 0 : data[0];
data[1] = Double.isNaN(data[1]) ? 0 : data[1];
data[2] = Double.isNaN(data[2]) ? 0 : data[2];

return VectorUtils.of(data);
};

IgniteBiFunction<Integer, Object[], Double> lbExtractor = (k, v) -> (double)v[1];

ModelsComposition mdl = (ModelsComposition)SparkModelParser.parse(
SPARK_MDL_PATH,
SupportedSparkModels.RANDOM_FOREST
);

System.out.println(">>> Random Forest model: " + mdl.toString(true));

double accuracy = BinaryClassificationEvaluator.evaluate(
dataCache,
mdl,
featureExtractor,
lbExtractor,
new Accuracy<>()
);

System.out.println("\n>>> Accuracy " + accuracy);
System.out.println("\n>>> Test Error " + (1 - accuracy));
}
}
}
Binary file not shown.
Binary file not shown.
Empty file.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"class":"org.apache.spark.ml.classification.RandomForestClassificationModel","timestamp":1548169635203,"sparkVersion":"2.2.0","uid":"rfc_4627f663b8c3","paramMap":{"featureSubsetStrategy":"auto","maxMemoryInMB":256,"impurity":"gini","numTrees":200,"probabilityCol":"probability","maxDepth":10,"labelCol":"survived","maxBins":32,"subsamplingRate":1.0,"rawPredictionCol":"rawPrediction","checkpointInterval":10,"featuresCol":"features","minInstancesPerNode":1,"predictionCol":"prediction","seed":207336481,"cacheNodeIds":false,"minInfoGain":0.0},"numFeatures":3,"numClasses":2,"numTrees":200}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,17 @@

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.TreeMap;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.ignite.internal.util.IgniteUtils;
import org.apache.ignite.ml.IgniteModel;
import org.apache.ignite.ml.composition.ModelsComposition;
import org.apache.ignite.ml.composition.predictionsaggregator.OnMajorityPredictionsAggregator;
import org.apache.ignite.ml.inference.Model;
import org.apache.ignite.ml.math.primitives.vector.Vector;
import org.apache.ignite.ml.math.primitives.vector.impl.DenseVector;
Expand Down Expand Up @@ -72,11 +77,52 @@ public static Model parse(String pathToMdl, SupportedSparkModels parsedSparkMdl)
return loadLinearSVMModel(ignitePathToMdl);
case DECISION_TREE:
return loadDecisionTreeModel(ignitePathToMdl);
case RANDOM_FOREST:
return loadRandomForestModel(ignitePathToMdl);
default:
throw new UnsupportedSparkModelException(ignitePathToMdl);
}
}

private static Model loadRandomForestModel(String pathToMdl) {
try (ParquetFileReader r = ParquetFileReader.open(HadoopInputFile.fromPath(new Path(pathToMdl), new Configuration()))) {
PageReadStore pages;
final MessageType schema = r.getFooter().getFileMetaData().getSchema();
final MessageColumnIO colIO = new ColumnIOFactory().getColumnIO(schema);
final Map<Integer, TreeMap<Integer, NodeData>> nodesByTreeId = new TreeMap<>();
while (null != (pages = r.readNextRowGroup())) {
final long rows = pages.getRowCount();
final RecordReader recordReader = colIO.getRecordReader(pages, new GroupRecordConverter(schema));
for (int i = 0; i < rows; i++) {
final SimpleGroup g = (SimpleGroup)recordReader.read();
final int treeID = g.getInteger(0, 0);
final SimpleGroup nodeDataGroup = (SimpleGroup)g.getGroup(1, 0);
NodeData nodeData = extractNodeDataFromParquetRow(nodeDataGroup);

if (nodesByTreeId.containsKey(treeID)) {
Map<Integer, NodeData> nodesByNodeId = nodesByTreeId.get(treeID);
nodesByNodeId.put(nodeData.id, nodeData);
}
else {
TreeMap<Integer, NodeData> nodesByNodeId = new TreeMap<>();
nodesByNodeId.put(nodeData.id, nodeData);
nodesByTreeId.put(treeID, nodesByNodeId);
}
}
}

final List<IgniteModel<Vector, Double>> models = new ArrayList<>();
nodesByTreeId.forEach((key, nodes) -> models.add(buildDecisionTreeModel(nodes)));

return new ModelsComposition(models, new OnMajorityPredictionsAggregator());
}
catch (IOException e) {
System.out.println("Error reading parquet file.");
e.printStackTrace();
}
return null;
}

/**
* Load Decision Tree model.
*
Expand Down Expand Up @@ -111,7 +157,7 @@ private static Model loadDecisionTreeModel(String pathToMdl) {
*
* @param nodes The sorted map of nodes.
*/
private static Model buildDecisionTreeModel(Map<Integer, NodeData> nodes) {
private static DecisionTreeNode buildDecisionTreeModel(Map<Integer, NodeData> nodes) {
DecisionTreeNode mdl = null;
if (!nodes.isEmpty()) {
NodeData rootNodeData = (NodeData)((NavigableMap)nodes).firstEntry().getValue();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,8 @@ public enum SupportedSparkModels {
DECISION_TREE,

/** Support Vector Machine . */
LINEAR_SVM
LINEAR_SVM,

/** Random forest. */
RANDOM_FOREST
}