001/**
002 * Copyright (c) 2011, The University of Southampton and the individual contributors.
003 * All rights reserved.
004 *
005 * Redistribution and use in source and binary forms, with or without modification,
006 * are permitted provided that the following conditions are met:
007 *
008 *   *  Redistributions of source code must retain the above copyright notice,
009 *      this list of conditions and the following disclaimer.
010 *
011 *   *  Redistributions in binary form must reproduce the above copyright notice,
012 *      this list of conditions and the following disclaimer in the documentation
013 *      and/or other materials provided with the distribution.
014 *
015 *   *  Neither the name of the University of Southampton nor the names of its
016 *      contributors may be used to endorse or promote products derived from this
017 *      software without specific prior written permission.
018 *
019 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
020 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
021 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
022 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
023 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
024 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
025 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
026 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
027 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
028 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
029 */
030package org.openimaj.examples.ml.clustering.kmeans;
031
032import java.util.Arrays;
033
034import org.openimaj.data.RandomData;
035import org.openimaj.ml.clustering.ByteCentroidsResult;
036import org.openimaj.ml.clustering.assignment.HardAssigner;
037import org.openimaj.ml.clustering.kmeans.ByteKMeans;
038
039/**
040 * Example showing how to use the Exact or Approximate KMeans clustering
041 * algorithm with in-memory data. The example sets up the clustering algorithm,
042 * generates some uniform random data to cluster, and runs the clustering
043 * algorithm. The resultant clusters are printed, and the example also shows how
044 * to perform cluster assignment (i.e. vector quantisation) in which vectors are
045 * assigned to their closest cluster.
046 * 
047 * @author Jonathon Hare (jsh2@ecs.soton.ac.uk)
048 */
049public class KMeansExample {
050        /**
051         * Main method for the example.
052         * 
053         * @param args
054         *            Ignored.
055         */
056        public static void main(String[] args) {
057                // Set up the variables needed to define the clustering operation
058                final int dimensionality = 2;
059                final int numItems = 10000;
060                final int K = 4;
061
062                // Create the clusterer; there are specific types for all kinds of data
063                // (we're using byte data here). The clusters provide a couple of
064                // static methods to quickly create an exact or approximate (using a
065                // KD-Tree ensemble) K-Means algorithm. Alternatively, the K-Means
066                // clusterer can be constructed with a KMeansConfiguration object which
067                // offers fine control over the k-means algorithm, including control
068                // over the nearest-neighbour implementation (i.e. approximate or not;
069                // different distance functions, etc).
070                final ByteKMeans kmeans = ByteKMeans.createExact(dimensionality, K);
071
072                // Settings for things like the number of iterations can be set through
073                // the KMeansConfiguration either at construction time, or afterwards:
074                kmeans.getConfiguration().setMaxIterations(100);
075
076                // Generate some random data to cluster
077                final byte[][] data = RandomData.getRandomByteArray(numItems, dimensionality, Byte.MIN_VALUE, Byte.MAX_VALUE);
078
079                // Perform the clustering
080                final ByteCentroidsResult result = kmeans.cluster(data);
081
082                // Get an assigner to assign vectors to the closest cluster. You could
083                // also construct an assigner implementation manually if you want
084                // more control over the assigner.
085                final HardAssigner<byte[], ?, ?> assigner = result.defaultHardAssigner();
086
087                // Now investigate which cluster each original data item belonged to:
088                for (int i = 0; i < 10; i++) {
089                        final byte[] vector = data[i];
090
091                        // Each leaf-node of the hierarchy is assigned a unique index number
092                        // between 0 and the total number of leaf-nodes.
093                        final int globalClusterNumber = assigner.assign(vector);
094
095                        System.out.format("%s was assigned to cluster %d\n", Arrays.toString(vector),
096                                        globalClusterNumber);
097                }
098        }
099}