詳解Java實(shí)現(xiàn)的k-means聚類算法
更新時(shí)間:2018年01月13日 15:46:25 作者:tianshl
這篇文章主要介紹了詳解Java實(shí)現(xiàn)的k-means聚類算法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
需求
對(duì)MySQL數(shù)據(jù)庫中某個(gè)表的某個(gè)字段執(zhí)行k-means算法,將處理后的數(shù)據(jù)寫入新表中。
源碼及驅(qū)動(dòng)
源碼
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; } /** * 重新計(jì)算質(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<>(); // 計(jì)算差 for(Double core: cores){ diffs.add(Math.abs(num - core)); } // 最小差 -> 索引 -> 對(duì)應(yīng)的質(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配置時(shí)的用戶名 String user = "root"; // MySQL配置時(shí)的密碼 String password = "root"; // 加載驅(qū)動(dòng) Class.forName("com.mysql.jdbc.Driver"); //聲明Connection對(duì)象 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; } /** * 關(guān)閉數(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));"); // 禁止自動(dòng)提交 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(); // 提交事務(wù) conn.commit(); // 關(guān)閉連接 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
運(yùn)行
# 指定依賴庫 java -Djava.ext.dirs=./lib Kmeans
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
解讀Spring事務(wù)是如何實(shí)現(xiàn)的
這篇文章主要介紹了Spring事務(wù)是如何實(shí)現(xiàn)的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-03-03簡(jiǎn)單了解spring cloud 網(wǎng)關(guān)服務(wù)
這篇文章主要介紹了簡(jiǎn)單了解spring cloud 網(wǎng)關(guān)服務(wù),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-10-10關(guān)于Lists.partition集合分組使用以及注意事項(xiàng)
這篇文章主要介紹了關(guān)于Lists.partition集合分組使用以及注意事項(xiàng),具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-01-01Springboot如何切換默認(rèn)的Tomcat容器
這篇文章主要介紹了Springboot如何切換默認(rèn)的Tomcat容器,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-06-06Spring?@Conditional注解示例詳細(xì)講解
@Conditional是Spring4新提供的注解,它的作用是按照一定的條件進(jìn)行判斷,滿足條件給容器注冊(cè)bean,這篇文章主要介紹了Spring?@Conditional注解示例詳細(xì)講解,需要的朋友可以參考下2022-11-11