日撸 Java 三百行day56-57

news2024/9/29 17:35:51

文章目录

  • day56-57 kMeans 聚类
    • 1.kMeans聚类理解
    • 2.代码理解
      • 2.1代码中变量的理解
      • 2.2代码理解

day56-57 kMeans 聚类

1.kMeans聚类理解

无监督的机器学习算法,其中k是划分为几个簇,并且选择k个数据作为不同簇的聚类中心,计算每个数据样本和聚类中心的距离(欧式距离或曼哈顿距离)并将数据样本分配给离聚类中心最近的类别。在遍历完所有数据后,则可以把数据集分成k个簇,对每个簇又要重新计算他的聚类中心(求平均值)。我们会进行多次迭代,直到聚类中心不变或者是到达一定次数的迭代。

2.代码理解

2.1代码中变量的理解

(主要是clustering()方法中的变量)

  • tempClusterArray
    当前循环中每个数据样本属于哪一个簇。如下值2=2代表数据样本2通过与k个聚类中心之间的计算,发现离2这个聚类中心距离最近,故将数据样本2聚类到1这个簇中。
    在这里插入图片描述
  • tempOldClusterArray
    用于存储旧的聚类分配结果的数组(可以理解为上一次迭代对数据聚类的结果)
    在这里插入图片描述- tempCenters
    存放聚类的中心。初始化时赋值为:对数据样本集随机排序,再随机选择数据集中的数据点作为初始聚类中心
    在这里插入图片描述
  • tempNewCenters
    对循环后分类后的不同簇重新选择聚类中心(求平均值)
    在这里插入图片描述

2.2代码理解

只要理解了KMeans的核心,代码分段读很好理解。

  • 1.选择簇的数量K(目前设置为3)、
  • 2.初始化聚类中心tempCenters(将数据集随机排序后选择前K个作为聚类中心)
  • 3.分配数据样本到簇(计算数据样本与聚类中心的距离,选择距离最短的)
  • 4.重新计算聚类中心(计算不同簇的平均值)
  • 5.重复步骤3,4(调出循环的条件是:tempOldClusterArray与tempClusterArray相等时 即上一次迭代和当前迭代聚类分配结果不再发生变化时)
package machinelearing.knn;

import weka.core.Instances;

import java.io.FileReader;
import java.util.Arrays;
import java.util.Random;

/**
 * @author: fulisha
 * @date: 2023-05-28 10:36
 * @description:
 */
public class KMeans {
    /**
     * Manhattan distance.
     */
    public static final int MANHATTAN = 0;


    /**
     * Euclidean distance.
     */
    public static final int EUCLIDEAN = 1;


    /**
     * The distance measure.
     */
    public int distanceMeasure = EUCLIDEAN;

    /**
     * A random instance;
     */
    public static final Random random = new Random();

    /**
     * The data.
     */
    Instances dataset;

    /**
     * The number of clusters.
     */
    int numClusters = 2;

    /**
     * The clusters.
     */
    int[][] clusters;


    /**
     * The first constructor.
     * @param paraFilename  The data filename.
     */
    public KMeans(String paraFilename) {
        dataset = null;
        try {
            FileReader fileReader = new FileReader(paraFilename);
            dataset = new Instances(fileReader);
            fileReader.close();
        } catch (Exception ee) {
            System.out.println("Cannot read the file: " + paraFilename + "\r\n" + ee);
            System.exit(0);
        }
    }

    public void setNumClusters(int paraNumClusters) {
        numClusters = paraNumClusters;
    }

    /**
     * Get a random indices for data randomization.
     * @param paraLength The length of the sequence.
     * @return  An array of indices, e.g., {4, 3, 1, 5, 0, 2} with length 6.
     */
    public static int[] getRandomIndices(int paraLength) {
        int[] resultIndices = new int[paraLength];

        // Step 1. Initialize.
        for (int i = 0; i < paraLength; i++) {
            resultIndices[i] = i;
        }

        // Step 2. Randomly swap.
        int tempFirst, tempSecond, tempValue;
        for (int i = 0; i < paraLength; i++) {
            // Generate two random indices.
            tempFirst = random.nextInt(paraLength);
            tempSecond = random.nextInt(paraLength);

            // Swap.
            tempValue = resultIndices[tempFirst];
            resultIndices[tempFirst] = resultIndices[tempSecond];
            resultIndices[tempSecond] = tempValue;
        }
        return resultIndices;
    }


    /**
     * The distance between two instances.
     * @param paraI The index of the first instance.
     * @param paraArray  The array representing a point in the space.
     * @return The distance.
     */
    public double distance(int paraI, double[] paraArray) {
        int resultDistance = 0;
        double tempDifference;
        switch (distanceMeasure) {
            case MANHATTAN:
                for (int i = 0; i < dataset.numAttributes() - 1; i++) {
                    tempDifference = dataset.instance(paraI).value(i) - paraArray[i];
                    if (tempDifference < 0) {
                        resultDistance -= tempDifference;
                    } else {
                        resultDistance += tempDifference;
                    }
                }
                break;
            case EUCLIDEAN:
                for (int i = 0; i < dataset.numAttributes() - 1; i++) {
                    tempDifference = dataset.instance(paraI).value(i) - paraArray[i];
                    resultDistance += tempDifference * tempDifference;
                }
                break;
            default:
                System.out.println("Unsupported distance measure: " + distanceMeasure);
        }

        return resultDistance;
    }


    public void clustering() {
        int[] tempOldClusterArray = new int[dataset.numInstances()];
        tempOldClusterArray[0] = -1;
        int[] tempClusterArray = new int[dataset.numInstances()];
        Arrays.fill(tempClusterArray, 0);
        double[][] tempCenters = new double[numClusters][dataset.numAttributes() - 1];

        // Step 1. Initialize centers.
        int[] tempRandomOrders = getRandomIndices(dataset.numInstances());
        for (int i = 0; i < numClusters; i++) {
            for (int j = 0; j < tempCenters[0].length; j++) {
                tempCenters[i][j] = dataset.instance(tempRandomOrders[i]).value(j);
            }
        }

        int[] tempClusterLengths = null;
        while (!Arrays.equals(tempOldClusterArray, tempClusterArray)) {
            System.out.println("New loop ...");
            tempOldClusterArray = tempClusterArray;
            tempClusterArray = new int[dataset.numInstances()];

            // Step 2.1 Minimization. Assign cluster to each instance.
            int tempNearestCenter;
            double tempNearestDistance;
            double tempDistance;

            for (int i = 0; i < dataset.numInstances(); i++) {
                tempNearestCenter = -1;
                tempNearestDistance = Double.MAX_VALUE;

                for (int j = 0; j < numClusters; j++) {
                    tempDistance = distance(i, tempCenters[j]);
                    if (tempNearestDistance > tempDistance) {
                        tempNearestDistance = tempDistance;
                        tempNearestCenter = j;
                    }
                }

                tempClusterArray[i] = tempNearestCenter;
            }

            // Step 2.2 Mean. Find new centers.
            tempClusterLengths = new int[numClusters];
            Arrays.fill(tempClusterLengths, 0);
            double[][] tempNewCenters = new double[numClusters][dataset.numAttributes() - 1];
            // Arrays.fill(tempNewCenters, 0);
            for (int i = 0; i < dataset.numInstances(); i++) {
                for (int j = 0; j < tempNewCenters[0].length; j++) {
                    tempNewCenters[tempClusterArray[i]][j] += dataset.instance(i).value(j);
                }
                tempClusterLengths[tempClusterArray[i]]++;
            }

            // Step 2.3 Now average
            for (int i = 0; i < tempNewCenters.length; i++) {
                for (int j = 0; j < tempNewCenters[0].length; j++) {
                    tempNewCenters[i][j] /= tempClusterLengths[i];
                }
            }

            System.out.println("Now the new centers are: " + Arrays.deepToString(tempNewCenters));
            tempCenters = tempNewCenters;
        }

        // Step 3. Form clusters.
        clusters = new int[numClusters][];
        int[] tempCounters = new int[numClusters];
        for (int i = 0; i < numClusters; i++) {
            clusters[i] = new int[tempClusterLengths[i]];
        }

        for (int i = 0; i < tempClusterArray.length; i++) {
            clusters[tempClusterArray[i]][tempCounters[tempClusterArray[i]]] = i;
            tempCounters[tempClusterArray[i]]++;
        }

        System.out.println("The clusters are: " + Arrays.deepToString(clusters));
    }


    public static void testClustering() {
        KMeans tempKMeans = new KMeans("C:/Users/王忠云/Desktop/sampledata/iris.arff");
        tempKMeans.setNumClusters(3);
        tempKMeans.clustering();
    }

    public static void main(String arags[]) {
        testClustering();
    }
}

  • 代码结果
    在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/586134.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

ASRT语音识别系统的部署以及模型的使用(运用篇)

ASRT语音识别系统的部署以及模型的使用(运用篇) 前言 ASRT是一个中文语音识别系统&#xff0c;由AI柠檬博主开源在GitHub上。 GitHub地址&#xff1a;ASRT_SpeechRecognition 国内Gitee镜像地址&#xff1a;ASRT_SpeechRecognition 文档地址&#xff1a;ASRT语音识别工具文…

Python打包成EXE

一、使用Pyinstaller pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pyinstaller 1.2Pyinstaller打包步骤 Pyinstaller -F -w -i apple.ico py_word.py 结果&#xff1a; 运行结果&#xff1a; 二、使用Auto-py-to-exe auto-py-to-exe 是一个用于打包 python 程序…

第二届(2023年)中国国际培育钻石产业发展与创新大会盛大召开!

5月25-26日&#xff0c;由广东省商务厅、中国国际贸易促进委员会广东省委员会&#xff08;广东国际商会&#xff09;、广州市商务局、番禺区人民政府、广东省交易控股集团有限公司/广东省公共资源交易中心指导&#xff0c;广州钻石交易中心&#xff08;简称广钻中心&#xff09…

C语言深度解析--指针

目录 指针 指针的定义&#xff1a; 指针的大小&#xff1a; 指针和指针类型 野指针 指针运算 指针-整数&#xff1a; 指针-指针&#xff1a; 指针的关系运算&#xff1a; 指针和数组 二级指针 指针数组 理解指针的第一步是在机器级上观察指针表示的内容。大多数现代…

第十六届全国大学生信息安全竞赛创新实践赛初赛部分WP AGCTF战队

持续两天的比赛&#xff0c;打的很累&#xff0c;web没有出太多的题&#xff0c;比赛被pwn师傅带飞了&#xff0c;希望下此加油&#xff0c;下边是此次比赛排名。 文章目录 MISC签到卡被加密的生产流量国粹调查问卷pyshell CRYPTO基于国密SM2算法的密钥密文分发可信度量Sign_i…

Java中的深拷贝和浅拷贝介绍

文章目录 基本类型和引用类型Clone方法浅拷贝深拷贝小结 在讲解什么是深拷贝和浅拷贝之前&#xff0c;我们先来了解一下什么是基本类型和引用类型。 基本类型和引用类型 基本类型也称为值类型&#xff0c;分别是字符类型 char&#xff0c;布尔类型 boolean以及数值类型 byte、…

Vue3 项目相关

vite 项目起步式 npm create vite - 1.命名项目名称- 2. 选择技术框架- 3. 进入项目文件夹 npm i 安装依赖&#xff0c;- 4. npm run dev 运行项目配置 package.json 文件 &#xff0c;使项目运行后自动再浏览器中打开。 在 dev 运行命令后添加一个 --open 即可。 "script…

微信小程序初识

微信小程序 因(ios&#xff0c;android)多平台彼此间并不互通&#xff0c;所以开发需要两个不同平台的开发团推队&#xff0c;所以微信小程序因此诞生。 小程序的优点 快速加载更强大的能力原生的体验易用且安全的微信数据开放高效和简单的开发 首先 根据自己的情况安装微…

弄懂软件测试左移和右移,靠它就行

软件测试技术应当贯穿整个软件开发生命周期、对软件产品&#xff08;包括阶段性产品&#xff09;进行验证和确认的活动过程&#xff0c;其核心目标是尽快尽早地发现软件产品中所存在的各种问题 bug—— 与用户需求、预先定义的不一致性。 传统的软件测试流程是 接到项目后参与…

cubemx stm32 pca9685pw模块 16路PWM 可用于舵机驱动 驱动代码

资料 淘宝链接请点这里 淘宝资料资料&#xff1a; 链接&#xff1a;https://pan.baidu.com/s/1Kda-c7QdZdQ03FBMa0zeRA 提取码&#xff1a;1234 pca9685pw介绍 这个模块是 I2C 通信控制 16 路 PWM 的模块。 所有路的 频率 是统一设置的&#xff0c;所以每一路的频率都一样&a…

java单元测试( Hamcrest 断言)

java单元测试( Hamcrest 断言) 单元测试特征: 1 范围狭窄 2 限于单一类或方法 3 体积小 为什么要编写单元测试&#xff1f; 为了防止错误&#xff08;很明显&#xff01;&#xff09; 而且还可以提高开发人员的生产力&#xff0c;因为单元测试&#xff1a; (1) 帮助实施——在…

网工内推 | 经验不限,国企招网工,IE认证优先,五险一金

01 一九零五&#xff08;北京&#xff09;网络科技有限公司 &#x1f537;招聘岗位&#xff1a;网络工程师 &#x1f537;职责描述&#xff1a; 1、负责公司内部现有网络配置及调优&#xff1b; 2、负责IT机房的网络和安全的日常维护工作&#xff1b; 3、负责IT机房的紧急故…

轻松掌握redis缓存穿透、击穿、雪崩问题及解决方案(20230529版)

1、缓存穿透 所谓缓存穿透就是非法传输了一个在数据库中不存在的条件&#xff0c;导致查询redis和数据库中都没有&#xff0c;并且有大量的请求进来&#xff0c;就会导致对数据库产生压力&#xff0c;解决这一问题的方法如下&#xff1a; 1、使用空缓存解决 对查询到值是空的…

【Python开发】FastAPI 02:请求参数—路径参数、查询参数

进行接口请求时&#xff0c;请求参数是重中之重了&#xff01;请求参数指客户端向服务端发送请求时&#xff0c;需要传递给服务端的参数&#xff0c;包括路径参数、查询参数、请求体等。举个例子&#xff0c;如果客户端想要获取某个用户的信息&#xff0c;可以向服务端发送一个…

PHPMySQL基础(一):创建数据库并通过PHP进行连接

PHP同样可以对数据库进行连接&#xff0c;并且实现增删改查、登录注册等功能&#xff0c;这一篇写一下怎么使用PHP去连接MySQL数据库 目录 一、创建数据库 1.1 登录页面 1.2 创建数据库 1.3 创建数据库表 1.4 添加表字段 1.5 插入数据 1.6 导出和导入 二、PHP连接数据…

华为OD机试真题B卷 Java 实现【报文重排序】,附详细解题思路

一、题目描述 对报文进行重传和重排序是常用的可靠性机制&#xff0c;重传缓冲区内有一定数量的子报文&#xff0c;每个子报文在原始报文中的顺序已知&#xff0c;现在需要恢复出原始报文。 二、输入描述 输入第一行为N&#xff0c;表示子报文的个数&#xff0c;0 < N &l…

SpringBoot 配置文件和日志文件

目录 一、SpringBoot配置文件 配置文件的格式 .properties配置文件格式 .yml配置文件格式 .properties 与 .yml的区别 配置文件的读取 .properties 与 .yml的区别 设置不同环境的配置⽂件 二、SpringBoot日志文件 日志打印的步骤 得到日志对象 方法一&#xff1a;使…

vulnhub靶场之RAGNAR LOTHBROK: 1

1.信息收集 探测存活主机&#xff0c;输入&#xff1a;netdiscover -r 192.168.239.0/24 &#xff0c;发现192.168.239.178存活。 对目标主机192.168.239.178进行端口扫描&#xff0c;发现存活21(ftp)、80、443、3306端口。 浏览器访问http://192.168.239.178&#xff0c;发…

设计模式 - 代理模式

基本介绍: 代理模式&#xff1a;为一个对象提供一个替身&#xff0c;以控制对这个对象的访问。即通过代理 对象访问目标对象.这样做的好处是:可以在目标对象实现的基础上,增强额外的 功能操作,即扩展目标对象的功能。被代理的对象可以是远程对象、创建开销大的对象或需要安全控…

chatgpt赋能python:Python三次方根的用途和计算方法

Python三次方根的用途和计算方法 如果您是一位Python编程工程师&#xff0c;您可能会经常需要用到Python的数学计算功能。在这篇文章中&#xff0c;我们将探讨Python三次方根的概念和使用&#xff0c;以及如何在Python中计算三次方根。 什么是三次方根&#xff1f; 三次方根…