All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.openimaj.ml.clustering.kmeans.HierarchicalDoubleKMeans Maven / Gradle / Ivy

Go to download

Various clustering algorithm implementations for all primitive types including random, random forest, K-Means (Exact, Hierarchical and Approximate), ...

There is a newer version: 1.3.10
Show newest version
/*
	AUTOMATICALLY GENERATED BY jTemp FROM
	/Users/jsh2/Work/openimaj/target/checkout/machine-learning/clustering/src/main/jtemp/org/openimaj/ml/clustering/kmeans/Hierarchical#T#KMeans.jtemp
*/
/**
 * Copyright (c) 2011, The University of Southampton and the individual contributors.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 *   * 	Redistributions of source code must retain the above copyright notice,
 * 	this list of conditions and the following disclaimer.
 *
 *   *	Redistributions in binary form must reproduce the above copyright notice,
 * 	this list of conditions and the following disclaimer in the documentation
 * 	and/or other materials provided with the distribution.
 *
 *   *	Neither the name of the University of Southampton nor the names of its
 * 	contributors may be used to endorse or promote products derived from this
 * 	software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
 package org.openimaj.ml.clustering.kmeans;

import gnu.trove.list.array.TIntArrayList;
import gnu.trove.map.hash.TIntObjectHashMap;

import org.openimaj.citation.annotation.Reference;
import org.openimaj.citation.annotation.ReferenceType;
import org.openimaj.data.DataSource;
import org.openimaj.data.IndexedViewDataSource;
import org.openimaj.knn.DoubleNearestNeighbours;
import org.openimaj.ml.clustering.IndexClusters;
import org.openimaj.ml.clustering.SpatialClusterer;
import org.openimaj.ml.clustering.assignment.HardAssigner;
import org.openimaj.ml.clustering.kmeans.HierarchicalDoubleKMeansResult.Node;
import org.openimaj.util.pair.IntDoublePair;

/** 
 * Hierarchical Double K-Means clustering ({@link HierarchicalDoubleKMeans}) is a simple
 * hierarchical version of DoubleKMeans. The algorithm recursively applies 
 * @{link DoubleKMeans} to create more refined partitions of the data.
 *
 * @author Sina Samangooei ([email protected])
 * @author Jonathon Hare ([email protected])
 */
@Reference(
	type = ReferenceType.Inproceedings,
	author = { "David. Nist\'er", "Henrik. Stew\'enius" },
	title = "Scalable Recognition with a Vocabulary Tree",
	year = "2006",
	booktitle = "CVPR",
	pages = { "2161", "", "2168" },
	customData = {
		"Date-Added", "2010-11-12 09:33:18 +0000",
		"Date-Modified", "2010-11-22 15:11:22 +0000"
	}
)
public class HierarchicalDoubleKMeans implements SpatialClusterer {
	/** data dimensionality */
	int M;

	/** K clusters per node */
	int K;

	/** KMeans configuration */
	KMeansConfiguration conf;

	/** Depth of the tree */
	int depth;

	/** 
	 * Construct a new {@link HierarchicalDoubleKMeans} with the given parameters.
	 *
	 * @param config configuration for the underlying kmeans clustering.
	 * @param M Data dimensionality.
	 * @param K Number of clusters per node.
	 * @param depth Tree depth.
	 */
	public HierarchicalDoubleKMeans(KMeansConfiguration config, int M, int K, int depth) {	
		this.conf = config;
		this.M = M;
		this.K = K;
		this.depth = depth;
	}
	
	/** 
	 * Construct a new {@link HierarchicalDoubleKMeans} with the given parameters.
	 * Uses the default parameters of the {@link KMeansConfiguration}.
	 *
	 * @param M Data dimensionality.
	 * @param K Number of clusters per node.
	 * @param depth Tree depth.
	 */
	public HierarchicalDoubleKMeans(int M, int K, int depth) {	
		this(new KMeansConfiguration(), M, K, depth);
	}

	/**
	 * Extract a subset of the data to a buffer
	 * 
	 * @param data Data
	 * @param ids Data labels
	 * @param id Label of data to copy
	 * 
	 * @return a new buffer with a copy of the selected data.
	 */
	private double[][] extractSubset(final double[][] data, int[] ids, int id) {
		int N = data.length;
		int M = data[0].length;
		int count = 0;

		// count how many data points with this label there are
		for (int i = 0; i < N; i++)
			if (ids[i] == id)
				count++;

		// copy each datum to the buffer
		double[][] newData = new double[count][M];
		count = 0;
		for (int i = 0; i < N; i++) {
			if (ids[i] == id) {
				System.arraycopy(data[i], 0, newData[count], 0, M);
				count++;
			}
		}
		return newData;
	}

	/** 
	 * Compute HierarchicalDoubleKMeans clustering.
	 * 
	 * @param data Data to cluster.
	 * @param K Number of clusters for this node.
	 * @param height Tree height.
	 * 
	 * @return a new HierarchicalDoubleKMeans node representing a sub-clustering.
	 **/
	private Node trainLevel(final double[][] data, int K, int height) {
		Node node = new Node();
		node.children = (height == 1) ? null : new Node[K];
		
		DoubleKMeans kmeans = newDoubleKMeans(K);
		node.result = kmeans.cluster(data);
		
		HardAssigner assigner = node.result.defaultHardAssigner();
		
		if (height > 1) {
			int[] ids = assigner.assign(data);
			
			for (int k = 0; k < K; k++) {
				double[][] partition = extractSubset(data, ids, k);

				int partitionK = Math.min(K, partition.length);

				node.children[k] = trainLevel(partition, partitionK, height - 1);
			}
		}

		return node;
	}
	
	/** 
	 * Compute HierarchicalDoubleKMeans clustering.
	 * 
	 * @param data Data to cluster.
	 * @param K Number of clusters for this node.
	 * @param height Tree height.
	 * 
	 * @return a new HierarchicalDoubleKMeans node representing a sub-clustering.
	 **/
	private Node trainLevel(final DataSource data, int K, int height) {
		Node node = new Node();
		node.children = (height == 1) ? null : new Node[K];

		DoubleKMeans kmeans = newDoubleKMeans(K);
		node.result = kmeans.cluster(data);
		
		HardAssigner assigner = node.result.defaultHardAssigner();
		
		if (height > 1) {
			final TIntObjectHashMap assignments = new TIntObjectHashMap();

			final double[][] tmp = new double[1][M];
			for (int i = 0; i < data.size(); i++) {
				data.getData(i, i + 1, tmp);
				final int asgn = assigner.assign(tmp[0]);

				TIntArrayList ids = assignments.get(asgn);
				if (ids == null)
					assignments.put(asgn, ids = new TIntArrayList());
				ids.add(i);
			}

			for (int k = 0; k < K; k++) {
				final int[] indexes = assignments.get(k).toArray();
				final DataSource partition = new IndexedViewDataSource(data, indexes);

				final int partitionK = Math.min(K, partition.size());

				node.children[k] = trainLevel(partition, partitionK, height - 1);
			}
		}

		return node;
	}

	@Override
	public HierarchicalDoubleKMeansResult cluster(final double[][] data) {
		HierarchicalDoubleKMeansResult result = new HierarchicalDoubleKMeansResult();
		
		result.K = K;
		result.M = M;
		result.depth = depth;
		result.root = trainLevel(data, Math.min(K, data.length), depth);
		
		return result;
	}
	
	@Override
	public int[][] performClustering(double[][] data) {
		HierarchicalDoubleKMeansResult clusters = this.cluster(data);
		return new IndexClusters(clusters.defaultHardAssigner().assign(data)).clusters();
	}
	
	@Override
	public HierarchicalDoubleKMeansResult cluster(DataSource data) {
		HierarchicalDoubleKMeansResult result = new HierarchicalDoubleKMeansResult();
		
		result.K = K;
		result.M = M;
		result.depth = depth;
		result.root = trainLevel(data, Math.min(K, data.size()), depth);
		
		return result;
	}

	private DoubleKMeans newDoubleKMeans(int K) {
		KMeansConfiguration newConf = conf.clone();
		newConf.setK(K);
		return new DoubleKMeans(newConf);
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy