Viết code Java thực hiện phân cụm K-means cho 2 cột dữ liệu cách nhau bởi dấu phẩy, đọc dữ liệu từ file.
Viết code để có thể phân 3 cụm trở lên.
Dữ liệu có dạng như sau:
1,2
3,5
2,4
7,3
9,6
Cho ví dụ về đầu ra của code
Assistant
Dưới đây là ví dụ về code Java thực hiện phân cụm K-means cho 2 cột dữ liệu cách nhau bởi dấu phẩy từ dữ liệu đọc từ file, có thể phân thành 3 cụm trở lên:
java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class KMeans {
private int k; // số cụm
private List<Point> points; // danh sách điểm dữ liệu
private List<Cluster> clusters; // danh sách cụm
public KMeans(int k) {
this.k = k;
this.points = new ArrayList<>();
this.clusters = new ArrayList<>();
}
public void loadData(String filename) {
try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
String line;
while ((line = br.readLine()) != null) {
String[] coordinates = line.split(",");
double x = Double.parseDouble(coordinates[0]);
double y = Double.parseDouble(coordinates[1]);
points.add(new Point(x, y));
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void initClusters() {
for (int i = 0; i < k; i++) {
Cluster cluster = new Cluster(i);
cluster.setCentroid(points.get(i));
clusters.add(cluster);
}
}
public void kmeans() {
boolean isConverged = false;
int iteration = 0;
while (!isConverged) {
clearClusters();
List<Point> prevCentroids = getCentroids();
assignPointsToClusters();
updateCentroids();
iteration++;
List<Point> currentCentroids = getCentroids();
double distance = 0;
for (int i = 0; i < prevCentroids.size(); i++) {
distance += prevCentroids.get(i).distanceTo(currentCentroids.get(i));
}
if (distance == 0) {
isConverged = true;
}
}
System.out.println("Number of iterations: " + iteration);
System.out.println("Clusters:");
for (Cluster cluster : clusters) {
System.out.println(cluster);
}
}
private void clearClusters() {
for (Cluster cluster : clusters) {
cluster.clearPoints();
}
}
private List<Point> getCentroids() {
List<Point> centroids = new ArrayList<>();
for (Cluster cluster : clusters) {
Point centroid = cluster.getCentroid();
centroids.add(centroid);
}
return centroids;
}
private void assignPointsToClusters() {
for (Point point : points) {
double minDistance = Double.MAX_VALUE;
int clusterId = 0;
for (int i = 0; i < k; i++) {
double distance = point.distanceTo(clusters.get(i).getCentroid());
if (distance < minDistance) {
minDistance = distance;
clusterId = i;
}
}
clusters.get(clusterId).addPoint(point);
}
}
private void updateCentroids() {
for (Cluster cluster : clusters) {
double sumX = 0;
double sumY = 0;
List<Point> points = cluster.getPoints();
int nPoints = points.size();
for (Point point : points) {
sumX += point.getX();
sumY += point.getY();
}
if (nPoints > 0) {
double newCentroidX = sumX / nPoints;
double newCentroidY = sumY / nPoints;
cluster.setCentroid(new Point(newCentroidX, newCentroidY));
}
}
}
public static void main(String[] args) {
KMeans kmeans = new KMeans(3);
kmeans.loadData("data.csv");
kmeans.initClusters();
kmeans.kmeans();
}
}
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.getX();
double dy = y - other.getY();
return Math.sqrt(dx * dx + dy * dy);
}
@Override
public String toString() {
return "(" + x + ", " + y + ")";
}
}
class Cluster {
private int id;
private List<Point> points;
private Point centroid;
public Cluster(int id) {
this.id = id;
this.points = new ArrayList<>();
}
public int getId() {
return id;
}
public List<Point> getPoints() {
return points;
}
public Point getCentroid() {
return centroid;
}
public void setCentroid(Point centroid) {
this.centroid = centroid;
}
public void addPoint(Point point) {
points.add(point);
}
public void clearPoints() {
points.clear();
}
@Override
public String toString() {
return "Cluster " + id + ": " + points;
}
}
Trong đoạn code trên, chúng ta đầu tiên định nghĩa lớp Point để biểu diễn một điểm dữ liệu với hai tọa độ x và y. Sau đó, chúng ta định nghĩa lớp Cluster để biểu diễn một cụm với một danh sách các điểm và trọng tâm (centroid). Cuối cùng, chúng ta triển khai lớp KMeans để thực hiện thuật toán phân cụm K-means.
Trong phương thức loadData, chúng ta đọc dữ liệu từ tệp đầu vào và tạo các đối tượng Point tương ứng để lưu trữ dữ liệu. Phương thức initClusters tạo ra các cụm ban đầu bằng cách chọn k điểm dữ liệu đầu tiên làm trọng tâm của các cụm.
Phương thức kmeans triển khai thuật toán phân cụm K-means. Ban đầu, chúng ta thiết lập isConverged = false và iteration = 0 để theo dõi quá trình thuật toán. Trong vòng lặp while, chúng ta sử dụng các phương thức clearClusters, assignPointsToClusters, updateCentroids để cập nhật cụm và trọng tâm của chúng. Cuối cùng, chúng ta kiểm tra xem trọng tâm đã thay đổi chưa bằng cách so sánh khoảng cách giữa các bộ trọng tâm cũ và mới. Nếu khoảng cách bằng 0, thuật toán đã hội tụ và chúng ta đặt isConverged = true để thoát khỏi vòng lặp.
Cuối cùng, trong phương thức main, chúng ta tạo một đối tượng KMeans với k = 3 (số lượng cụm) và gọi các phương thức loadData, initClusters và kmeans.
Lưu ý: Để thực hiện mã này, bạn cần tạo một tệp có tên "data.csv" và đặt dữ liệu vào đó theo định dạng đã cho trong câu hỏi.