KMean 聚类

news/2024/5/20 5:59:23 标签: 聚类, 数据挖掘

KMean 聚类

  • KMean 聚类
    • 1 解决什么问题
    • 2 java实现计算二维点的聚类案例
    • 输出

KMean 聚类

1 解决什么问题

假设二维坐标轴上有一些点,现在让你把这些点分个类。于是对我们来说,这个分类似乎就是把距离相近的点画到一类中去。

  1. 假设要划分N类,坐标点M
  2. M个坐标点随机选取N个点,作为每个分类的中心点,这N个点的列表记录为centerPointList
  3. 遍历M个坐标点中的每个点
    • 计算当前点和N个中心点的距离,dis1、dis2 ... disN
    • dis1、dis2 ... disN找到最小的距离的下标。下标记录为cluster,那么这个cluster就是这次遍历时候当前点归属的分类。
  4. 步骤3结束后,每个点都会归属到某个分类。计算每个分类中点集合的均值,把这个均值作为新的中心点,替换掉centerPointList
  5. 重复3、4直到重复次数大于约定次数,或者中心点变化较小。此时就可以知道每个点归属的分类。

2 java实现计算二维点的聚类案例

package com.forezp.kmean;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @author yuegang
 */
public class KMeanCluster {
    /**
     * 表示二维空间中的点
     */
    public static class Point {
        Integer x = 0;
        Integer y = 0;

        public Point() {
        }

        public Point(Integer x, Integer y) {
            this.x = x;
            this.y = y;
        }

        public void incX(Integer x) {
            this.x += x;
        }

        public void incY(int y) {
            this.y += y;
        }

        public Integer getX() {
            return x;
        }

        public void setX(Integer x) {
            this.x = x;
        }

        public Integer getY() {
            return y;
        }

        public void setY(Integer y) {
            this.y = y;
        }

        @Override
        public String toString() {
            return "(" + x + ", " + y + ")";
        }
    }

    /**
     * 表示二维空间中的点
     * 下标是点的顺序
     */
    private final List<Point> pointIndexDataMap;

    private final List<List<Point>> centerPointList = Lists.newArrayList(); // 记录每一个分类的中心点

    private final List<Integer> pointClusterMap = Lists.newArrayList(); // 点所属的分类

    private int index = 0; // 计算次数
    private int clusterCount = 0; // 分类个数

    public KMeanCluster(List<Point> pointIndexDataMap, int clusterCount) {
        this.pointIndexDataMap = pointIndexDataMap;
        this.clusterCount = clusterCount;
        index = 0;
        initCenterPoint();
        initCluster(pointIndexDataMap);
    }

    private void initCluster(List<Point> pointIndexDataMap) {
        // 初始化每个点的分类,设置一个没有意义的值
        for (int j = 0; j < pointIndexDataMap.size(); ++j) {
            pointClusterMap.add(-1);
        }
    }

    private void initCenterPoint() {
        List<Point> objects = Lists.newArrayListWithExpectedSize(clusterCount);
        List<Integer> yList = Lists.newArrayListWithExpectedSize(clusterCount);
        Random random = new Random();

        for (int i = 0; i < clusterCount; ++i) { // 注意这个不能相同
            int i1 = random.nextInt(pointIndexDataMap.size());
            while (yList.contains(i1)) {
                i1 = random.nextInt(pointIndexDataMap.size());
            }
            yList.add(i1);
        }

        for (int i = 0; i < clusterCount; ++i) {
            objects.add(pointIndexDataMap.get(yList.get(i)));
        }
        centerPointList.add(objects);
    }

    public void calc() {
        List<Point> pointIndices = centerPointList.get(index);

        for (int i = 0; i < pointIndexDataMap.size(); ++i) {
            Point point = pointIndexDataMap.get(i);
            // 计算该点和那个簇最近,把把归属到这个簇中。

            int cluster = 0;
            double min = Double.MAX_VALUE;

            for (int inc = 0; inc < pointIndices.size(); ++inc) {
                Point point1 = pointIndices.get(inc);
                Integer x = point.getX();
                Integer y = point.getY();
                Integer x1 = point1.getX();
                Integer y1 = point1.getY();

                int i1 = x - x1;
                int i2 = y - y1;
                int total = i1 * i1 + i2 * i2;
                double sqrt = Math.sqrt(total);
                if (sqrt < min) {
                    min = sqrt;
                    cluster = inc;
                }
            }
            pointClusterMap.set(i, cluster);
        }
        // 计算每个族的中心点;
        int size = centerPointList.get(0).size();
        Map<Integer, Point> map = Maps.newTreeMap();
        Map<Integer, Integer> cluterCount = Maps.newHashMapWithExpectedSize(size);
        for (int i = 0; i < pointClusterMap.size(); ++i) {
            int cluster = pointClusterMap.get(i);

            Point point = map.computeIfAbsent(cluster, sss -> new Point());
            cluterCount.put(cluster, cluterCount.getOrDefault(cluster, 0) + 1);

            Point point1 = pointIndexDataMap.get(i);
            point.incX(point1.getX());
            point.incY(point1.getY());
        }

        for (Map.Entry<Integer, Point> integerPointEntry : map.entrySet()) {
            Integer key = integerPointEntry.getKey();
            Point point = integerPointEntry.getValue();
            Integer integer = cluterCount.get(key);

            point.setX(point.getX() / integer);
            point.setY(point.getY() / integer);
        }

        ++index;
        Map<Integer, List<Point>> curClassfiyMap = Maps.newTreeMap();
        for (int i = 0; i < pointClusterMap.size(); ++i) {
            Point point = pointIndexDataMap.get(i);
            Integer classfly = pointClusterMap.get(i);
            List<Point> points = curClassfiyMap.computeIfAbsent(classfly, k -> Lists.newArrayList());
            points.add(point);
        }
        List<Point> curCenterPointList = new ArrayList<>(map.values());
        centerPointList.add(curCenterPointList);
        show(curClassfiyMap, curCenterPointList);
    }

    private void show(Map<Integer, List<Point>> curClassfiyMap, List<Point> curCenterPointList) {
        System.out.println("计算次数:" + index);
        System.out.println("当前分类:" + curClassfiyMap);
        System.out.println("当前中心点:" + curCenterPointList);

    }


    public static void main(String[] args) {
        Point point = new Point(100, 100);
        Point point1 = new Point(1, 1);
        Point point2 = new Point(110, 120);
        Point point3 = new Point(10, 20);
        Point point4 = new Point(130, 160);

        List<Point> pointIndexDataMap = Lists.newArrayList(point, point1, point2, point3, point4);
        KMeanCluster oneCalc = new KMeanCluster(pointIndexDataMap, 2);

        for (int i = 0; i < 2; ++i) {
            oneCalc.calc();
        }
    }
}

输出

计算次数:1
当前分类:{0=[(110, 120), (130, 160)], 1=[(100, 100), (1, 1), (10, 20)]}
当前中心点:[(120, 140), (37, 40)]
计算次数:2
当前分类:{0=[(100, 100), (110, 120), (130, 160)], 1=[(1, 1), (10, 20)]}
当前中心点:[(113, 126), (5, 10)]

http://www.niftyadmin.cn/n/5347981.html

相关文章

HAL STM32基于系统滴答定时器(SysTick)实现多任务时间片轮询

HAL STM32基于系统滴答定时器&#xff08;SysTick&#xff09;实现多任务时间片轮询 &#x1f4d1;RTOS&#xff08;实时操作系统&#xff09;和定时器时间片轮询是两种不同的任务调度和执行方式的差异简介 &#x1f516; 以下部分内容&#xff0c;由AI给出的解答&#xff1a; …

[C++]使用纯opencv部署yolov8旋转框目标检测

【官方框架地址】 https://github.com/ultralytics/ultralytics 【算法介绍】 YOLOv8是一种先进的对象检测算法&#xff0c;它通过单个神经网络实现了快速的物体检测。其中&#xff0c;旋转框检测是YOLOv8的一项重要特性&#xff0c;它可以有效地检测出不同方向和角度的物体。…

中间件与rabbitmq

中间件是一种软件&#xff0c;用于在不同的应用程序、系统或服务之间提供通用功能和服务。它充当应用程序之间的桥梁&#xff0c;帮助它们相互通信和交换数据。中间件简化了复杂软件系统的开发和维护&#xff0c;使不同的系统组件能够更容易地协同工作。中间件的类型很多&#…

京东广告算法架构体系建设--在线模型系统分布式异构计算演变 | 京东零售广告技术团队

一、现状介绍 算法策略在广告行业中起着重要的作用&#xff0c;它可以帮助广告主和广告平台更好地理解用户行为和兴趣&#xff0c;从而优化广告投放策略&#xff0c;提高广告点击率和转化率。模型系统作为承载算法策略的载体&#xff0c;目前承载搜索、推荐、首焦、站外等众多广…

如何解决Flutter应用程序的兼容性问题

随着移动应用开发领域的不断发展&#xff0c;Flutter作为一种跨平台框架&#xff0c;受到了越来越多开发者的青睐。要确保Flutter应用程序能够在不同的设备和操作系统上稳定运行&#xff0c;并提供一致的用户体验&#xff0c;我们需要重视应用程序的兼容性问题。下面将简单的介…

HTML — 链接

一. 概述 HTML 使用超链接与网络上的另一个文档相连&#xff0c;可以实现点击即查看另一个文档的内容。HTML 中的链接允许用户在浏览网页时单击文本或图片来跳转到其他位置。 二. HTML 链接&#x1f517; —— 使用标签 HTML 中使用 <a></a> 标签来设置网页中的超…

[ruby on rails] concerns的使用

concern是用来把公共的方法提取到一起&#xff0c;保持代码DRY&#xff0c;是用module来实现的 model中的concern module Visibleextend ActiveSupport::ConcernVALID_STATUSES [public, private, archived] # 其他地方引用 Visible::VALID_STATUSES# 关联关系 blongs_to,…

.NET中的matplotlib平替,ScottPlot简单使用

文章目录 前言解决方案Python调用.NET 原生解决 ScottPlot找到文章ScottPlot Nuget安装简单代码测试代码跑不了5.0新版本测试 总结 前言 我之前在学OpenCV 三语言开发的时候&#xff0c;遇到了一个问题&#xff0c;怎么可视化的显示数据。Python有matplotlib&#xff0c;那么C…