詳解Java實現(xiàn)的k-means聚類算法
更新時間:2018年01月13日 15:46:25 作者:tianshl
這篇文章主要介紹了詳解Java實現(xiàn)的k-means聚類算法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
需求
對MySQL數(shù)據(jù)庫中某個表的某個字段執(zhí)行k-means算法,將處理后的數(shù)據(jù)寫入新表中。
源碼及驅(qū)動
源碼
import java.sql.*;
import java.util.*;
/**
* @author tianshl
* @version 2018/1/13 上午11:13
*/
public class Kmeans {
// 源數(shù)據(jù)
private List<Integer> origins = new ArrayList<>();
// 分組數(shù)據(jù)
private Map<Double, List<Integer>> grouped;
// 初始質(zhì)心列表
private List<Double> cores;
// 數(shù)據(jù)源
private String tableName;
private String colName;
/**
* 構(gòu)造方法
*
* @param tableName 源數(shù)據(jù)表名稱
* @param colName 源數(shù)據(jù)列名稱
* @param cores 質(zhì)心列表
*/
private Kmeans(String tableName, String colName,List<Double> cores){
this.cores = cores;
this.tableName = tableName;
this.colName = colName;
}
/**
* 重新計算質(zhì)心
*
* @return 新的質(zhì)心列表
*/
private List<Double> newCores(){
List<Double> newCores = new ArrayList<>();
for(List<Integer> v: grouped.values()){
newCores.add(v.stream().reduce(0, (sum, num) -> sum + num) / (v.size() + 0.0));
}
Collections.sort(newCores);
return newCores;
}
/**
* 判斷是否結(jié)束
*
* @return bool
*/
private Boolean isOver(){
List<Double> _cores = newCores();
for(int i=0, len=cores.size(); i<len; i++){
if(!cores.get(i).toString().equals(_cores.get(i).toString())){
// 使用新質(zhì)心
cores = _cores;
return false;
}
}
return true;
}
/**
* 數(shù)據(jù)分組
*/
private void setGrouped(){
grouped = new HashMap<>();
Double core;
for (Integer origin: origins) {
core = getCore(origin);
if (!grouped.containsKey(core)) {
grouped.put(core, new ArrayList<>());
}
grouped.get(core).add(origin);
}
}
/**
* 選擇質(zhì)心
*
* @param num 要分組的數(shù)據(jù)
* @return 質(zhì)心
*/
private Double getCore(Integer num){
// 差 列表
List<Double> diffs = new ArrayList<>();
// 計算差
for(Double core: cores){
diffs.add(Math.abs(num - core));
}
// 最小差 -> 索引 -> 對應的質(zhì)心
return cores.get(diffs.indexOf(Collections.min(diffs)));
}
/**
* 建立數(shù)據(jù)庫連接
* @return connection
*/
private Connection getConn(){
try {
// URL指向要訪問的數(shù)據(jù)庫名mydata
String url = "jdbc:mysql://localhost:3306/data_analysis_dev";
// MySQL配置時的用戶名
String user = "root";
// MySQL配置時的密碼
String password = "root";
// 加載驅(qū)動
Class.forName("com.mysql.jdbc.Driver");
//聲明Connection對象
Connection conn = DriverManager.getConnection(url, user, password);
if(conn.isClosed()){
System.out.println("連接數(shù)據(jù)庫失敗!");
return null;
}
System.out.println("連接數(shù)據(jù)庫成功!");
return conn;
} catch (Exception e) {
System.out.println("連接數(shù)據(jù)庫失??!");
e.printStackTrace();
}
return null;
}
/**
* 關閉數(shù)據(jù)庫連接
*
* @param conn 連接
*/
private void close(Connection conn){
try {
if(conn != null && !conn.isClosed()) conn.close();
} catch (Exception e){
e.printStackTrace();
}
}
/**
* 獲取源數(shù)據(jù)
*/
private void getOrigins(){
Connection conn = null;
try {
conn = getConn();
if(conn == null) return;
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery(String.format("select %s from %s", colName, tableName));
while(rs.next()){
origins.add(rs.getInt(1));
}
conn.close();
} catch (Exception e){
e.printStackTrace();
} finally {
close(conn);
}
}
/**
* 向新表中寫數(shù)據(jù)
*/
private void write(){
Connection conn = null;
try {
conn = getConn();
if(conn == null) return;
// 創(chuàng)建表
Statement statement = conn.createStatement();
// 刪除舊數(shù)據(jù)表
statement.execute("DROP TABLE IF EXISTS k_means; ");
// 創(chuàng)建新表
statement.execute("CREATE TABLE IF NOT EXISTS k_means(`core` DECIMAL(11, 7), `col` INTEGER(11));");
// 禁止自動提交
conn.setAutoCommit(false);
PreparedStatement ps = conn.prepareStatement("INSERT INTO k_means VALUES (?, ?)");
for(Map.Entry<Double, List<Integer>> entry: grouped.entrySet()){
Double core = entry.getKey();
for(Integer value: entry.getValue()){
ps.setDouble(1, core);
ps.setInt(2, value);
ps.addBatch();
}
}
// 批量執(zhí)行
ps.executeBatch();
// 提交事務
conn.commit();
// 關閉連接
conn.close();
} catch (Exception e){
e.printStackTrace();
} finally {
close(conn);
}
}
/**
* 處理數(shù)據(jù)
*/
private void run(){
System.out.println("獲取源數(shù)據(jù)");
// 獲取源數(shù)據(jù)
getOrigins();
// 停止分組
Boolean isOver = false;
System.out.println("數(shù)據(jù)分組處理");
while(!isOver) {
// 數(shù)據(jù)分組
setGrouped();
// 判斷是否停止分組
isOver = isOver();
}
System.out.println("將處理好的數(shù)據(jù)寫入數(shù)據(jù)庫");
// 將分組數(shù)據(jù)寫入新表
write();
System.out.println("寫數(shù)據(jù)完畢");
}
public static void main(String[] args){
List<Double> cores = new ArrayList<>();
cores.add(260.0);
cores.add(600.0);
// 表名, 列名, 質(zhì)心列表
new Kmeans("attributes", "attr_length", cores).run();
}
}
源文件
Kmeans.java
編譯
javac Kmeans.java
運行
# 指定依賴庫 java -Djava.ext.dirs=./lib Kmeans
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

