【发布时间】:2020-01-04 02:39:29
【问题描述】:
我最终必须显示 K-menas 集群(集群的中心和属于集群的点)。现在我拥有 ArrayList 的中心和数据集,然后我将 ArrayLists 加入集群(也是 ArrayList)。但在这里我不知道如何为每个集群添加颜色。这意味着中心的每次迭代颜色都将保持不变,但点会根据它们所属的女巫集群改变颜色(= 女巫中心是最近的)。
我应该使用哈希图吗?关键是颜色?怎么改?
/* n= Number of centers, int lowerBound = 0, int upperBound =1000000 */
public static List<PointXY> randomCentri(int n, int lowerBound, int upperBound) {
List<PointXY> centers = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
float x = (float)(Math.random() * (upperBound - lowerBound) + lowerBound);
float y = (float)(Math.random() * (upperBound - lowerBound) + lowerBound);
PointXY point = new PointXY(x, y);
centers.add(point);
}
return centers;
}
// Dataset from file (.txt) (GPS coordinates)
public static List<PointXY> podatki(String inputFile) throws Exception {
List<PointXY> dataset = new ArrayList<>();
BufferedReader br = new BufferedReader(new FileReader(inputFile));
String line;
while ((line = br.readLine()) != null) {
String[] tokens = line.split(",");
float x = Float.valueOf(tokens[0]);
float y = Float.valueOf(tokens[1]);
PointXY point = new PointXY(x, y);
dataset.add(point);
}
br.close();
return dataset;
}
基本上这是 K-Means 算法的核心。我们首先分配一个名为 clusters 的列表列表,它使用 center.size() 空列表进行初始化。然后,对于我们数据集中的每一个数据,我们通过前面定义的getNearestPointIndex方法得到最近的中心索引,并将数据附加到最近中心的簇列表中。第三个循环,对于簇中的每个簇,我们计算平均值并将其附加到noviCentri变量中,作为我们方法的返回值。
public static List<PointXY> noviCentri(List<PointXY> dataset, List<PointXY> centers) {
List<List<PointXY>> clusters = new ArrayList<>(centers.size());
for (int i = 0; i < centers.size(); i++) {
clusters.add(new ArrayList<PointXY>());
}
for (PointXY data : dataset) {
int index = data.najblizjaTIndex(centers);
clusters.get(index).add(data);
}
List<PointXY> noviCentri = new ArrayList<>(centers.size());
for (List<PointXY> cluster : clusters) {
noviCentri.add(PointXY.povprecje(cluster));
}
return noviCentri;
}
【问题讨论】: