GiniImpurityMeasure implements ImpurityMeasure<GiniImpurityMeasure> { @Override public double impurity() { long leftCnt = 0; long rightCnt = 0; double leftImpurity = 0; double rightImpurity = 0; for (long e : left) leftCnt += e; for (long e : right) rightCnt += e; if (leftCnt > 0) for (long e : left) leftImpurity += Math.pow(e, 2) / leftCnt; if (rightCnt > 0) for (long e : right) rightImpurity += Math.pow(e, 2) / rightCnt; return -(leftImpurity + rightImpurity); } GiniImpurityMeasure(long[] left, long[] right); @Override double impurity(); @Override GiniImpurityMeasure add(GiniImpurityMeasure b); @Override GiniImpurityMeasure subtract(GiniImpurityMeasure b); long[] getLeft(); long[] getRight();  }
@Test public void testImpurityOnEmptyData() { long[] left = new long[]{0, 0, 0}; long[] right = new long[]{0, 0, 0}; GiniImpurityMeasure impurity = new GiniImpurityMeasure(left, right); assertEquals(0.0, impurity.impurity(), 1e-10); }
@Test public void testImpurityLeftPart() { long[] left = new long[]{3, 0, 0}; long[] right = new long[]{0, 0, 0}; GiniImpurityMeasure impurity = new GiniImpurityMeasure(left, right); assertEquals(-3, impurity.impurity(), 1e-10); }
@Test public void testImpurityRightPart() { long[] left = new long[]{0, 0, 0}; long[] right = new long[]{3, 0, 0}; GiniImpurityMeasure impurity = new GiniImpurityMeasure(left, right); assertEquals(-3, impurity.impurity(), 1e-10); }
@Test public void testImpurityLeftAndRightPart() { long[] left = new long[]{3, 0, 0}; long[] right = new long[]{0, 3, 0}; GiniImpurityMeasure impurity = new GiniImpurityMeasure(left, right); assertEquals(-6, impurity.impurity(), 1e-10); }