本文整理汇总了Java中org.apache.commons.math3.ml.clustering.CentroidCluster类的典型用法代码示例。如果您正苦于以下问题:Java CentroidCluster类的具体用法?Java CentroidCluster怎么用?Java CentroidCluster使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
CentroidCluster类属于org.apache.commons.math3.ml.clustering包,在下文中一共展示了CentroidCluster类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: centroidOf
import org.apache.commons.math3.ml.clustering.CentroidCluster; //导入依赖的package包/类
/**
* Computes the centroid for a cluster.
*
* @param cluster the cluster
* @return the computed centroid for the cluster,
* or {@code null} if the cluster does not contain any points
*/
protected Clusterable centroidOf(final Cluster<T> cluster) {
final List<T> points = cluster.getPoints();
if (points.isEmpty()) {
return null;
}
// in case the cluster is of type CentroidCluster, no need to compute the centroid
if (cluster instanceof CentroidCluster) {
return ((CentroidCluster<T>) cluster).getCenter();
}
final int dimension = points.get(0).getPoint().length;
final double[] centroid = new double[dimension];
for (final T p : points) {
final double[] point = p.getPoint();
for (int i = 0; i < centroid.length; i++) {
centroid[i] += point[i];
}
}
for (int i = 0; i < centroid.length; i++) {
centroid[i] /= points.size();
}
return new DoublePoint(centroid);
}
示例2: assignPointsToClusters
import org.apache.commons.math3.ml.clustering.CentroidCluster; //导入依赖的package包/类
/**
* Adds the given points to the closest {@link Cluster}.
*
* @param clusters the {@link Cluster}s to add the points to
* @param points the points to add to the given {@link Cluster}s
* @param assignments points assignments to clusters
* @return the number of points assigned to different clusters as the iteration before
*/
private int assignPointsToClusters(final List<CentroidCluster<T>> clusters,
final Collection<T> points,
final int[] assignments) {
int assignedDifferently = 0;
int pointIndex = 0;
for (final T p : points) {
int clusterIndex = getNearestCluster(clusters, p);
if (clusterIndex != assignments[pointIndex]) {
assignedDifferently++;
}
CentroidCluster<T> cluster = clusters.get(clusterIndex);
cluster.addPoint(p);
assignments[pointIndex++] = clusterIndex;
}
return assignedDifferently;
}
示例3: trainCodebook
import org.apache.commons.math3.ml.clustering.CentroidCluster; //导入依赖的package包/类
/**
* Return the cluster center points. Each point is n-dimensional where n is the
* number of cepstral coefficients used.
*
* @param cepstralCoefficients
* @return
*/
protected DoublePoint[] trainCodebook(final List<DoublePoint> cepstralCoefficients) {
if (cepstralCoefficients.size() < vqSize) {
throw new IllegalArgumentException("Not enough training data to train model: " +
"coefficient count " + cepstralCoefficients.size() + " < " + vqSize);
}
final List<CentroidCluster<DoublePoint>> centroids = clusterer.cluster(cepstralCoefficients);
final DoublePoint[] centers = new DoublePoint[centroids.size()];
int i = 0;
for (CentroidCluster<DoublePoint> c : centroids) {
centers[i] = new DoublePoint(c.getCenter().getPoint());
i++;
}
return centers;
}
示例4: biggestClusterMean
import org.apache.commons.math3.ml.clustering.CentroidCluster; //导入依赖的package包/类
private static double biggestClusterMean( List<Double> rots ) {
if (rots.isEmpty())
return 0;
class Wrapper implements Clusterable {
double[] rot;
public Wrapper(double r) {
this.rot = new double[] {r};
}
@Override
public double[] getPoint() {
return rot;
}
}
List<Wrapper> toCluster = rots.stream().map(x -> new Wrapper(x) ).collect( Collectors.toList() );
List<CentroidCluster<Wrapper>> results = new KMeansPlusPlusClusterer<Wrapper>( 5, 1000 ).cluster( toCluster );
//
// DBSCANClusterer<Wrapper> cr = new MultiKM DBSCANClusterer<>( 0.05, 100 );
// List<Cluster<Wrapper>> results = cr.cluster( toCluster );
CentroidCluster<Wrapper> biggest = results.stream().max(
( a, b ) -> Double.compare( a.getPoints().size(), b.getPoints().size() ) ).get();
return biggest.getCenter().getPoint()[0];// getPoints().stream().mapToDouble( x -> x.rot[0] ).average().getAsDouble();
}
示例5: cluster
import org.apache.commons.math3.ml.clustering.CentroidCluster; //导入依赖的package包/类
private List<CentroidCluster<DoublePoint>> cluster(int[] pixels) {
KMeansPlusPlusClusterer<DoublePoint> clusterer =
new KMeansPlusPlusClusterer<>(params.maxColors, params.maxIterations);
List<DoublePoint> points = new ArrayList<>();
for (int i = 0; i < pixels.length; i++) {
points.add(new DoublePoint(intToRgbDouble(pixels[i])));
}
return clusterer.cluster(points);
}
示例6: makeColorMap
import org.apache.commons.math3.ml.clustering.CentroidCluster; //导入依赖的package包/类
private int[][] makeColorMap() {
List<int[]> colList = new LinkedList<>();
for (CentroidCluster<DoublePoint> ctr : centers) {
double[] c = ctr.getCenter().getPoint();
int red = (int) Math.round(c[0]);
int grn = (int) Math.round(c[1]);
int blu = (int) Math.round(c[2]);
colList.add(new int[] {red, grn, blu});
}
return colList.toArray(new int[0][]);
}
示例7: getCost
import org.apache.commons.math3.ml.clustering.CentroidCluster; //导入依赖的package包/类
@Override
public double getCost(final List<CentroidCluster<WeightedDoublePoint>> clusters) {
double cost = 0;
for (CentroidCluster<WeightedDoublePoint> cluster : clusters) {
for (WeightedDoublePoint point : cluster.getPoints()) {
cost += FastMath.pow(measure.compute(cluster.getCenter().getPoint(), point.getPoint()), 2);
}
}
return cost;
}
示例8: getPointFromLargestVarianceCluster
import org.apache.commons.math3.ml.clustering.CentroidCluster; //导入依赖的package包/类
/**
* Get a random point from the {@link Cluster} with the largest distance variance.
*
* @param clusters the {@link Cluster}s to search
* @return a random point from the selected cluster
* @throws ConvergenceException if clusters are all empty
*/
private T getPointFromLargestVarianceCluster(final Collection<CentroidCluster<T>> clusters)
throws ConvergenceException {
double maxVariance = Double.NEGATIVE_INFINITY;
Cluster<T> selected = null;
for (final CentroidCluster<T> cluster : clusters) {
if (!cluster.getPoints().isEmpty()) {
// compute the distance variance of the current cluster
final Clusterable center = cluster.getCenter();
final Variance stat = new Variance();
for (final T point : cluster.getPoints()) {
stat.increment(point.getWeight() * distance(point, center));
}
final double variance = stat.getResult();
// select the cluster with the largest variance
if (variance > maxVariance) {
maxVariance = variance;
selected = cluster;
}
}
}
// did we find at least one non-empty cluster ?
if (selected == null) {
throw new ConvergenceException(LocalizedFormats.EMPTY_CLUSTER_IN_K_MEANS);
}
// extract a random point from the cluster
final List<T> selectedPoints = selected.getPoints();
return selectedPoints.remove(random.nextInt(selectedPoints.size()));
}
示例9: getFarthestPoint
import org.apache.commons.math3.ml.clustering.CentroidCluster; //导入依赖的package包/类
/**
* Get the point farthest to its cluster center
*
* @param clusters the {@link Cluster}s to search
* @return point farthest to its cluster center
* @throws ConvergenceException if clusters are all empty
*/
private T getFarthestPoint(final Collection<CentroidCluster<T>> clusters) throws ConvergenceException {
double maxDistance = Double.NEGATIVE_INFINITY;
Cluster<T> selectedCluster = null;
int selectedPoint = -1;
for (final CentroidCluster<T> cluster : clusters) {
// get the farthest point
final Clusterable center = cluster.getCenter();
final List<T> points = cluster.getPoints();
for (int i = 0; i < points.size(); ++i) {
final double distance = points.get(i).getWeight() * distance(points.get(i), center);
if (distance > maxDistance) {
maxDistance = distance;
selectedCluster = cluster;
selectedPoint = i;
}
}
}
// did we find at least one non-empty cluster ?
if (selectedCluster == null) {
throw new ConvergenceException(LocalizedFormats.EMPTY_CLUSTER_IN_K_MEANS);
}
return selectedCluster.getPoints().remove(selectedPoint);
}
示例10: getNearestCluster
import org.apache.commons.math3.ml.clustering.CentroidCluster; //导入依赖的package包/类
/**
* Returns the nearest {@link Cluster} to the given point
*
* @param clusters the {@link Cluster}s to search
* @param point the point to find the nearest {@link Cluster} for
* @return the index of the nearest {@link Cluster} to the given point
*/
private int getNearestCluster(final Collection<CentroidCluster<T>> clusters, final T point) {
double minDistance = Double.MAX_VALUE;
int clusterIndex = 0;
int minCluster = 0;
for (final CentroidCluster<T> c : clusters) {
final double distance = point.getWeight() * distance(point, c.getCenter());
if (distance < minDistance) {
minDistance = distance;
minCluster = clusterIndex;
}
clusterIndex++;
}
return minCluster;
}
示例11: clusters
import org.apache.commons.math3.ml.clustering.CentroidCluster; //导入依赖的package包/类
@operator (
value = "kmeans",
can_be_const = false,
type = IType.LIST,
category = { IOperatorCategory.STATISTICAL },
concept = { IConcept.STATISTIC, IConcept.CLUSTERING })
@doc (
value = "returns the list of clusters (list of instance indices) computed with the kmeans++ algorithm from the first operand data according to the number of clusters to split the data into (k) and the maximum number of iterations to run the algorithm for (If negative, no maximum will be used) (maxIt). Usage: kmeans(data,k,maxit)",
special_cases = "if the lengths of two vectors in the right-hand aren't equal, returns 0",
examples = { @example (
value = "kmeans ([[2,4,5], [3,8,2], [1,1,3], [4,3,4]],2,10)",
isExecutable = false) })
public static GamaList<GamaList> KMeansPlusplusApache(final IScope scope, final GamaList data, final Integer k,
final Integer maxIt) throws GamaRuntimeException {
final MersenneTwister rand = new MersenneTwister(scope.getRandom().getSeed().longValue());
final List<DoublePoint> instances = new ArrayList<DoublePoint>();
for (int i = 0; i < data.size(); i++) {
final GamaList d = (GamaList) data.get(i);
final double point[] = new double[d.size()];
for (int j = 0; j < d.size(); j++) {
point[j] = Cast.asFloat(scope, d.get(j));
}
instances.add(new Instance(i, point));
}
final KMeansPlusPlusClusterer<DoublePoint> kmeans =
new KMeansPlusPlusClusterer<DoublePoint>(k, maxIt, new EuclideanDistance(), rand);
final List<CentroidCluster<DoublePoint>> clusters = kmeans.cluster(instances);
final GamaList results = (GamaList) GamaListFactory.create();
for (final Cluster<DoublePoint> cl : clusters) {
final GamaList clG = (GamaList) GamaListFactory.create();
for (final DoublePoint pt : cl.getPoints()) {
clG.addValue(scope, ((Instance) pt).getId());
}
results.addValue(scope, clG);
}
return results;
}
示例12: clusterSamples
import org.apache.commons.math3.ml.clustering.CentroidCluster; //导入依赖的package包/类
/**
* Generates the clusters on the data using simple K-means++ algorithm.
*
* Warning: even if we give {@link Iterable}, the implementation will load
* everything in memory.
*
* @param nbClusters
* the number of clusters to generate
* @param variables
* all the variables of the samples (ordered as in the CSV)
* @param variablesToUse
* the variables to use in the clustering
* @param samples
* the {@link Iterable} on samples
* @param writer
* the writer for samples with the clusters added. Can be null,
* samples with cluster names will not be written to disk in the
* case.
* @param centroidWriter
* the writer for the centroids. Can be null, centroids will not
* be written to disk in the case.
*/
public void clusterSamples(int nbClusters, String[] variables, String[] variablesToUse, SampleIterable samples,
SampleWriter writer, SampleWriter centroidWriter) {
int[] variableIndices = getVariableIndices(variables, variablesToUse);
List<Point> inputList = new ArrayList<Point>();
for (Sample s : samples) {
inputList.add(new Point(s, variableIndices));
}
KMeansPlusPlusClusterer<Point> c = new KMeansPlusPlusClusterer<Point>(nbClusters, 10);
List<CentroidCluster<Point>> cluster = c.cluster(inputList);
try {
int i = 0;
for (CentroidCluster<Point> cl : cluster) {
String clusterName = "cluster" + i;
if (writer != null) {
for (Point point : cl.getPoints()) {
writer.writeSample(new Sample(point.s.getContent(), clusterName));
}
}
double[] centroidData = cl.getCenter().getPoint();
double[] copyOf = Arrays.copyOf(centroidData, centroidData.length + 1);
copyOf[centroidData.length] = cl.getPoints().size();
if (centroidWriter != null) {
centroidWriter.writeSample(new Sample(copyOf, clusterName));
}
i++;
}
} finally {
IOUtils.closeQuietly(writer);
IOUtils.closeQuietly(centroidWriter);
}
}
示例13: objectClusterer
import org.apache.commons.math3.ml.clustering.CentroidCluster; //导入依赖的package包/类
public static Map<Integer, List<PathObject>> objectClusterer(final Collection<PathObject> pathObjects, final BufferedImage imgThumbnail, final double thumbScaleX, final double thumbScaleY, final int nClusters) {
Map<Integer, List<PathObject>> map = new HashMap<>();
if (pathObjects.isEmpty())
return map;
if (nClusters <= 1 || pathObjects.size() == 1) {
map.put(Integer.valueOf(0), new ArrayList<>(pathObjects));
return map;
}
// int maxIterations = 100;
KMeansPlusPlusClusterer<ClusterableObject> km = new KMeansPlusPlusClusterer<>(nClusters);
List<ClusterableObject> clusterableObjects = new ArrayList<>();
WritableRaster raster = imgThumbnail.getRaster();
int nChannels = raster.getNumBands();
double[] valueBuffer = new double[nChannels];
int w = imgThumbnail.getWidth();
int h = imgThumbnail.getHeight();
boolean isRGB = imgThumbnail.getSampleModel().getNumBands() == 3 && imgThumbnail.getSampleModel().getSampleSize(0) == 8;
for (PathObject pathObject : pathObjects) {
// Get pixel values for the ROI centroid
// CIE LAB is used rather than RGB where possible, due to better suitability for Euclidean distances
ROI roi = pathObject.getROI();
if (roi == null)
continue;
int x = (int)(roi.getCentroidX() * thumbScaleX + 0.5);
int y = (int)(roi.getCentroidY() * thumbScaleY + 0.5);
if (x < 0 || x >= w || y < 0 || y >= h)
continue;
if (isRGB)
valueBuffer = makeCIELAB(imgThumbnail.getRGB(x, y), valueBuffer);
else {
for (int c = 0; c < nChannels; c++)
valueBuffer[c] = raster.getSampleDouble(x, y, c);
}
clusterableObjects.add(new ClusterableObject(pathObject, valueBuffer));
}
List<CentroidCluster<ClusterableObject>> results = km.cluster(clusterableObjects);
int i = 0;
for (CentroidCluster<ClusterableObject> centroidCluster : results) {
Integer label = Integer.valueOf(i);
List<PathObject> objects = new ArrayList<>();
for (ClusterableObject co : centroidCluster.getPoints())
objects.add(co.getPathObject());
map.put(label, objects);
i++;
}
return map;
}
示例14: computedKMeansCluster
import org.apache.commons.math3.ml.clustering.CentroidCluster; //导入依赖的package包/类
public double[][] computedKMeansCluster(double[]... images) {
AdaptedIsoClustering clusterer = new AdaptedIsoClustering(AnalyzeCloudShadowIDAreas.clusterCount,
AnalyzeCloudShadowIDAreas.maxIterCount);
List<Clusterable> list = new ArrayList<>();
for (int xyPos = 0; xyPos < images[0].length; xyPos++) {
double[] values = new double[images.length];
for (int imageIndex = 0; imageIndex < images.length; imageIndex++) {
values[imageIndex] = images[imageIndex][xyPos];
}
list.add(new DoublePoint(values));
}
List<CentroidCluster<Clusterable>> cluster = clusterer.cluster(list);
double[][] clusterCentroidArray = new double[AnalyzeCloudShadowIDAreas.clusterCount][S2IdepixCloudShadowOp.SENSOR_BAND_CLUSTERING];
// double[][] clusterArray = new double[AnalyzeCloudShadowIDAreas.clusterCount][counter+2];
// for (int dd = 0; dd < clusterCount; dd++) {
// for (int ee = 0; ee <counter+2; ee++) {
// clusterArray[dd][ee] = Double.NaN;
// }
// }
int countClusterNumber = 0;
for (CentroidCluster<Clusterable> centroidCluster : cluster) {
for (int ii = 0; ii < S2IdepixCloudShadowOp.SENSOR_BAND_CLUSTERING; ii++) {
clusterCentroidArray[countClusterNumber][ii] = centroidCluster.getCenter().getPoint()[ii];
//System.out.printf("Centroid in cluster: %f %n", centroidCluster.getCenter().getPoint()[0]);
//System.out.printf("Centroid in %d cluster: %.2f %n", countClusterNumber, clusterCentroidArray[countClusterNumber]);
//System.out.printf("Count of all points in %d cluster: %d \n",countClusterNumber, centroidCluster.getPoints().size());
}
// System.out.println("Array of all cluster points in this cluster:");
// Clusterable[] clusterableArray = centroidCluster.getPoints().toArray(new Clusterable[centroidCluster.getPoints().size()]);
// for (int i = 0; i < clusterableArray.length; i++) {
// Clusterable clusterable = clusterableArray[i];
// clusterArray[countClusterNumber][i] = clusterable.getPoint()[0];
// System.out.printf("clusterable[%d]= %.2f %d %.2f%n", i, clusterable.getPoint()[0], countClusterNumber, clusterArray[countClusterNumber][i]);
// }
// System.out.println("Count of all points in this cluster : " + centroidCluster.getPoints().size());
countClusterNumber++;
}
// done
return clusterCentroidArray;
}
示例15: compute
import org.apache.commons.math3.ml.clustering.CentroidCluster; //导入依赖的package包/类
protected synchronized List<Possibility> compute(int numCentroids, int maxIterations, double fuzziness) {
goals.clear();
mapping.reset();
this.spaceWeight = this.spaceWeightNext;
this.altWeight = this.altWeightNext;
this.timeWeight = this.timeWeightNext;
this.tagWeight = this.tagWeightNext;
//2. compute goal vectors
for (NObject o : objects) {
goals.addAll(mapping.newGoals(o));
}
//3. normalize
mapping.normalize(goals);
//4. distance function
DistanceMeasure distanceMetric = new DistanceMeasure() {
@Override
public double compute(double[] a, double[] b) {
double dist = 0;
int i = 0;
if (time) {
dist += Math.abs(a[i] - b[i]) * timeWeight;
i++;
}
if (space) {
//TODO use earth surface distance measurement on non-normalized space lat,lon coordinates
if (spaceWeight!=0) {
double dx = Math.abs(a[i] - b[i]);
i++;
double dy = Math.abs(a[i] - b[i]);
i++;
double ed = Math.sqrt( dx*dx + dy*dy );
dist += ed * spaceWeight;
}
else {
i+=2;
}
}
if (spaceAltitude) {
dist += Math.abs(a[i] - b[i]) * altWeight;
i++;
}
if (tags) {
if ((a.length > 0) && (tagWeight!=0)) {
double tagWeightFraction = tagWeight / (a.length);
for ( ;i < a.length; i++) {
dist += Math.abs(a[i] - b[i]) * tagWeightFraction;
}
}
}
return dist;
}
};
//5. cluster
FuzzyKMeansClusterer<Goal> clusterer = new FuzzyKMeansClusterer<Goal>(numCentroids, fuzziness, maxIterations, distanceMetric);
List<CentroidCluster<Goal>> centroids = clusterer.cluster(goals);
//6. denormalize and return annotated objects
for (Goal g : goals) {
mapping.denormalize(g);
}
return getPossibilities(centroids);
}