聚类算法kmeans java 代码
时间: 2023-04-07 18:02:52 浏览: 101
KMeans聚类算法+代码
5星 · 资源好评率100%
我可以回答这个问题。K-means算法是一种常用的聚类算法,可以用Java语言实现。以下是一个简单的K-means Java代码示例:
```
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class KMeans {
private int k; // 聚类数
private List<Point> points; // 数据点
private List<Cluster> clusters; // 聚类结果
public KMeans(int k, List<Point> points) {
this.k = k;
this.points = points;
this.clusters = new ArrayList<>();
}
public void cluster() {
// 随机初始化聚类中心
Random random = new Random();
for (int i = 0; i < k; i++) {
Point center = points.get(random.nextInt(points.size()));
Cluster cluster = new Cluster(center);
clusters.add(cluster);
}
// 迭代聚类
boolean changed = true;
while (changed) {
changed = false;
// 清空聚类结果
for (Cluster cluster : clusters) {
cluster.clear();
}
// 将每个数据点归入最近的聚类中心
for (Point point : points) {
Cluster nearestCluster = null;
double minDistance = Double.MAX_VALUE;
for (Cluster cluster : clusters) {
double distance = point.distanceTo(cluster.getCenter());
if (distance < minDistance) {
minDistance = distance;
nearestCluster = cluster;
}
}
nearestCluster.addPoint(point);
}
// 更新聚类中心
for (Cluster cluster : clusters) {
if (cluster.updateCenter()) {
changed = true;
}
}
}
}
public List<Cluster> getClusters() {
return clusters;
}
}
class Point {
private double x;
private double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
public double distanceTo(Point other) {
double dx = x - other.x;
double dy = y - other.y;
return Math.sqrt(dx * dx + dy * dy);
}
}
class Cluster {
private Point center;
private List<Point> points;
public Cluster(Point center) {
this.center = center;
this.points = new ArrayList<>();
}
public Point getCenter() {
return center;
}
public void addPoint(Point point) {
points.add(point);
}
public void clear() {
points.clear();
}
public boolean updateCenter() {
if (points.isEmpty()) {
return false;
}
double sumX = 0;
double sumY = 0;
for (Point point : points) {
sumX += point.getX();
sumY += point.getY();
}
double newCenterX = sumX / points.size();
double newCenterY = sumY / points.size();
if (newCenterX == center.getX() && newCenterY == center.getY()) {
return false;
}
center = new Point(newCenterX, newCenterY);
return true;
}
}
```
这段代码实现了K-means算法的基本流程,包括随机初始化聚类中心、迭代聚类、更新聚类中心等。你可以根据自己的需求进行修改和扩展。
阅读全文