import gov.sandia.cognition.math.matrix.Vector; //导入方法依赖的package包/类
public ArrayList initializeClusters(
int numClusters,
Collection extends Vector> elements)
{
if (numClusters < 0)
{
// Error: Bad number of clusters.
throw new IllegalArgumentException(
"The number of clusters cannot be negative.");
}
else if (elements == null)
{
// Error: Bad elements.
throw new NullPointerException("The elements cannot be null.");
}
else if (numClusters == 0 || elements.size() == 0)
{
// No clusters to create.
return new ArrayList();
}
ArrayList elementsArray =
new ArrayList(elements);
// Initialize the cluster objects.
ArrayList clusterList =
new ArrayList();
for (int k = 0; k < numClusters; k++)
{
// keep selecting random point until and ensure that the
// means aren't on top of eachother
Vector mean = null;
double minDiff = 0.0;
while (minDiff <= 0.0)
{
// select a new data point at random and place the cluster
// on top of it
int index = this.random.nextInt( elements.size() );
// add some noise to the point
Vector data = elementsArray.get(index);
Vector randomNoise = VectorFactory.getDefault().createUniformRandom(
data.getDimensionality(),
-this.getRandomRange(), this.getRandomRange(), this.random );
mean = data.plus(randomNoise);
minDiff = Double.POSITIVE_INFINITY;
for (int i = 0; i < k; i++)
{
Vector otherMean =
clusterList.get(i).getGaussian().getMean();
double diff = mean.euclideanDistance(otherMean);
if (minDiff > diff)
{
minDiff = diff;
}
}
}
// create a diagonal covariance matrix with "defaultCovariance"
// on the diagonal, and zeros elsewhere
int M = mean.getDimensionality();
Matrix covariance = MatrixFactory.getDefault().createIdentity(M, M).scale(this.getDefaultCovariance());
MultivariateGaussian.PDF gaussian =
new MultivariateGaussian.PDF(mean, covariance);
GaussianCluster cluster = new GaussianCluster(null, gaussian);
clusterList.add(cluster);
}
return clusterList;
}