public class hierCluster {
public List startAnalysis(List nodes,int ClusterNum){
List finalClusters=new ArrayList();
List originalClusters=InitialCluster(nodes);
finalClusters=originalClusters;
while(finalClusters.size()>ClusterNum){
double min=Double.MAX_VALUE;
int mergeIndexA=0;
int mergeIndexB=0;
for(int i=0;i
for(int j=0;j
if(i!=j){
Cluster clusterA=finalClusters.get(i);
Cluster clusterB=finalClusters.get(j);
List nodesA=clusterA.getNodes();
List nodesB=clusterB.getNodes();
for(int m=0;m
for(int n=0;n
double tempDis=dist(nodesA.get(m),nodesB.get(n));
if(tempDis
min=tempDis;
mergeIndexA=i;
mergeIndexB=j;
}
}
}
}
} //end for j
}// end for i
//合并cluster[mergeIndexA]和cluster[mergeIndexB]
finalClusters=mergeCluster(finalClusters,mergeIndexA,mergeIndexB);
}//end while
return finalClusters;
}
private List mergeCluster(List finalCluster, int mergeIndexA, int mergeIndexB) {
if(mergeIndexA!=mergeIndexB)
{
Cluster clusterA=finalCluster.get(mergeIndexA);
Cluster clusterB=finalCluster.get(mergeIndexB);
List nodesA=clusterA.getNodes();
ListnodesB=clusterB.getNodes();
for (Node dp : nodesB) {
Node tempDp = new Node();
tempDp.setNodeName(dp.getNodeName());
tempDp.setDimension(dp.getDimension());
tempDp.setCluster(clusterA);
nodesA.add(tempDp);
}
clusterA.setNodes(nodesA);
finalCluster.remove(mergeIndexB);
//System.out.println(" remove mergeIndexA"+mergeIndexA+";"+mergeIndexB);
}
return finalCluster;
}
public double dist(Node a,Node b)
{
double[] dimensionA=a.getDimension();
double[] dimensionB=b.getDimension();
double distance=0;
if(dimensionA.length==dimensionB.length)//注意易出错为://if(
dimensionA==dimensionB)
{
for(int j=0;j
{
double temp=Math.pow(dimensionA[j]-dimensionB[j], 2);
distance=distance+temp;
}
distance=Math.pow(distance, 0.5);
}
return distance;
}
public List InitialCluster(Listnodes)
{
ListoriginalCluster=new ArrayList();
for(int i=0;i
{
Node tempNode=nodes.get(i);
ListtempNodes=new ArrayList();
tempNodes.add(tempNode);
Cluster tempCluster=new Cluster();
tempCluster.setClusterName("cluster"+String.valueOf(i));
tempCluster.setNodes(tempNodes);
tempNode.setCluster(tempCluster);
originalCluster.add(tempCluster);
}
return originalCluster;
}
public static void main(String[] args) {
ArrayList nodes = new ArrayList();
for(int i=0;i<20;i++){//随机产生点
float tempx=(float) Math.random();
float tempy=(float) Math.random();
double[]a={tempx,tempy};
Node tempNode=new Node(a,String.valueOf(i));
nodes.add(tempNode);
}
int clusterNum=5; //类簇数
hierCluster hc=new hierCluster();
List clusters=hc.startAnalysis(nodes, clusterNum);
for(Cluster cl:clusters){
System.out.println("------"+cl.getClusterName()+"------");
List tempDps=cl.getNodes();
for(Node tempdp:tempDps){
System.out.println(tempdp.getNodeName());
}
}
}
}