[英]Algorithm K-Means
朋友们,希望对你有所帮助,我正在开发Java中的K-Means算法,所以我已经执行了循环来对数据进行相应的质心操作并确定距离,但是每个质心的距离对于循环是不同的. 现在我需要的是把所有这些结果放在自己的周期之外。 我附上部分代码。
System.out.println("\n" + "----------" + "\n" + "Cluster K" + "\n" + "----------");
System.out.println();
for (int i = 0; i < Datos.length; i++) {
distanciaK = (float) Math.sqrt(Math.pow(Datos[i][0] - Datos[10][0], 2) + Math.pow(Datos[i][1] - Datos[10][1], 2) + Math.pow(Datos[i][2] - Datos[10][2], 2) + Math.pow(Datos[i][3] - Datos[10][3], 2) + Math.pow(Datos[i][4] - Datos[10][4], 2));
System.out.println(distanciaK);
}
System.out.println("\n" + "----------" + "\n" + "Cluster M" + "\n" + "----------");
System.out.println();
for (int i = 0; i < Datos.length; i++) {
distanciaM = (float) Math.sqrt(Math.pow(Datos[i][0] - Datos[12][0], 2) + Math.pow(Datos[i][1] - Datos[12][1], 2) + Math.pow(Datos[i][2] - Datos[12][2], 2) + Math.pow(Datos[i][3] - Datos[12][3], 2) + Math.pow(Datos[i][4] - Datos[12][4], 2));
System.out.println(distanciaM);
}
System.out.println();
代码 Output
9.0 8.485281 9.380832 6.3245554 4.2426405 3.6055512 7.615773 8.83176 2.828427 5.8309517 0.0 4.7958317 5.477226 5.196152
5.196152 4.8989797 9.486833 6.928203 4.8989797 3.8729835 7.071068 7.071068 3.1622777 4.2426405 5.477226 6.708204 0.0 1.0
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
导入以上包 Created Map 作为集群名称和值作为代表集群的列表。 将方法添加到相应的 map 条目中。
System.out.println("\n" + "----------" + "\n" + "Cluster K" + "\n" + "----------");
System.out.println();
Map<String,List<Float>> clusterMeanInfo = new HashMap<>();
clusterMeanInfo.put("Cluster K",new ArrayList<>());
clusterMeanInfo.put("Cluster M",new ArrayList<>());
for (int i = 0; i < Datos.length; i++) {
distanciaK = (float) Math.sqrt(Math.pow(Datos[i][0] - Datos[10][0], 2) + Math.pow(Datos[i][1] - Datos[10][1], 2) + Math.pow(Datos[i][2] - Datos[10][2], 2) + Math.pow(Datos[i][3] - Datos[10][3], 2) + Math.pow(Datos[i][4] - Datos[10][4], 2));
System.out.println(distanciaK);
clusterMeanInfo.get("Cluster K").add(distanciaK);
}
System.out.println("\n" + "----------" + "\n" + "Cluster M" + "\n" + "----------");
System.out.println();
for (int i = 0; i < Datos.length; i++) {
distanciaM = (float) Math.sqrt(Math.pow(Datos[i][0] - Datos[12][0], 2) + Math.pow(Datos[i][1] - Datos[12][1], 2) + Math.pow(Datos[i][2] - Datos[12][2], 2) + Math.pow(Datos[i][3] - Datos[12][3], 2) + Math.pow(Datos[i][4] - Datos[12][4], 2));
System.out.println(distanciaM);
kMeans.add(distanciaM);
clusterMeanInfo.get("Cluster K").add(distanciaM);
}
for (String key :clusterMeanInfo.keySet()) {
System.out.print(key + ' ');
clusterMeanInfo.get(key).forEach( value -> {
System.out.print(value + ' ');
});
System.out.println();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.