数据挖掘—K-Means算法(Java实现)

算法描述

(1)任意选择k个数据对象作为初始聚类中心
(2)根据簇中对象的平均值,将每个对象赋给最类似的簇
(3)更新簇的平均值,即计算每个对象簇中对象的平均值
(4)计算聚类准则函数E
(5)重复2-4步骤,直到准则函数E值不再进行变化

代码


public class Cluster {public String clusterName; // 类簇名private Medoid medoid; // 类簇的质点private ArrayList<DataPoint> dataPoints; // 类簇中各样本点public Cluster(String clusterName) {this.clusterName = clusterName;this.medoid = null; // will be set by calling setCentroid()dataPoints = new ArrayList<DataPoint>();}public void setMedoid(Medoid c) {medoid = c;}public Medoid getMedoid() {return medoid;}public void addDataPoint(DataPoint dp) { // called from CAInstancedp.setCluster(this);// 标注该类簇属于某点,计算欧式距离this.dataPoints.add(dp);}public void removeDataPoint(DataPoint dp) {this.dataPoints.remove(dp);}public int getNumDataPoints() {return this.dataPoints.size();}public DataPoint getDataPoint(int pos) {return (DataPoint) this.dataPoints.get(pos);}public String getName() {return this.clusterName;}public ArrayList<DataPoint> getDataPoints() {return this.dataPoints;}
}

public class ClusterAnalysis {public Cluster[] clusters;// 所有类簇private int miter;// 迭代次数private ArrayList<DataPoint> dataPoints = new ArrayList<DataPoint>();// 所有样本点private int dimNum;//维度public ClusterAnalysis(int k, int iter, ArrayList<DataPoint> dataPoints,int dimNum) {clusters = new Cluster[k];// 类簇种类数for (int i = 0; i < k; i++) {clusters[i] = new Cluster(i+"");}this.miter = iter;this.dataPoints = dataPoints;this.dimNum=dimNum;}public int getIterations() {return miter;}public ArrayList<DataPoint>[] getClusterOutput() {ArrayList<DataPoint> v[] = new ArrayList[clusters.length];for (int i = 0; i < clusters.length; i++) {v[i] = clusters[i].getDataPoints();}return v;}public void startAnalysis(double[][] medoids) {setInitialMedoids(medoids);double[][] newMedoids=medoids;double[][] oldMedoids=new double[medoids.length][this.dimNum];while(!isEqual(oldMedoids,newMedoids)){for(int m = 0; m < clusters.length; m++){//每次迭代开始情况各类簇的点clusters[m].getDataPoints().clear();}for (int j = 0; j < dataPoints.size(); j++) {int clusterIndex=0;double minDistance=Double.MAX_VALUE;for (int k = 0; k < clusters.length; k++) {//判断样本点属于哪个类簇double eucDistance=dataPoints.get(j).testEuclideanDistance(clusters[k].getMedoid());if(eucDistance<minDistance){minDistance=eucDistance;clusterIndex=k;}}//将该样本点添加到该类簇clusters[clusterIndex].addDataPoint(dataPoints.get(j));}for(int m = 0; m < clusters.length; m++){clusters[m].getMedoid().calcMedoid();//重新计算各类簇的质点}for(int i=0;i<medoids.length;i++){for(int j=0;j<this.dimNum;j++){oldMedoids[i][j]=newMedoids[i][j];}}for(int n=0;n<clusters.length;n++){newMedoids[n]=clusters[n].getMedoid().getDimensioin();}this.miter++;}}private void setInitialMedoids(double[][] medoids) {for (int n = 0; n < clusters.length; n++) {Medoid medoid = new Medoid(medoids[n]);clusters[n].setMedoid(medoid);medoid.setCluster(clusters[n]);}}private boolean isEqual(double[][] oldMedoids,double[][] newMedoids){boolean flag=false;for(int i=0;i<oldMedoids.length;i++){for(int j=0;j<oldMedoids[i].length;j++){if(oldMedoids[i][j]!=newMedoids[i][j]){return flag;}}}flag=true;return flag;}
}

public class DataPoint {private double dimension[]; //样本点的维度private String pointName; //样本点名字private Cluster cluster; //类簇private double euDt;//样本点到质点的距离public DataPoint(double dimension[], String pointName) {this.dimension = dimension;this.pointName = pointName;this.cluster = null;}@Overridepublic String toString() {String result = "Point_id=" + pointName + "  [";for (int i = 0; i < dimension.length; i++) {result += String.format("%.2f",dimension[i]) + " ";}return result.trim()+"] clusterId: "+cluster.clusterName;}public void setCluster(Cluster cluster) {this.cluster = cluster;}public double calEuclideanDistanceSum() {double sum=0.0;Cluster cluster=this.getCluster();ArrayList<DataPoint> dataPoints=cluster.getDataPoints();for(int i=0;i<dataPoints.size();i++){double[] dims=dataPoints.get(i).getDimensioin();for(int j=0;j<dims.length;j++){double temp=Math.pow((dims[j]-this.dimension[j]),2);sum=sum+temp;}}return Math.sqrt(sum);}public double testEuclideanDistance(Medoid c) {double sum=0.0;double[] cDim=c.getDimensioin();for(int i=0;i<dimension.length;i++){double temp=Math.pow((dimension[i]-cDim[i]),2);sum=sum+temp;}return Math.sqrt(sum);}public double[] getDimensioin() {return this.dimension;}public Cluster getCluster() {return this.cluster;}public double getCurrentEuDt() {return this.euDt;}public String getPointName() {return this.pointName;}
}
public class Medoid{private double dimension[]; // 质点的维度private Cluster cluster; //所属类簇private double etdDisSum;//Medoid到本类簇中所有的欧式距离之和public String toString() {String result ="  [";DecimalFormat decimalFormat=new DecimalFormat("0.000000");for (int i = 0; i < dimension.length; i++) {result += decimalFormat.format(dimension[i]) + " ";}return result.trim()+"] clusterId: "+cluster.clusterName;}public Medoid(double dimension[]) {this.dimension = dimension;}public void setCluster(Cluster c) {this.cluster = c;}public double[] getDimensioin() {return this.dimension;}public Cluster getCluster() {return this.cluster;}public void calcMedoid() {// 取代价最小的点calcEtdDisSum();double minEucDisSum = this.etdDisSum;ArrayList<DataPoint> dps = this.cluster.getDataPoints();for (int i = 0; i < dps.size(); i++) {double tempeucDisSum = dps.get(i).calEuclideanDistanceSum();if (tempeucDisSum < minEucDisSum) {dimension = dps.get(i).getDimensioin();minEucDisSum=tempeucDisSum;}}}// 计算该Medoid到同类簇所有样本点的欧斯距离和private void calcEtdDisSum() {double sum=0.0;Cluster cluster=this.getCluster();ArrayList<DataPoint> dataPoints=cluster.getDataPoints();for(int i=0;i<dataPoints.size();i++){double[] dims=dataPoints.get(i).getDimensioin();for(int j=0;j<dims.length;j++){double temp=Math.abs(dims[j]-this.dimension[j]);sum=sum+temp;}}etdDisSum= sum;}
}

public class TestMain {public static List<double[]> readTxt(String fileName){List<double[]> list=new ArrayList<>();try {File filename = new File(fileName); // 读取input.txt文件InputStreamReader reader = new InputStreamReader(new FileInputStream(filename)); // 建立一个输入流对象readerBufferedReader br = new BufferedReader(reader);String line = "";line = br.readLine();while (true) {line = br.readLine();if(line==null) break;String[] temp=line.split(",");double[] c=new double[temp.length];for(int i=0;i<temp.length;i++){c[i]=Float.parseFloat(temp[i]);}list.add(c);}} catch (Exception e) {e.printStackTrace();}return list;}public static void writeTxt(String content){try { // 防止文件建立或读取失败,用catch捕捉错误并打印,也可以throw/* 读入TXT文件 */File writename = new File("src/km/output.txt"); // 相对路径,如果没有则要建立一个新的output。txt文件BufferedWriter out = new BufferedWriter(new FileWriter(writename));out.write(content); // \r\n即为换行out.flush(); // 把缓存区内容压入文件out.close(); // 最后记得关闭文件} catch (Exception e) {e.printStackTrace();}}public static void main (String args[]){ArrayList<DataPoint> dataPoints = new ArrayList<DataPoint>();List<double[]> list=readTxt("src/km/t2.txt");for(int i=0;i<list.size();i++){dataPoints.add(new DataPoint(list.get(i),String.valueOf(i)));}long s=System.currentTimeMillis();ClusterAnalysis ca=new ClusterAnalysis(5,200,dataPoints,5);double[][] cen={list.get(22),list.get(3),list.get(45),list.get(156),list.get(96)};ca.startAnalysis(cen);StringBuilder stringBuilder=new StringBuilder();ArrayList<DataPoint>[] v = ca.getClusterOutput();System.out.println("K-中心点聚类算法运行时间"+(System.currentTimeMillis()-s)+"ms");for (int ii=0; ii<v.length; ii++){ArrayList tempV = v[ii];stringBuilder.append("\n").append("-----------Cluster").append(ii).append("---------").append("\n");stringBuilder.append("Mid_Point:  ").append(ca.clusters[ii].getMedoid()).append("  Points_num:  "+ca.clusters[ii].getDataPoints().size()).append("\n");System.out.println(ca.clusters[ii].getMedoid()+"  Points_num:  "+ca.clusters[ii].getDataPoints().size());Iterator iter = tempV.iterator();while(iter.hasNext()){DataPoint dpTemp = (DataPoint)iter.next();stringBuilder.append(dpTemp).append("\n");}}writeTxt(stringBuilder.toString());}}

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

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

相关文章

自我价值感缺失的表现_不同类型的缺失价值观和应对方法

自我价值感缺失的表现Before handling the missing values, we must know what all possible types of it exists in the data science world. Basically there are 3 types to be found everywhere on the web, but in some of the core research papers there is one more ty…

[收藏转载]C# GDI+ 简单绘图(一)

最近对GDI这个东西接触的比较多&#xff0c;也做了些简单的实例&#xff0c;比如绘图板&#xff0c;仿QQ截图等&#xff0e; 废话不多说了&#xff0c;我们先来认识一下这个GDI&#xff0c;看看它到底长什么样. GDI&#xff1a;Graphics Device Interface Plus也就是图形设备接…

mybaties总结+hibernate总结

一、对原生态jdbc程序中问题总结 1.1 jdbc程序 需求&#xff1a;使用jdbc查询mysql数据库中用户表的记录 statement:向数据库中发送一个sql语句 预编译statement&#xff1a;好处&#xff1a;提高数据库性能。 预编译statement向数据库中发送一个sql语句&#xff0c;数据库编译…

客户旅程_我如何充分利用freeCodeCamp的旅程

客户旅程by Catherine Vassant (aka Codingk8)由凯瑟琳瓦森(Catherine Vassant)(又名Codingk8) 我如何充分利用freeCodeCamp的旅程 (How I made the most out of my freeCodeCamp journey) 我的路线图&#xff1f; ️超越课程范围的reeCodeCamp (My road map ?️ to freeCode…

Python14 函数

函数 面向对象编程&#xff1a; 类----class 面向过程编程&#xff1a;过程---def 函数式编程&#xff1a;函数---def def test(x):描述x 1return x#def是定义函数的关键字#test是函数名称#&#xff08;x&#xff09;是参数#x1是 函数体&#xff0c;是一段逻辑代码#return 定义…

学习sql注入:猜测数据库_面向数据科学家SQL:学习简单方法

学习sql注入:猜测数据库We don’t pick a hammer and look for nails — that would be an unusual way of solving problems. The usual way of doing business is to identify the problem first, then look for appropriate tools.我们不用锤子找钉子&#xff0c;那是解决问…

android 百度地图3.0,android 百度地图3.0

一&#xff1a;为地图设置事件注意新版本中要有一个getMapmMapView.getMap().setOnMapStatusChangeListener(listener);OnMapStatusChangeListener listener newOnMapStatusChangeListener() {/*** 手势操作地图&#xff0c;设置地图状态等操作导致地图状态开始改变。* param s…

(摘录)sockaddr与sockaddr_in,sockaddr_un结构体详细讲解

struct sockaddr { unsigned short sa_family; /* address family, AF_xxx */ char sa_data[14]; /* 14 bytes of protocol address */ }; sa_family是地址家族&#xff0c;一般都是“AF_xxx”的形式。好像通常大多用的是都是AF_INET。 sa_data是14字节协议…

数据挖掘—K-中心点聚类算法(Java实现)

K-中心点聚类算法 &#xff08;1&#xff09;任意选择k个对象作为初始的簇中心点 &#xff08;2&#xff09;指派每个剩余对象给离他最近的中心点所表示的簇 &#xff08;3&#xff09;选择一个未被选择的中心点直到所有的中心点都被选择过 &#xff08;4&#xff09;选择一个…

使用akka构建高并发程序_如何使用Akka Cluster创建简单的应用程序

使用akka构建高并发程序If you read my previous story about Scalachain, you probably noticed that it is far from being a distributed system. It lacks all the features to properly work with other nodes. Add to it that a blockchain composed by a single node is…

pandas之数值计算与统计

数值计算与统计 对于DataFrame来说&#xff0c;求和、最大、最小、平均等统计方法&#xff0c;默认是按列进行统计&#xff0c;即axis 0&#xff0c;如果添加参数axis 1则会按照行进行统计。 如果存在空值&#xff0c;在统计时默认会忽略空值&#xff0c;如果添加参数skipna …

python自动化数据报告_如何:使用Python将实时数据自动化到您的网站

python自动化数据报告This tutorial will be helpful for people who have a website that hosts live data on a cloud service but are unsure how to completely automate the updating of the live data so the website becomes hassle free. For example: I host a websit…

一颗站在技术边缘的土豆

2012年开始上专业课&#xff0c;2013年打了一年游戏&#xff0c;年底专业课忘光了&#xff0c;但是蒙混过关没挂科&#xff0c;2014年7月份毕业&#xff0c;对这个社会充满向往。2014年9月份——方正代理商做网络安全公司。2015年3月份跳槽到一家vmware代理商公司。2016年6月&a…

leetcode 839. 相似字符串组(并查集)

如果交换字符串 X 中的两个不同位置的字母&#xff0c;使得它和字符串 Y 相等&#xff0c;那么称 X 和 Y 两个字符串相似。如果这两个字符串本身是相等的&#xff0c;那它们也是相似的。 例如&#xff0c;“tars” 和 “rats” 是相似的 (交换 0 与 2 的位置)&#xff1b; “r…

android intent参数是上次的结果,【Android】7.0 Intent向下一个活动传递数据、返回数据给上一个活动...

1.0 可以利用Intent吧数据传递给上一个活动&#xff0c;新建一个叫“hellotest01”的项目。新建活动FirstActivity&#xff0c;勾选“Generate Layout File”和“Launcher Activity”。image修改AndroidMainifest.xml中的内容&#xff1a;android:name".FirstActivity&quo…

实习一年算工作一年吗?_经过一年的努力,我如何找到软件工程工作

实习一年算工作一年吗?by Andrew Ngo通过安德鲁恩戈 经过一年的努力&#xff0c;我如何找到软件工程工作 (How I landed a software engineering job after a year of hard work) Many of us think the path to becoming a software engineer requires years of education an…

学习深度学习需要哪些知识_您想了解的有关深度学习的所有知识

学习深度学习需要哪些知识有关深层学习的FAU讲义 (FAU LECTURE NOTES ON DEEP LEARNING) Corona was a huge challenge for many of us and affected our lives in a variety of ways. I have been teaching a class on Deep Learning at Friedrich-Alexander-University Erlan…

参加开发竞赛遇到的问题【总结】

等比赛完就写。 转载于:https://www.cnblogs.com/jiangyuanjia/p/11261978.html

html5--3.16 button元素

html5--3.16 button元素 学习要点 掌握button元素的使用button元素 用来建立一个按钮从功能上来说&#xff0c;与input元素建立的按钮相同button元素是双标签&#xff0c;其内部可以配置图片与文字&#xff0c;进行更复杂的样式设计不仅可以在表单中使用&#xff0c;还可以在其…

如何注册鸿蒙id,鸿蒙系统真机调试证书 和 设备ID获取

鸿蒙系统真机调试创建项目创建项目创建应用创建鸿蒙应用(注意&#xff0c;测试阶段需要发邮件申请即可)关联应用项目进入关联 添加引用准备调试使用的 p12 和证书请求 csr使用以下命令// 别名"test"可以修改&#xff0c;但必须前后一致&#xff0c;密码请自行修改key…