test_code.m 2.11 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
clear all


%
% Try some function calls
% 
try
    mpi_assign_mex(randn(10,100),randn(20,10));
    error('Dimension mismatch!');
end

try
    [CX1,sse,s] = mpi_kmeans_mex(randn(10,100), 0,0);    
    error('0 clusters');
end

%
% a very easy test with known outcome
%
X = [2 0 0;
     1 0 0;
     0 0 2;
     0 0 1;
     0 0 3];

[CX1,sse,s] = mpi_kmeans_mex(X',2,0,1000);

targetCX = [0 1.5;
	    0 0;
	    2 0];

d1 = sum(sum(abs(targetCX - CX1)));
d2 = sum(sum(abs(targetCX(:,2:-1:1) - CX1)));

assert(min(d1,d2)<1e-8);


%
% do 100 random tests
%
for i=1:100
    
    if i==1
	dims = 1;
    else
	dims = ceil(80 * rand);
    end
    
    nclusts = i;
    npts = ceil(10000 * rand);
    X = randn(dims,npts);
    nr_restarts = round(3*rand);
    if nclusts == 1
	CX0 = 1;
    else
	CX0 = randn(dims,nclusts);
    end
    
    maxiter = 0;

    XX = X;
    CC = CX0;
    
    t=cputime;
    [CX1,sse,s] = mpi_kmeans_mex(X, CX0,maxiter,nr_restarts);    
    fprintf('1: time needed %g\n',cputime-t);
    
    assert((sum(XX(:)-X(:)))==0,'Training points X changed');
    assert((sum(CC(:)-CX0(:)))==0,'CX0 changed');
    assert(~any(isnan(CX1(:))),'NaN in CX1');
    
    s2 = mpi_assign_mex(X,CX1);
    assert(all(s2==s),'wrong assignment');

    clear centr
    if dims == 1
	for i=1:size(X,2)
	    [ignore,centr(i,1)] = min(( (CX1 - repmat(X(:,i),1,nclusts)).^2));
	end
    else
	for i=1:size(X,2)
	    [ignore,centr(i,1)] = min(sum( (CX1 - repmat(X(:,i),1,nclusts)).^2));
	end
    end
    
    assert(sum(abs([centr-double(s)]))==0,'wrong assignment');

    
    if (0)
	t=cputime;
	[CX2,sse2,s2] = mpi_kmeans_ordinary(X, CX0,maxiter);    
	fprintf('2: time needed %g\n',cputime-t);
	
	if (sum(XX(:)-X(:)))~=0
	    error('X changed\n');
	end
	if (sum(CC(:)-CX0(:)))~=0
	    error('CX changed\n');
	end

	if any(isnan(CX2(:))) 
	    error('CX2 isnan');
	end

	if (sum(sum(abs(CX1-CX2)))) > 1e-9
	    sum(sum(abs(CX1-CX2)))
	    error('bug: cluster centers not the same');
	end
	
	if (sum(s-s2))~=0
	    error('assignment not the same');
	end
	
	if abs(sse-sse2) > 1e-8
	    error('sse not the same');
	end
	

    end
    
end

fprintf('Test passed\n');