但在这里,我不知道如何为每个簇添加颜色。这意味着中心的每次迭代颜色都将保持不变,但点的颜色将根据它们所属的群集而改变(=中心是最近的)。
我应该使用hashmap吗?键是颜色?如何改变?
/* 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的列表列表,该列表使用centers.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;
}发布于 2019-08-31 06:01:26
您可以:
如您所见,您可以选择实现。哪个是“正确的”?好吧,一如既往地,这取决于你的需求:颜色映射是一次性的,“一次性”使用,你只是暂时将颜色归于列表吗?在这种情况下,使用Map选项可能是一个简单、足够的解决方案。或者,您是否更多地将其视为数据集的“基本”属性,需要永久地归属于它们,并在方法之间传递……您是否仍然需要DataSet和ClusterCentre类来添加其他属性,在这种情况下,您不妨从一开始就开始创建这种“适当的”数据结构,并使其在以后需要时更容易扩展……
https://stackoverflow.com/questions/57733561
复制相似问题