org.dmg.pmml.True Java Examples

The following examples show how to use org.dmg.pmml.True. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RPartConverter.java    From jpmml-r with GNU Affero General Public License v3.0 6 votes vote down vote up
private TreeModel encodeRegression(RGenericVector frame, RIntegerVector rowNames, RIntegerVector var, RIntegerVector n, int[][] splitInfo, RNumberVector<?> splits, RIntegerVector csplit, Schema schema){
	RNumberVector<?> yval = frame.getNumericElement("yval");

	ScoreEncoder scoreEncoder = new ScoreEncoder(){

		@Override
		public Node encode(Node node, int offset){
			Number score = yval.getValue(offset);
			Number recordCount = n.getValue(offset);

			node
				.setScore(score)
				.setRecordCount(recordCount);

			return node;
		}
	};

	Node root = encodeNode(True.INSTANCE, 1, rowNames, var, n, splitInfo, splits, csplit, scoreEncoder, schema);

	TreeModel treeModel = new TreeModel(MiningFunction.REGRESSION, ModelUtil.createMiningSchema(schema.getLabel()), root);

	return configureTreeModel(treeModel);
}
 
Example #2
Source File: ScoreDistributionInternerTest.java    From jpmml-evaluator with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void intern(){
	ScoreDistribution left = new ScoreDistribution("event", 0.33d);
	ScoreDistribution right = new ScoreDistribution("event", 0.33d);

	Node leftChild = createNode(left);
	Node rightChild = createNode(right);

	Node root = new ComplexNode(True.INSTANCE)
		.addNodes(leftChild, rightChild);

	TreeModel treeModel = new TreeModel()
		.setNode(root);

	for(int i = 0; i < 2; i++){
		assertNotSame((leftChild.getScoreDistributions()).get(i), (rightChild.getScoreDistributions()).get(i));
	}

	ScoreDistributionInterner interner = new ScoreDistributionInterner();
	interner.applyTo(treeModel);

	for(int i = 0; i < 2; i++){
		assertSame((leftChild.getScoreDistributions()).get(i), (rightChild.getScoreDistributions()).get(i));
	}
}
 
Example #3
Source File: PredicateInterner.java    From jpmml-evaluator with GNU Affero General Public License v3.0 6 votes vote down vote up
public Predicate intern(Predicate predicate){

		if(predicate instanceof SimplePredicate){
			return intern((SimplePredicate)predicate);
		} else

		if(predicate instanceof SimpleSetPredicate){
			return intern((SimpleSetPredicate)predicate);
		} else

		if(predicate instanceof True){
			return True.INSTANCE;
		} else

		if(predicate instanceof False){
			return False.INSTANCE;
		}

		return predicate;
	}
 
Example #4
Source File: RandomForestConverter.java    From jpmml-r with GNU Affero General Public License v3.0 6 votes vote down vote up
private <P extends Number> TreeModel encodeTreeModel(MiningFunction miningFunction, ScoreEncoder<P> scoreEncoder, List<? extends Number> leftDaughter, List<? extends Number> rightDaughter, List<P> nodepred, List<? extends Number> bestvar, List<Double> xbestsplit, Schema schema){
	RGenericVector randomForest = getObject();

	Node root = encodeNode(True.INSTANCE, 0, scoreEncoder, leftDaughter, rightDaughter, bestvar, xbestsplit, nodepred, new CategoryManager(), schema);

	TreeModel treeModel = new TreeModel(miningFunction, ModelUtil.createMiningSchema(schema.getLabel()), root)
		.setMissingValueStrategy(TreeModel.MissingValueStrategy.NULL_PREDICTION)
		.setSplitCharacteristic(TreeModel.SplitCharacteristic.BINARY_SPLIT);

	if(this.compact){
		Visitor visitor = new RandomForestCompactor();

		visitor.applyTo(treeModel);
	}

	return treeModel;
}
 
Example #5
Source File: TreeUtil.java    From jpmml-sklearn with GNU Affero General Public License v3.0 6 votes vote down vote up
static
public <E extends Estimator & HasTree> TreeModel encodeTreeModel(E estimator, PredicateManager predicateManager, ScoreDistributionManager scoreDistributionManager, MiningFunction miningFunction, Schema schema){
	Tree tree = estimator.getTree();

	int[] leftChildren = tree.getChildrenLeft();
	int[] rightChildren = tree.getChildrenRight();
	int[] features = tree.getFeature();
	double[] thresholds = tree.getThreshold();
	double[] values = tree.getValues();

	Node root = encodeNode(True.INSTANCE, predicateManager, scoreDistributionManager, 0, leftChildren, rightChildren, features, thresholds, values, miningFunction, schema);

	TreeModel treeModel = new TreeModel(miningFunction, ModelUtil.createMiningSchema(schema.getLabel()), root)
		.setSplitCharacteristic(TreeModel.SplitCharacteristic.BINARY_SPLIT);

	ClassDictUtil.clearContent(tree);

	return treeModel;
}
 
Example #6
Source File: TreePredictorUtil.java    From jpmml-sklearn with GNU Affero General Public License v3.0 6 votes vote down vote up
static
public TreeModel encodeTreeModel(TreePredictor treePredictor, PredicateManager predicateManager, Schema schema){
	int[] leaf = treePredictor.isLeaf();
	int[] leftChildren = treePredictor.getLeft();
	int[] rightChildren = treePredictor.getRight();
	int[] featureIdx = treePredictor.getFeatureIdx();
	double[] thresholds = treePredictor.getThreshold();
	int[] missingGoToLeft = treePredictor.getMissingGoToLeft();
	double[] values = treePredictor.getValues();

	Node root = encodeNode(True.INSTANCE, predicateManager, 0, leaf, leftChildren, rightChildren, featureIdx, thresholds, missingGoToLeft, values, schema);

	TreeModel treeModel = new TreeModel(MiningFunction.REGRESSION, ModelUtil.createMiningSchema(schema.getLabel()), root)
		.setSplitCharacteristic(TreeModel.SplitCharacteristic.BINARY_SPLIT)
		.setMissingValueStrategy(TreeModel.MissingValueStrategy.DEFAULT_CHILD);

	return treeModel;
}
 
Example #7
Source File: TreeModelCompactor.java    From jpmml-lightgbm with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void exitNode(Node node){
	Number recordCount = node.getRecordCount();
	Predicate predicate = node.getPredicate();

	if(recordCount != null){
		node.setRecordCount(null);
	} // End if

	if(predicate instanceof True){
		Node parentNode = getParentNode();

		if(parentNode == null){
			return;
		}

		initScore(parentNode, node);
		replaceChildWithGrandchildren(parentNode, node);
	}
}
 
Example #8
Source File: TreeModelCompactor.java    From jpmml-xgboost with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void exitNode(Node node){
	Predicate predicate = node.getPredicate();

	if(predicate instanceof True){
		Node parentNode = getParentNode();

		if(parentNode == null){
			return;
		}

		initScore(parentNode, node);
		replaceChildWithGrandchildren(parentNode, node);
	}
}
 
Example #9
Source File: PredicateInternerTest.java    From jpmml-evaluator with GNU Affero General Public License v3.0 5 votes vote down vote up
static
private void checkTree(Node leftChild, Node rightChild){
	Node root = new BranchNode(null, True.INSTANCE)
		.addNodes(leftChild, rightChild);

	TreeModel treeModel = new TreeModel()
		.setNode(root);

	assertNotSame(leftChild.getPredicate(), rightChild.getPredicate());

	PredicateInterner interner = new PredicateInterner();
	interner.applyTo(treeModel);

	assertSame(leftChild.getPredicate(), rightChild.getPredicate());
}
 
Example #10
Source File: NodeResolverTest.java    From jpmml-evaluator with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void resolve(){
	Node leftChild = new LeafNode()
		.setId("1");

	Node rightChild = new LeafNode()
		.setId("2");

	Node root = new BranchNode(null, True.INSTANCE)
		.setId("0")
		.setDefaultChild(rightChild.getId())
		.addNodes(leftChild, rightChild);

	TreeModel treeModel = new TreeModel(MiningFunction.REGRESSION, new MiningSchema(), null)
		.setNode(root);

	PMML pmml = new PMML(Version.PMML_4_3.getVersion(), new Header(), new DataDictionary())
		.addModels(treeModel);

	NodeResolver resolver = new NodeResolver();
	resolver.applyTo(pmml);

	assertEquals(rightChild.getId(), root.getDefaultChild());

	treeModel.setMissingValueStrategy(TreeModel.MissingValueStrategy.DEFAULT_CHILD);

	resolver.applyTo(pmml);

	assertSame(rightChild, root.getDefaultChild());
}
 
Example #11
Source File: MiningModelEvaluator.java    From jpmml-evaluator with GNU Affero General Public License v3.0 5 votes vote down vote up
private List<Segment> getActiveHead(List<Segment> segments){

		for(int i = 0, max = segments.size(); i < max; i++){
			Segment segment = segments.get(i);

			Predicate predicate = PredicateUtil.ensurePredicate(segment);

			if(predicate instanceof True){
				return segments.subList(0, i + 1);
			}
		}

		return segments;
	}
 
Example #12
Source File: PredicateUtil.java    From jpmml-evaluator with GNU Affero General Public License v3.0 5 votes vote down vote up
static
Boolean evaluatePredicate(Predicate predicate, EvaluationContext context){

	if(predicate instanceof SimplePredicate){
		return evaluateSimplePredicate((SimplePredicate)predicate, context);
	} else

	if(predicate instanceof SimpleSetPredicate){
		return evaluateSimpleSetPredicate((SimpleSetPredicate)predicate, context);
	} else

	if(predicate instanceof CompoundPredicate){
		return evaluateCompoundPredicate((CompoundPredicate)predicate, context);
	} else

	if(predicate instanceof True){
		return evaluateTrue((True)predicate);
	} else

	if(predicate instanceof False){
		return evaluateFalse((False)predicate);
	} // End if

	if(predicate instanceof JavaPredicate){
		return evaluateJavaPredicate((JavaPredicate)predicate, context);
	}

	throw new UnsupportedElementException(predicate);
}
 
Example #13
Source File: RDFUpdateIT.java    From oryx with Apache License 2.0 5 votes vote down vote up
private static void checkNode(Node node) {
  assertNotNull(node.getId());
  if (!node.hasScoreDistributions()) {
    // Non-leaf
    List<Node> children = node.getNodes();
    assertEquals(2, children.size());
    Node rightChild = children.get(0);
    Node leftChild = children.get(1);
    assertInstanceOf(leftChild.getPredicate(), True.class);
    assertEquals(node.getRecordCount().intValue(),
                 leftChild.getRecordCount().intValue() + rightChild.getRecordCount().intValue());
    assertEquals(node.getId() + "+", rightChild.getId());
    assertEquals(node.getId() + "-", leftChild.getId());
    checkNode(rightChild);
    checkNode(leftChild);
  } else {
    // Leaf
    List<ScoreDistribution> scoreDists = node.getScoreDistributions();
    int numDists = scoreDists.size();
    assertRange(numDists, 1, 2);
    ScoreDistribution first = scoreDists.get(0);
    if (numDists == 1) {
      assertEquals(1.0, first.getConfidence().doubleValue());
    } else {
      assertGreater(first.getConfidence().doubleValue(), 0.0);
      assertLess(first.getConfidence().doubleValue(), 1.0);
      ScoreDistribution second = scoreDists.get(1);
      assertGreater(second.getConfidence().doubleValue(), 0.0);
      assertLess(second.getConfidence().doubleValue(), 1.0);
    }
  }
}
 
Example #14
Source File: RDFUpdate.java    From oryx with Apache License 2.0 5 votes vote down vote up
private Predicate buildPredicate(Split split,
                                 CategoricalValueEncodings categoricalValueEncodings) {
  if (split == null) {
    // Left child always applies, but is evaluated second
    return new True();
  }

  int featureIndex = inputSchema.predictorToFeatureIndex(split.feature());
  FieldName fieldName = FieldName.create(inputSchema.getFeatureNames().get(featureIndex));

  if (split.featureType().equals(FeatureType.Categorical())) {
    // Note that categories in MLlib model select the *left* child but the
    // convention here will be that the predicate selects the *right* child
    // So the predicate will evaluate "not in" this set
    // More ugly casting
    @SuppressWarnings("unchecked")
    Collection<Double> javaCategories = (Collection<Double>) (Collection<?>)
        JavaConversions.seqAsJavaList(split.categories());
    Set<Integer> negativeEncodings = javaCategories.stream().map(Double::intValue).collect(Collectors.toSet());

    Map<Integer,String> encodingToValue =
        categoricalValueEncodings.getEncodingValueMap(featureIndex);
    List<String> negativeValues = negativeEncodings.stream().map(encodingToValue::get).collect(Collectors.toList());

    String joinedValues = TextUtils.joinPMMLDelimited(negativeValues);
    return new SimpleSetPredicate(fieldName,
                                  SimpleSetPredicate.BooleanOperator.IS_NOT_IN,
                                  new Array(Array.Type.STRING, joinedValues));

  } else {
    // For MLlib, left means <= threshold, so right means >
    return new SimplePredicate(fieldName,
        SimplePredicate.Operator.GREATER_THAN,
        Double.toString(split.threshold()));
  }
}
 
Example #15
Source File: RegressionTree.java    From pyramid with Apache License 2.0 5 votes vote down vote up
public TreeModel encodeTreeModel(Schema schema){
    org.dmg.pmml.tree.Node root = new org.dmg.pmml.tree.Node()
            .setPredicate(new True());

    encodeNode(root, 0, schema);

    TreeModel treeModel = new TreeModel(MiningFunction.REGRESSION, ModelUtil.createMiningSchema(schema.getLabel()), root)
            .setSplitCharacteristic(TreeModel.SplitCharacteristic.BINARY_SPLIT)
            .setMissingValueStrategy(TreeModel.MissingValueStrategy.NONE)
            .setMathContext(MathContext.FLOAT);

    return treeModel;
}
 
Example #16
Source File: MiningModelUtil.java    From pyramid with Apache License 2.0 5 votes vote down vote up
static
public Segmentation createSegmentation(Segmentation.MultipleModelMethod multipleModelMethod, List<? extends Model> models, List<? extends Number> weights){

    if((weights != null) && (models.size() != weights.size())){
        throw new IllegalArgumentException();
    }

    List<Segment> segments = new ArrayList<>();

    for(int i = 0; i < models.size(); i++){
        Model model = models.get(i);
        Number weight = (weights != null ? weights.get(i) : null);

        Segment segment = new Segment()
                .setId(String.valueOf(i + 1))
                .setPredicate(new True())
                .setModel(model);

        if(weight != null && !ValueUtil.isOne(weight)){
            segment.setWeight(ValueUtil.asDouble(weight));
        }

        segments.add(segment);
    }

    return new Segmentation(multipleModelMethod, segments);
}
 
Example #17
Source File: GBMConverter.java    From jpmml-r with GNU Affero General Public License v3.0 5 votes vote down vote up
private TreeModel encodeTreeModel(MiningFunction miningFunction, RGenericVector tree, RGenericVector c_splits, Schema schema){
	Node root = encodeNode(True.INSTANCE, 0, tree, c_splits, new FlagManager(), new CategoryManager(), schema);

	TreeModel treeModel = new TreeModel(miningFunction, ModelUtil.createMiningSchema(schema.getLabel()), root)
		.setSplitCharacteristic(TreeModel.SplitCharacteristic.MULTI_SPLIT);

	return treeModel;
}
 
Example #18
Source File: Tree.java    From jpmml-lightgbm with GNU Affero General Public License v3.0 5 votes vote down vote up
public TreeModel encodeTreeModel(PredicateManager predicateManager, Schema schema){
	Node root = encodeNode(True.INSTANCE, predicateManager, new CategoryManager(), 0, schema);

	TreeModel treeModel = new TreeModel(MiningFunction.REGRESSION, ModelUtil.createMiningSchema(schema.getLabel()), root)
		.setSplitCharacteristic(TreeModel.SplitCharacteristic.BINARY_SPLIT)
		.setMissingValueStrategy(TreeModel.MissingValueStrategy.DEFAULT_CHILD);

	return treeModel;
}
 
Example #19
Source File: IForestConverter.java    From jpmml-r with GNU Affero General Public License v3.0 5 votes vote down vote up
private TreeModel encodeTreeModel(RGenericVector trees, int index, Schema schema){
	RIntegerVector nrnodes = trees.getIntegerElement("nrnodes");
	RIntegerVector ntree = trees.getIntegerElement("ntree");
	RIntegerVector nodeStatus = trees.getIntegerElement("nodeStatus");
	RIntegerVector leftDaughter = trees.getIntegerElement("lDaughter");
	RIntegerVector rightDaughter = trees.getIntegerElement("rDaughter");
	RIntegerVector splitAtt = trees.getIntegerElement("splitAtt");
	RDoubleVector splitPoint = trees.getDoubleElement("splitPoint");
	RIntegerVector nSam = trees.getIntegerElement("nSam");

	int rows = nrnodes.asScalar();
	int columns = ntree.asScalar();

	Node root = encodeNode(
		True.INSTANCE,
		0,
		0,
		FortranMatrixUtil.getColumn(nodeStatus.getValues(), rows, columns, index),
		FortranMatrixUtil.getColumn(nSam.getValues(), rows, columns, index),
		FortranMatrixUtil.getColumn(leftDaughter.getValues(), rows, columns, index),
		FortranMatrixUtil.getColumn(rightDaughter.getValues(), rows, columns, index),
		FortranMatrixUtil.getColumn(splitAtt.getValues(), rows, columns, index),
		FortranMatrixUtil.getColumn(splitPoint.getValues(), rows, columns, index),
		schema
	);

	TreeModel treeModel = new TreeModel(MiningFunction.REGRESSION, ModelUtil.createMiningSchema(schema.getLabel()), root)
		.setSplitCharacteristic(TreeModel.SplitCharacteristic.BINARY_SPLIT);

	return treeModel;
}
 
Example #20
Source File: TreeModelUtil.java    From jpmml-sparkml with GNU Affero General Public License v3.0 5 votes vote down vote up
static
private <M extends Model<M> & DecisionTreeModel> TreeModel encodeTreeModel(M model, PredicateManager predicateManager, MiningFunction miningFunction, ScoreEncoder scoreEncoder, Schema schema){
	Node root = encodeNode(True.INSTANCE, model.rootNode(), predicateManager, new CategoryManager(), scoreEncoder, schema);

	TreeModel treeModel = new TreeModel(miningFunction, ModelUtil.createMiningSchema(schema.getLabel()), root)
		.setSplitCharacteristic(TreeModel.SplitCharacteristic.BINARY_SPLIT);

	return treeModel;
}
 
Example #21
Source File: RangerConverter.java    From jpmml-r with GNU Affero General Public License v3.0 5 votes vote down vote up
private TreeModel encodeTreeModel(MiningFunction miningFunction, ScoreEncoder scoreEncoder, RGenericVector childNodeIDs, RNumberVector<?> splitVarIDs, RNumberVector<?> splitValues, RGenericVector terminalClassCounts, Schema schema){
	RNumberVector<?> leftChildIDs = (RNumberVector<?>)childNodeIDs.getValue(0);
	RNumberVector<?> rightChildIDs = (RNumberVector<?>)childNodeIDs.getValue(1);

	Node root = encodeNode(True.INSTANCE, 0, scoreEncoder, leftChildIDs, rightChildIDs, splitVarIDs, splitValues, terminalClassCounts, new CategoryManager(), schema);

	TreeModel treeModel = new TreeModel(miningFunction, ModelUtil.createMiningSchema(schema.getLabel()), root)
		.setSplitCharacteristic(TreeModel.SplitCharacteristic.BINARY_SPLIT);

	return treeModel;
}
 
Example #22
Source File: BinaryTreeConverter.java    From jpmml-r with GNU Affero General Public License v3.0 5 votes vote down vote up
private TreeModel encodeTreeModel(RGenericVector tree, Schema schema){
	Node root = encodeNode(True.INSTANCE, tree, schema);

	TreeModel treeModel = new TreeModel(this.miningFunction, ModelUtil.createMiningSchema(schema.getLabel()), root)
		.setSplitCharacteristic(TreeModel.SplitCharacteristic.BINARY_SPLIT);

	return treeModel;
}
 
Example #23
Source File: TreeModelFlattener.java    From jpmml-sklearn with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void exitNode(Node node){
	Predicate predicate = node.getPredicate();

	if(predicate instanceof True){
		Node parentNode = getParentNode();

		if(parentNode == null){
			return;
		}

		List<Node> parentChildren = parentNode.getNodes();
		if(parentChildren.size() != 1){
			return;
		}

		boolean success = parentChildren.remove(node);
		if(!success){
			throw new IllegalArgumentException();
		} // End if

		if((MiningFunction.REGRESSION).equals(this.miningFunction)){
			parentNode.setScore(null);

			initScore(parentNode, node);
		} else

		if((MiningFunction.CLASSIFICATION).equals(this.miningFunction)){
			initScoreDistribution(parentNode, node);
		} else

		{
			throw new IllegalArgumentException();
		}
	}
}
 
Example #24
Source File: RegTree.java    From jpmml-xgboost with GNU Affero General Public License v3.0 5 votes vote down vote up
public TreeModel encodeTreeModel(PredicateManager predicateManager, Schema schema){
	org.dmg.pmml.tree.Node root = encodeNode(True.INSTANCE, predicateManager, 0, schema);

	TreeModel treeModel = new TreeModel(MiningFunction.REGRESSION, ModelUtil.createMiningSchema(schema.getLabel()), root)
		.setSplitCharacteristic(TreeModel.SplitCharacteristic.BINARY_SPLIT)
		.setMissingValueStrategy(TreeModel.MissingValueStrategy.DEFAULT_CHILD)
		.setMathContext(MathContext.FLOAT);

	return treeModel;
}
 
Example #25
Source File: TreeModelCompactor.java    From jpmml-sklearn with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void exitNode(Node node){
	Predicate predicate = node.getPredicate();

	if(predicate instanceof True){
		Node parentNode = getParentNode();

		if(parentNode == null){
			return;
		}

		if((MiningFunction.REGRESSION).equals(this.miningFunction)){
			parentNode.setScore(null);

			initScore(parentNode, node);
			replaceChildWithGrandchildren(parentNode, node);
		} else

		if((MiningFunction.CLASSIFICATION).equals(this.miningFunction)){

			// Replace intermediate nodes, but not terminal nodes
			if(node.hasNodes()){
				replaceChildWithGrandchildren(parentNode, node);
			}
		} else

		{
			throw new IllegalArgumentException();
		}
	}
}
 
Example #26
Source File: TreeModelCompactor.java    From jpmml-sparkml with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void exitNode(Node node){
	Predicate predicate = node.getPredicate();

	if(predicate instanceof True){
		Node parentNode = getParentNode();

		if(parentNode == null){
			return;
		}

		if((MiningFunction.REGRESSION).equals(this.miningFunction)){
			initScore(parentNode, node);
			replaceChildWithGrandchildren(parentNode, node);
		} else

		if((MiningFunction.CLASSIFICATION).equals(this.miningFunction)){

			// Replace intermediate nodes, but not terminal nodes
			if(node.hasNodes()){
				replaceChildWithGrandchildren(parentNode, node);
			}
		} else

		{
			throw new IllegalArgumentException();
		}
	}
}
 
Example #27
Source File: RandomForestCompactor.java    From jpmml-r with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void exitNode(Node node){
	Predicate predicate = node.getPredicate();

	if(predicate instanceof True){
		Node parentNode = getParentNode();

		if(parentNode == null){
			return;
		}

		initScore(parentNode, node);
		replaceChildWithGrandchildren(parentNode, node);
	}
}
 
Example #28
Source File: GolfingTreeModelExample.java    From jpmml-model with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public PMML produce(){
	FieldName temperature = FieldName.create("temperature");
	FieldName humidity = FieldName.create("humidity");
	FieldName windy = FieldName.create("windy");
	FieldName outlook = FieldName.create("outlook");
	FieldName whatIdo = FieldName.create("whatIDo");

	Header header = new Header()
		.setCopyright("www.dmg.org")
		.setDescription("A very small binary tree model to show structure.");

	DataDictionary dataDictionary = new DataDictionary()
		.addDataFields(
			new DataField(temperature, OpType.CONTINUOUS, DataType.DOUBLE),
			new DataField(humidity, OpType.CONTINUOUS, DataType.DOUBLE),
			new DataField(windy, OpType.CATEGORICAL, DataType.STRING)
				.addValues(createValues("true", "false")),
			new DataField(outlook, OpType.CATEGORICAL, DataType.STRING)
				.addValues(createValues("sunny", "overcast", "rain")),
			new DataField(whatIdo, OpType.CATEGORICAL, DataType.STRING)
				.addValues(createValues("will play", "may play", "no play"))
		);

	dataDictionary.setNumberOfFields((dataDictionary.getDataFields()).size());

	MiningSchema miningSchema = new MiningSchema()
		.addMiningFields(
			new MiningField(temperature),
			new MiningField(humidity),
			new MiningField(windy),
			new MiningField(outlook),
			new MiningField(whatIdo)
				.setUsageType(MiningField.UsageType.TARGET)
		);

	Node root = new BranchNode("will play", True.INSTANCE);

	// Upper half of the tree
	root.addNodes(
		new BranchNode("will play", new SimplePredicate(outlook, Operator.EQUAL, "sunny"))
			.addNodes(
				new BranchNode("will play",
					createCompoundPredicate(BooleanOperator.AND,
						new SimplePredicate(temperature, Operator.LESS_THAN, "90"),
						new SimplePredicate(temperature, Operator.GREATER_THAN, "50"))
					)
					.addNodes(
						new LeafNode("will play", new SimplePredicate(humidity, Operator.LESS_THAN, "80")),
						new LeafNode("no play", new SimplePredicate(humidity, Operator.GREATER_OR_EQUAL, "80"))
					),
				new LeafNode("no play",
					createCompoundPredicate(BooleanOperator.OR,
						new SimplePredicate(temperature, Operator.GREATER_OR_EQUAL, "90"),
						new SimplePredicate(temperature, Operator.LESS_OR_EQUAL, "50"))
					)
			)
	);

	// Lower half of the tree
	root.addNodes(
		new BranchNode("may play",
			createCompoundPredicate(BooleanOperator.OR,
				new SimplePredicate(outlook, Operator.EQUAL, "overcast"),
				new SimplePredicate(outlook, Operator.EQUAL, "rain"))
			)
			.addNodes(
				new LeafNode("may play",
					createCompoundPredicate(BooleanOperator.AND,
						new SimplePredicate(temperature, Operator.GREATER_THAN, "60"),
						new SimplePredicate(temperature, Operator.LESS_THAN, "100"),
						new SimplePredicate(outlook, Operator.EQUAL, "overcast"),
						new SimplePredicate(humidity, Operator.LESS_THAN, "70"),
						new SimplePredicate(windy, Operator.EQUAL, "false"))
					),
				new LeafNode("no play",
					createCompoundPredicate(BooleanOperator.AND,
						new SimplePredicate(outlook, Operator.EQUAL, "rain"),
						new SimplePredicate(humidity, Operator.LESS_THAN, "70"))
					)
			)
	);

	TreeModel treeModel = new TreeModel(MiningFunction.CLASSIFICATION, miningSchema, root)
		.setModelName("golfing");

	PMML pmml = new PMML(Version.PMML_4_4.getVersion(), header, dataDictionary)
		.addModels(treeModel);

	return pmml;
}
 
Example #29
Source File: TreeModelCompactor.java    From jpmml-lightgbm with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void enterNode(Node node){
	Object id = node.getId();
	Object score = node.getScore();
	Object defaultChild = node.getDefaultChild();

	if(id == null){
		throw new IllegalArgumentException();
	} // End if

	if(node.hasNodes()){
		List<Node> children = node.getNodes();

		if(children.size() != 2 || score != null || defaultChild == null){
			throw new IllegalArgumentException();
		}

		Node firstChild = children.get(0);
		Node secondChild = children.get(1);

		if(equalsNode(defaultChild, firstChild)){
			children = swapChildren(node);

			firstChild = children.get(0);
			secondChild = children.get(1);
		} else

		if(equalsNode(defaultChild, secondChild)){
			// Ignored
		} else

		{
			throw new IllegalArgumentException();
		}

		node.setDefaultChild(null);

		secondChild.setPredicate(True.INSTANCE);
	} else

	{
		if(score == null || defaultChild != null){
			throw new IllegalArgumentException();
		}
	}

	node.setId(null);
}
 
Example #30
Source File: TreeModelCompactor.java    From jpmml-xgboost with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void enterNode(Node node){
	Object id = node.getId();
	Object score = node.getScore();
	Object defaultChild = node.getDefaultChild();

	if(id == null){
		throw new IllegalArgumentException();
	} // End if

	if(node.hasNodes()){
		List<Node> children = node.getNodes();

		if(children.size() != 2 || score != null || defaultChild == null){
			throw new IllegalArgumentException();
		}

		Node firstChild = children.get(0);
		Node secondChild = children.get(1);

		if(equalsNode(defaultChild, firstChild)){
			children = swapChildren(node);

			firstChild = children.get(0);
			secondChild = children.get(1);
		} else

		if(equalsNode(defaultChild, secondChild)){
			// Ignored
		} else

		{
			throw new IllegalArgumentException();
		}

		node.setDefaultChild(null);

		secondChild.setPredicate(True.INSTANCE);
	} else

	{
		if(score == null || defaultChild != null){
			throw new IllegalArgumentException();
		}
	}

	node.setId(null);
}