Java Implementation K-means Clustering

Source: Internet
Author: User

Reprint Please specify source: http://blog.csdn.net/xiaojimanman/article/details/51086879

Http://www.llwjy.com/blogdetail/bf27dd0be964886d11185743779e40e0.html

Personal Blog Station has been online, the website www.llwjy.com ~ welcome you to vomit Groove ~

-------------------------------------------------------------------------------------------------

Before beginning to play a small ad, you create a QQ group: 321903218, click on the link to join the group "Lucene case Development", mainly used to communicate how to use Lucene to create a site search backstage, but also irregular in the group open the relevant public classes, Interested children's shoes can be added to the exchange.


The KNN classification algorithm has been introduced in the previous blog post, which will focus on the next K-means clustering algorithm. K-means algorithm is a classical clustering algorithm, the basic idea of the algorithm is to select K points (random) as the center of the cluster, and then the results of the cluster to calculate the centroid of the class, through iterative method to update the centroid continuously, until the centroid is unchanged or slightly moved, the final cluster result is the final cluster result. The following first describes the next K-means specific algorithm steps.


K-means algorithm

In the preceding has been about the introduction of the next K-means, the following describes the specific algorithm description:

1) Select K points as the initial centroid;

2) Each sample is computed to the similarity or distance of K centroid, and the sample is divided into the class of centroid with the highest similarity or shortest distance.

3) for the cluster results, the centroid of each class is calculated, and the new centroid is the centroid of the next round.

4) determine whether the algorithm satisfies the termination condition, satisfies the end condition, otherwise continues the 2nd, 3, 4 steps.

Before introducing the algorithm, we first look at the K-means algorithm clustering plane 200,000 points into 34 categories of results (such as)



Algorithm implementation

The whole idea of K-means clustering algorithm is relatively simple, and the following steps introduce how to implement the K-means algorithm in Java.


First, K-means algorithm basic properties

In the K-means algorithm, there are several important indicators, such as the K value, the maximum number of iterations, for these indicators, we uniformly set them as the properties of the class, as follows:

Private List<t> dataarray;//The original value to be classified private int K = 3;//will be divided into the number of categories private int maxclustertimes = 500;//Maximum number of iterations private L Ist<list<t>> clusterlist;//Clustering Results private list<t> clusteringcentert;//centroid


Ii. selection of the initial centroid

The results of the K-means clustering algorithm receive a large degree of initial centroid selection, in order to ensure that there is sufficient randomness, for the selection of the initial centroid here, a completely random method is used to randomly disrupt the data to be classified, then the first k samples as the initial centroid (through multiple iterations, will reduce the initial centroid effect).

list<t> Centert = new arraylist<t> (size);//Disrupt Data collections.shuffle (DataArray); for (int i = 0; i < size; i++) {Centert.add (Dataarray.get (i));}


three or one wheel cluster

      in the K-means algorithm, most of the time is a round of clustering, the specific function is very simple, is to calculate each sample and all the centroid of the similarity or distance, to find the most similar to the sample centroid or distance nearest centroid, The sample is then divided into the class, and the specific logic describes the comments in the reference code.

private void Clustering (list<t> precenter, int times) {if (Precenter = = NULL | | precenter.size () < 2) {return;} Disrupting the order of centroid Collections.shuffle (Precenter); list<list<t>> clusterlist = Getlistt (Precenter.size ()); for (T O1:this.dataArray) {//search for the most similar centroid int max = 0;dou ble maxscore = Similarscore (O1, Precenter.get (0)); for (int i = 1; i < precenter.size (); i++) {if (Maxscore < similar Score (O1, Precenter.get (i))) {Maxscore = Similarscore (O1, Precenter.get (i)); max = i;}} Clusterlist.get (max). Add (O1);} Calculates the centroid of each category of this cluster result list<t> Nowcenter = new arraylist<t> (); for (list<t> list:clusterlist) { Nowcenter.add (Getcentert (list));} Whether the maximum number of iterations is reached if (Times >= this.maxclustertimes | | precenter.size () < this. K) {this.clusterlist = Clusterlist;return;} This.clusteringcentert = nowcenter;//Determines whether the centroid is moving, if not moved, ends the cluster, otherwise the next round if (Iscenterchange (Precenter, Nowcenter)) { Clear (clusterlist); Clustering (Nowcenter, times + 1);} else {this.clusterlist = clusterlist;}}


Iv. Whether the center of mass moves

In the third step, an important step is mentioned: after each round of clustering, the centroid is recalculated and the centroid is computed for movement. For the calculation of the new centroid, the similarity between samples and the ability to determine whether the two samples are equal, these functions are defined as abstract methods for subclasses to implement because they do not know the specific data types of the samples. Here's how to tell if the centroid has moved.

Private Boolean Iscenterchange (list<t> PreT, list<t> NowT) {if (PreT = = NULL | | nowT = NULL) {return false;} for (t T1:pret) {Boolean bol = true;for (t t2:nowt) {if (Equals (t1, T2)) {//t1 has equal in T2, the centroid is considered not moved Bol = False;break;}} There is a centroid movement that requires the next calculation if (BOL) {return bol;}} return false;}

From the above code can be seen, the idea of the algorithm is for the front and back of the two centroid array of the previous set of Centroid is in the next Centroid group appears, one does not appear, it is believed that the centroid has changed.


Full code

The above four steps have fully introduced the K-means algorithm of the specific algorithm ideas, the following look at the complete code implementation.

 /** * @Description: K-means cluster * * Package COM.LULEI.DATAMINING.KNN;  Import Java.util.arraylist;import Java.util.collections;import java.util.List; Public abstract class Kmeansclustering <t>{private list<t> dataarray;//The original value to be classified private int K = 3;// The number of classes to be divided private int maxclustertimes = 500;//Maximum iterations private list<list<t>> clusterlist;//clustering result private List <T> clusteringcentert;//centroid public int getk () {return K;} public void setk (int k) {if (K < 1) {throw new IllegalArgumentException ("K must greater than 0");} This. k = k;} public int Getmaxclustertimes () {return maxclustertimes;} public void setmaxclustertimes (int maxclustertimes) {if (Maxclustertimes <) {throw new IllegalArgumentException (" Maxclustertimes must greater than 10 ");} This.maxclustertimes = Maxclustertimes;} Public list<t> Getclusteringcentert () {return clusteringcentert;} /** * @return * @Author: Lulei * @Description: Clustering The data */public list<list<t>> Clustering () {if (DataArray = =NULL) {return null;} The initial k points are the first K points in the array of int size = k > dataarray.size ()? Dataarray.size (): K;  list<t> Centert = new arraylist<t> (size);//Disrupt Data collections.shuffle (DataArray); for (int i = 0; i < size; i++) {Centert.add (Dataarray.get (i));} Clustering (Centert, 0); return clusterlist;} /** * @param precenter * @param times * @Author: Lulei * @Description: Round cluster */private void Clustering (list<t> prece nter, int times) {if (Precenter = = NULL | | precenter.size () < 2) {return;} Disrupting the order of centroid Collections.shuffle (Precenter); list<list<t>> clusterlist = Getlistt (Precenter.size ()); for (T O1:this.dataArray) {//search for the most similar centroid int max = 0;dou ble maxscore = Similarscore (O1, Precenter.get (0)); for (int i = 1; i < precenter.size (); i++) {if (Maxscore < similar Score (O1, Precenter.get (i))) {Maxscore = Similarscore (O1, Precenter.get (i)); max = i;}} Clusterlist.get (max). Add (O1);} Calculate the centroid of each category of this cluster result list<t> Nowcenter = new arraylist<t> (); for (list<t> List:clusterlisT) {Nowcenter.add (Getcentert (list));} Whether the maximum number of iterations is reached if (Times >= this.maxclustertimes | | precenter.size () < this. K) {this.clusterlist = Clusterlist;return;} This.clusteringcentert = nowcenter;//Determines whether the centroid is moving, if not moved, ends the cluster, otherwise the next round if (Iscenterchange (Precenter, Nowcenter)) { Clear (clusterlist); Clustering (Nowcenter, times + 1);} else {this.clusterlist = clusterlist;}} /** * @param size * @return * @Author: Lulei * @Description: Initialize a cluster result */private list<list<t>> getlistt (int s ize) {list<list<t>> List = new arraylist<list<t>> (size), for (int i = 0; i < size; i++) {List.ad D (New arraylist<t> ());} return list;} /** * @param lists * @Author: Lulei * @Description: emptying useless array */private void clear (List<list<t>> lists) {for (Li St<t> list:lists) {list.clear ();} Lists.clear ();} /** * @param value * @Author: Lulei * @Description: Add a record to the model */public void AddRecord (T value) {if (DataArray = = null) {DA Taarray = new arraylist<t> ();} Dataarray.add (value);} /** * @param preT * @param nowT * @return * @Author: Lulei * @Description: Determine if the centroid is moving */private boolean iscenterchange (Li St<t> PreT, list<t> NowT) {if (PreT = = NULL | | nowT = NULL) {return false;} for (t T1:pret) {Boolean bol = true;for (t t2:nowt) {if (Equals (t1, T2)) {//t1 has equal in T2, the centroid is considered not moved Bol = False;break;}} There is a centroid movement that requires the next calculation if (BOL) {return bol;}} return false;} /** * @param O1 * @param o2 * @return * @Author: Lulei * @Description: O1 o2 the similarity between */public abstract double Similarscore ( T O1, T O2);/** * @param O1 * @param o2 * @return * @Author: Lulei * @Description: Determine if O1 O2 is equal */public abstract Boolean Equals (t O1, T O2);/** * @param list * @return * @Author: Lulei * @Description: Find the centroid of a set of data */public abstract T Getcentert (L Ist<t> list);}


Realization of two-dimensional clustering

In the algorithm description, introduced a 200,000 points into 34 categories, the following for two-dimensional coordinate data implementation of its specific subclasses.


First, the similarity degree

For the similarity of the two-dimensional coordinates, here we take the opposite number of clusters of two points, the concrete implementation is as follows:

@Overridepublic Double Similarscore (Xybean O1, Xybean O2) {Double distance = math.sqrt ((O1.getx ()-O2.GETX ()) * (O1.getx ( )-O2.getx ()) + (O1.gety ()-o2.gety ()) * (O1.gety ()-o2.gety ())); return distance *-1;}


Second, the sample/centroid is equal

To determine whether the sample/centroid is equal only need to determine whether the coordinates of two points are equal, the concrete implementation is as follows:

@Overridepublic Boolean equals (Xybean O1, Xybean O2) {return o1.getx () = = O2.getx () && o1.gety () = = O2.gety ();}


third, obtain a new centroid under a classification

For two-dimensional coordinate data, you can use the center of gravity of all points as the centroid of the classification, as follows:

@Overridepublic Xybean Getcentert (list<xybean> List) {int x = 0;int y = 0;try {for (Xybean xy:list) {x + = Xy.getx ( ); y + = Xy.gety ();} x = X/list.size (); y = Y/list.size ();} catch (Exception e) {}return new Xybean (x, y);}


Iv. Main Method

For the specific two-dimensional coordinates of the source code is no longer posted here, is to implement the above-described abstract class, and implementation of the 3 abstract methods, the following we randomly generated 200,000 points, and then clustered into 34 categories, the specific code is as follows:

public static void Main (string[] args) {int width = 600;int height = 400;int K = 34; Xycluster xycluster = new Xycluster (); for (int i = 0; i < 200000; i++) {int x = (int) (Math.random () * width) + 1;int y = (int) (Math.random () * height) + 1;xycluster.addrecord (new Xybean (x, y));} XYCLUSTER.SETK (K); Long a = System.currenttimemillis (); list<list<xybean>> Cresult = xycluster.clustering (); List<xybean> Center = Xycluster.getclusteringcentert (); SYSTEM.OUT.PRINTLN (Jsonutil.parsejson (center)); Long B = System.currenttimemillis (); SYSTEM.OUT.PRINTLN ("Time Consuming:" + (B-A) + "MS"), new Imgutil (). Drawxybeans (width, height, cresult, "D:/2.png", 0, 0);}


For this randomly generated 200,000 points into 34 classes, the total time spent 5485ms. (Computer Configuration: i5 + 8G memory)


-------------------------------------------------------------------------------------------------
Small welfare
-------------------------------------------------------------------------------------------------
Individual at the Geek College, "Lucene case development" course has been launched, welcome everyone to spit Groove ~

First lesson: Lucene Overview

Lesson Two: Introduction to Lucene common functions

Lesson Three: web crawler

Lesson Four: Database connection pooling

Lesson Five: Collection of novel websites

Lesson Six: The operation of the novel website database

The seventh lesson: the realization of the novel Web site's distributed crawler

Eighth lesson: Lucene Real-time search

Lesson Nineth: The underlying operation of the index


Java Implementation K-means Clustering

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.