Skip to content
The Chat Archive
gpt-3.5-turbo-0613· OpenAI WildChat-4.8M (AI2)

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…

  1. User

    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. 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

  2. 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 đọc từ file:

    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    
    public class KMeansClustering {
        private static final int K = 2; // Số cụm muốn phân
    
        public static void main(String[] args) {
            List<Point> points = readDataFromFile("data.txt"); // Đọc dữ liệu từ file
    
            List<Cluster> clusters = kmeans(points); // Thực hiện phân cụm K-means
            printClusters(clusters); // In ra kết quả
    
        }
    
        private static List<Point> readDataFromFile(String filename) {
            List<Point> points = new ArrayList<>();
    
            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();
            }
    
            return points;
        }
    
        private static List<Cluster> kmeans(List<Point> points) {
            List<Cluster> clusters = initializeClusters(points); // Khởi tạo các cụm ban đầu
    
            boolean changed;
            do {
                assignPointsToClusters(points, clusters); // Gán các điểm vào các cụm
                changed = calculateNewCentroids(clusters); // Tính toán lại vị trí trọng tâm các cụm
            } while (changed);
    
            return clusters;
        }
    
        private static List<Cluster> initializeClusters(List<Point> points) {
            List<Cluster> clusters = new ArrayList<>();
    
            for (int i = 0; i < K; i++) {
                Point centroid = points.get(i);
                Cluster cluster = new Cluster(centroid);
                clusters.add(cluster);
            }
    
            return clusters;
        }
    
        private static void assignPointsToClusters(List<Point> points, List<Cluster> clusters) {
            for (Cluster cluster : clusters) {
                cluster.getPoints().clear();
            }
    
            for (Point point : points) {
                Cluster closestCluster = clusters.get(0);
                double shortestDistance = Double.MAX_VALUE;
    
                for (Cluster cluster : clusters) {
                    double distance = calculateDistance(point, cluster.getCentroid());
                    if (distance < shortestDistance) {
                        shortestDistance = distance;
                        closestCluster = cluster;
                    }
                }
    
                closestCluster.getPoints().add(point);
            }
        }
    
        private static boolean calculateNewCentroids(List<Cluster> clusters) {
            boolean changed = false;
    
            for (Cluster cluster : clusters) {
                Point oldCentroid = cluster.getCentroid();
                Point newCentroid = calculateCentroid(cluster.getPoints());
    
                if (!newCentroid.equals(oldCentroid)) {
                    cluster.setCentroid(newCentroid);
                    changed = true;
                }
            }
    
            return changed;
        }
    
        private static Point calculateCentroid(List<Point> points) {
            double sumX = 0, sumY = 0;
            for (Point point : points) {
                sumX += point.getX();
                sumY += point.getY();
            }
    
            double centroidX = sumX / points.size();
            double centroidY = sumY / points.size();
    
            return new Point(centroidX, centroidY);
        }
    
        private static double calculateDistance(Point p1, Point p2) {
            double dx = p1.getX() - p2.getX();
            double dy = p1.getY() - p2.getY();
            return Math.sqrt(dx * dx + dy * dy);
        }
    
        private static void printClusters(List<Cluster> clusters) {
            for (int i = 0; i < clusters.size(); i++) {
                System.out.println("Cluster " + (i + 1) + ":");
                for (Point point : clusters.get(i).getPoints()) {
                    System.out.println("(" + point.getX() + ", " + point.getY() + ")");
                }
                System.out.println();
            }
        }
    
        private static 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;
            }
    
            @Override
            public boolean equals(Object obj) {
                if (this == obj) {
                    return true;
                }
                if (obj == null || getClass() != obj.getClass()) {
                    return false;
                }
                Point other = (Point) obj;
                return x == other.x && y == other.y;
            }
        }
    
        private static class Cluster {
            private Point centroid;
            private List<Point> points;
    
            public Cluster(Point centroid) {
                this.centroid = centroid;
                this.points = new ArrayList<>();
            }
    
            public Point getCentroid() {
                return centroid;
            }
    
            public void setCentroid(Point centroid) {
                this.centroid = centroid;
            }
    
            public List<Point> getPoints() {
                return points;
            }
        }
    }
    

    Với dữ liệu đầu vào như sau:

    1,2
    3,5
    2,4
    7,3
    9,6
    

    Đầu ra sẽ là:

    Cluster 1:
    (1.0, 2.0)
    (3.0, 5.0)
    (2.0, 4.0)
    
    Cluster 2:
    (7.0, 3.0)
    (9.0, 6.0)
    

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.