日撸java_day56-57

news2024/10/1 19:24:42

文章目录

  • day56-57kMeans 聚类
  • 代码
  • 运行截图

day56-57kMeans 聚类

1.kMeans 聚类需要中心点收敛时结束.
2.数据集为 iris, 所以最后一个属性没使用. 如果对于没有决策属性的数据集, 需要进行相应修改.
3.数据没有归一化.
4.getRandomIndices() 和 knn 的完全相同, 拷贝过来. 本来应该写在 SimpleTools.java 里面的, 代码不多, 为保证独立性就放这里了.
5.distance() 和 knn 的相似, 注意不要用决策属性, 而且参数不同. 第 2 个参数为实数向量, 这是类为中心可能为虚拟的, 而中心点那里并没有对象.
6.获得虚拟中心后, 换成与其最近的点作为实际中心, 再聚类.(写了两个clustering方法,注释掉一个,第二个实现此功能)

代码

package machineLearning.kmeans;

import weka.core.Instances;

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

/**
 * ClassName: KMeans
 * Package: machineLearning.kmeans
 * Description: kMeans clustering.
 *
 * @Author: luv_x_c
 * @Create: 2023/7/31 12:29
 */
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);
        }// OF try
    }// OF the first constructor

    /**
     * A setter.
     */
    public void setNumClusters(int paraNumClusters) {
        numClusters = paraNumClusters;
    }// Of the setter

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

        // Step1. Initialize.
        for (int i = 0; i < pratLength; i++) {
            resultIndices[i] = i;
        }// Of for i

        // Step2. Randomly swap.
        for (int i = 0; i < pratLength; i++) {
            // Generate two random indices.
            int tempFirst = RANDOM.nextInt(pratLength);
            int tempSecond = RANDOM.nextInt(pratLength);

            //Swap.
            int tempValue = resultIndices[tempFirst];
            resultIndices[tempFirst] = resultIndices[tempSecond];
            resultIndices[tempSecond] = tempValue;
        }// OF for i

        return resultIndices;
    }// OF getRandomIndices

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

        return resultDistance;
    }// Of distance

    /**
     * Clustering.
     */
//    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];
//
//        // Step1. 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);
//            }// OF for j
//        }// Of for i
//
//        int[] tempClusterLengths = null;
//        while (!Arrays.equals(tempOldClusterArray, tempClusterArray)) {
//            System.out.println("New loop ...");
//            tempOldClusterArray = tempClusterArray;
//            tempClusterArray = new int[dataset.numInstances()];
//
//            // Step2.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;
//                    }// Of if
//                }// OF  for j
//                tempClusterArray[i] = tempNearestCenter;
//            }// of for i
//
//            // Step2.2. Mean. Find new centers.
//            tempClusterLengths = new int[numClusters];
//            Arrays.fill(tempClusterLengths, 0);
//            double[][] tempNewCenters = new double[numClusters][dataset.numAttributes() - 1];
//            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);
//                }// OF for j
//                tempClusterLengths[tempClusterArray[i]]++;
//            }// Of for i
//
//            // Step2.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];
//                }// Of for j
//            }// Of for i
//
//            System.out.println("Now the centers are: " + Arrays.deepToString(tempNewCenters));
//            tempCenters = tempNewCenters;
//        }// Of while
//
//        //Step3. Form clusters.
//        clusters = new int[numClusters][];
//        int[] tempCounters = new int[numClusters];
//        for (int i = 0; i < numClusters; i++) {
//            clusters[i] = new int[tempClusterLengths[i]];
//        }// Of for i
//
//        for (int i = 0; i < tempClusterArray.length; i++) {
//            clusters[tempClusterArray[i]][tempCounters[tempClusterArray[i]]] = i;
//            tempCounters[tempClusterArray[i]]++;
//        }//  of fot i
//
//        System.out.println("The clusters are:   " + Arrays.deepToString(clusters));
//    }// Of clustering
    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];

        // Step1. 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);
            }// OF for j
        }// Of for i

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

            // Step2.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;
                    }// Of if
                }// OF  for j
                tempClusterArray[i] = tempNearestCenter;
            }// of for i

            // Step2.2. Mean. Find new centers.
            tempClusterLengths = new int[numClusters];
            Arrays.fill(tempClusterLengths, 0);
            double[][] tempNewCenters = new double[numClusters][dataset.numAttributes() - 1];
            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);
                }// OF for j
                tempClusterLengths[tempClusterArray[i]]++;
            }// Of for i

            // Step2.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];
                }// Of for j
            }// Of for i

//            System.out.println("Now the centers are: " + Arrays.deepToString(tempNewCenters));
            tempCenters = tempNewCenters;
            // 新增部分:虚拟中心替换为实际中心
            int[] nearestCenters = new int[numClusters]; // 用于存储每个虚拟中心最近的实际中心的索引
            for (int i = 0; i < numClusters; i++) {
                double minDistance = Double.MAX_VALUE;
                int nearestCenterIndex = -1;
                for (int j = 0; j < dataset.numInstances(); j++) {
                    double distanceToCenter = distance(j, tempCenters[i]);
                    if (distanceToCenter < minDistance) {
                        minDistance = distanceToCenter;
                        nearestCenterIndex = j;
                    }
                }
                nearestCenters[i] = nearestCenterIndex;
            }

             // 替换虚拟中心为实际中心
            for (int i = 0; i < numClusters; i++) {
                for (int j = 0; j < tempCenters[0].length; j++) {
                    tempCenters[i][j] = dataset.instance(nearestCenters[i]).value(j);
                }
            }
            System.out.println("Now the centers are: " + Arrays.deepToString(tempCenters));
        }// Of while

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

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

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

    /**
     * A test unit.
     */
    public static void testClustering() {
        KMeans tempKmeans = new KMeans("E:\\java_code\\data\\sampledata\\iris.arff");
        tempKmeans.setNumClusters(3);
        tempKmeans.clustering();
    }// Of testClustering

    /**
     * The entrance of the program.
     *
     * @param args NOt used now.
     */
    public static void main(String[] args) {
        testClustering();

    }// Of main
}// Of class KMeans

运行截图

在这里插入图片描述

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

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

相关文章

markdown语法速记

markdown语法速记 这里只记录兼容性强的语法格式&#xff1a; [markdown官方文档]https://markdown.com.cn 标题 #号后跟一个空格如&#xff1a;“# title_level_1” 代表一级标题&#xff0c;两个#号代表二级标题&#xff0c;以此类推&#xff1b;最小为6级标题换行 直接…

两数相加 II

给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。 你可以假设除了数字 0 之外&#xff0c;这两个数字都不会以零开头。 示例1&#xff1a; 输入&#xff1a;l1 [7,2,4,3], l2 [5,6,4] 输…

【ASP.NET MVC】使用动软(五)(13)

一、问题 前文完成的用户登录后的首页如下&#xff1a; 后续账单管理、人员管理等功能页面都有相同的头部&#xff0c;左边和下边&#xff0c;唯一不同的右边内容部分&#xff0c;所以要解决重复设计的问题。 二、解决方法——使用布局页 在Views上右键添加新建项&#xff…

鸿蒙4.0发布会说了啥?关注个性与效率,小艺智能程度令人惊艳

鸿蒙4.0系统的发布会已经结束&#xff0c;整个发布会看下来&#xff0c;给我最深刻的印象就是——鸿蒙4.0是一个让手机更接近个人终端的系统。但选择系统难免掺杂个人喜好和偏见&#xff0c;因此本文我只会从鸿蒙4.0那些让我感到惊喜的功能入手介绍&#xff0c;不对系统进行评价…

【深度学习Week4】MobileNet_ShuffleNet

报错&#xff1a;unsafe legacy renegotiation disabled 解决方案&#xff1a; 尝试了更换cryptography36.0.2版本&#xff0c;以及更换下载链接的方法&#xff0c;都不行&#xff0c;最后采用了手动下载mat文件并上传到colab的方法 高光谱图像分类数据集简介Indian Pines&…

免疫疗法勘察兵——DC细胞

DC细胞又叫树状细胞或者树突细胞&#xff0c;1869年由保罗兰格尔翰斯发现&#xff0c;一开始被误以为是神经细胞的一种&#xff0c;直到1973年皮肤科医师Inga Silberberg发现了他的免疫功能&#xff0c;同年&#xff0c;被拉尔夫斯坦曼和赞威尔A科恩两人正式命名为“dendritic…

《凤凰架构》第一章——演进中的部分

前言 刚开始决定弄懂文中所提到的所有东西&#xff0c;就像我写ByteByteGo呢几篇文章一样&#xff0c;把每一句话都弄懂。但是对于《凤凰架构》来说&#xff0c;这有点太费时间了&#xff0c;并且没有必要&#xff0c;有些东西可能永远都不会用到&#xff0c;但文章为了全面的…

【基础类】—CSS盒模型的全面认识

一、基本概念&#xff1a;标准IE模型 盒模型&#xff1a;margin border padding content 标准模型&#xff1a;将元素的宽度和高度仅计算为内容区域的尺寸&#xff08;content-box&#xff0c;默认&#xff09; 当CSS盒模型为 标准盒模型 &#xff08;box-sizing: conten…

【安全测试】安全测试威胁建模设计方法STRIDE

目录 背景 TM(ThreatModeling) 实践 具体流程 资料获取方法 背景 目前安全测试一般都存在如下问题&#xff1a; 安全测试人员不懂业务&#xff0c;业务测试人员不懂安全&#xff0c;安全测试设计出现遗漏是无法避免的安全测试点繁多复杂&#xff0c;单点分析会导致风险暴…

商城-学习整理-基础-商品服务API-品牌管理(六)

目录 一、使用逆向工程生成前后端代码1、新增品牌管理菜单2、使用生成的前端代码 二、优化逆向生成的品牌管理页面1、显示状态开关优化2、品牌上传优化&#xff08;使用阿里云存储&#xff09;1&#xff09;阿里云对象存储-普通上传方式2&#xff09;阿里云对象存储-服务端签名…

paddlenlp:社交网络中多模态虚假媒体内容核查(代码篇)

初赛之baseline解读篇 一、模型框架图1、框架解读2、评价指标解读 二、代码功能1、数据集加载2、模型定义3、模型训练4、模型预测 三、写在最后 一、模型框架图 1、框架解读 第一列是输入&#xff0c;一部分是文本&#xff08;需核查文本、文本证据材料&#xff09;&#xff…

ExtJs 7.7.0 下载方法与去除trial水印

背景 最近发现Sencha ExtJs发布了ExtJs7.7.0版本&#xff0c;立刻下载了SDK包&#xff0c;许多朋友不知如何下载&#xff0c;如何去除右上角的trial水印。本文讲下相关下载技巧与方法。 下载SDK 首先需要申请试用&#xff0c;申请地址如下&#xff0c;需要注意可能需要梯子&…

好烦!快让ChatGPT停止道歉!SD创作宣传图的超细教程;教你在PH冷启动薅流量;CSDN举办AI应用创新大赛 | ShowMeAI日报

&#x1f440;日报&周刊合集 | &#x1f3a1;生产力工具与行业应用大全 | &#x1f9e1; 点赞关注评论拜托啦&#xff01; &#x1f916; Stable Diffusion 图生图入门&#xff0c;一份详细的思维导图 &#x1f916; DeeCamp X CSDN 举办AI应用创新大赛&#xff0c;万元奖金…

【C++】继承的基本特性(定义,赋值转换,友元,静态成员,虚拟继承,默认成员函数,作用域)

文章目录 一、继承的定义1.定义格式2.继承基类成员访问方式的变化 二、基类和派生类对象赋值转换三、继承的作用域1. 在继承体系中基类和派生类都有独立的作用域。2.子类和父类中有同名成员3.成员函数的隐藏4.注意在实际中在继承体系里面最好不要定义同名的成员。 四、派生类的…

【C语言学习】整数类型表达数的范围

一、整数类型表达数的范围 1.char类型 char 是1个字节 &#xff0c;即00000000 ~ 11111111&#xff0c;一般情况默认是有符号char(signed char) ,此时char所能表达的数就是 -128 ~ 127&#xff0c;即 -2 ^ n-1 ~ (2 ^ n-1)-1 ,其中n是位数或比特位&#xff08;1字节8位8比特&…

OPENCV C++(四)形态学操作+连通域统计

形态学操作 先得到一个卷积核 Mat kernel getStructuringElement(MORPH_RECT,Size(5,5)); 第一个是形状 第二个是卷积核大小 依次为腐蚀 膨胀 开运算 闭运算 Mat erodemat,dilatemat,openmat,closemat;morphologyEx(result1, erodemat, MORPH_ERODE, kernel);morphologyEx…

万界星空科技/免费开源MES系统/免费仓库管理

仓库管理&#xff08;仓储管理&#xff09;&#xff0c;指对仓库及仓库内部的物资进行收发、结存等有效控制和管理&#xff0c;确保仓储货物的完好无损&#xff0c;保证生产经营活动的正常进行&#xff0c;在此基础上对货物进行分类记录&#xff0c;通过报表分析展示仓库状态、…

道本科技受邀参加建筑产业互联网推动建筑产业现代化体系构建座谈会,以数字化产品为建筑行业注入新动能!

2023年7月底&#xff0c;道本科技作为中国建筑业协会合作伙伴&#xff0c;受邀参加了建筑产业互联网推动建筑产业现代化体系构建座谈会。在这次座谈会上&#xff0c;道本科技旗下产品“合规数”“合同智能审查”和“智合同范本库”被中国建筑&#xff08;中小企业&#xff09;产…

Leaflet.Control.Opacity 控制图层的透明度

最新有一个需求&#xff0c;能动态的控制Leaflet.js 地图图层的透明度&#xff0c;官网文档: https://leafletjs.com/reference.html#gridlayer-setopacity 一直有个setOpacity方法&#xff0c;我以为拿来就能使呢&#xff0c;其实不行。后来找到一个日本人开发的demo: 右侧Co…

部署SpringBoot项目在服务器上,并通过swagger登录

1.项目编译打包 2.上传jar包到服务器并启动 xftp将打包好后的jar包传到虚拟机指定路径 java -jar执行该jar包 3.通过swagger登录 输入后点击下面的执行按钮 会得到一个tocken 4.将tocken放到postman的Headers中 5.修改url 例如我本地测试是http://localhost:8080/接口名&am…