Skip to content

Commit

Permalink
PUB-923: Add JUnit test for numerical accuracy of KMeans for trivial …
Browse files Browse the repository at this point in the history
…3D case.
  • Loading branch information
arnocandel committed Aug 7, 2014
1 parent 7888375 commit 4ae77ae
Showing 1 changed file with 60 additions and 0 deletions.
60 changes: 60 additions & 0 deletions src/test/java/hex/KMeans2Test.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,13 @@
import org.junit.BeforeClass;
import org.junit.Test;
import water.*;
import water.fvec.FVecTest;
import water.fvec.Frame;
import water.fvec.ParseDataset2;
import water.util.Log;
import water.util.Log.Tag.Sys;

import java.util.Arrays;
import java.util.Random;

public class KMeans2Test extends TestUtil {
Expand Down Expand Up @@ -173,4 +176,61 @@ static double dist(double[] cluster, double[] goal) {
frame.delete();
res.delete();
}

private double[] d(double... ds) { return ds; }

boolean close(double[] a, double[] b) {
for (int i=0;i<a.length;++i) {
if (Math.abs(a[i]-b[i]) > 1e-8) return false;
}
return true;
}

@Test public void testCentroids(){
String data =
"1, 0, 0\n" +
"0, 1, 0\n" +
"0, 0, 1\n";
Frame fr = null;
try {
Key k = FVecTest.makeByteVec("yada", data);
fr = ParseDataset2.parse(Key.make(), new Key[]{k});

for( int i=0; i<10; i++ ) {
for( boolean normalize : new boolean[]{false, true}) {
for( Initialization init : new Initialization[]{Initialization.None, Initialization.PlusPlus, Initialization.Furthest}) {
KMeans2 parms = new KMeans2();
parms.source = fr;
parms.k = 3;
parms.normalize = normalize;
parms.max_iter = 100;
parms.initialization = init;
parms.seed = 0;
parms.invoke();
KMeans2Model kmm = UKV.get(parms.dest());

double[][] exp1 = new double[][]{ d(1, 0, 0), d(0, 1, 0), d(0, 0, 1), };
double[][] exp2 = new double[][]{ d(0, 1, 0), d(1, 0, 0), d(0, 0, 1), };
double[][] exp3 = new double[][]{ d(0, 1, 0), d(0, 0, 1), d(1, 0, 0), };
double[][] exp4 = new double[][]{ d(1, 0, 0), d(0, 0, 1), d(0, 1, 0), };
double[][] exp5 = new double[][]{ d(0, 0, 1), d(1, 0, 0), d(0, 1, 0), };
double[][] exp6 = new double[][]{ d(0, 0, 1), d(0, 1, 0), d(1, 0, 0), };

boolean gotit = false;
for (int j = 0; j < parms.k; ++j) gotit |= close(exp1[j], kmm.centers[j]);
for (int j = 0; j < parms.k; ++j) gotit |= close(exp2[j], kmm.centers[j]);
for (int j = 0; j < parms.k; ++j) gotit |= close(exp3[j], kmm.centers[j]);
for (int j = 0; j < parms.k; ++j) gotit |= close(exp4[j], kmm.centers[j]);
for (int j = 0; j < parms.k; ++j) gotit |= close(exp5[j], kmm.centers[j]);
for (int j = 0; j < parms.k; ++j) gotit |= close(exp6[j], kmm.centers[j]);
Assert.assertTrue(gotit);
kmm.delete();
}
}
}

} finally {
if( fr != null ) fr.delete();
}
}
}

0 comments on commit 4ae77ae

Please sign in to comment.