K-Means 聚类算法实现:基于 Hadoop 的主函数代码

该代码为 K-Means 算法的主函数,通过命令行参数获取数据集名称和聚类数,然后定义随机中心点、新中心点、数据集和聚类结果的路径。接着调用 CenterRandomAdapter 类生成随机中心点,然后进行 K-Means 算法循环,每次循环调用 KmeansAdapter 类的 start 方法进行计算,并判断是否需要停机。最后调用 KmeansAdapter 类的 createClusterResult 方法生成聚类结果。

package com.huiluczP;

import com.huiluczP.center.CenterRandomAdapter;
import com.huiluczP.cluster.KmeansAdapter;
import com.huiluczP.util.DataUtil;
import org.apache.hadoop.conf.Configuration;

import java.io.IOException;

// kmeans主方法
// 主要就是循环调用直到次数或者停机状态
// 每次循环判断下停机
// data为逗号连接
public class KmeansRun {
    public static void main(String[] args){
        // 命令行参数为数据集名称与聚类数
        String dataName = args[0];
        int k = Integer.parseInt(args[1]);
        System.out.println(k);

        String centerPath = DataUtil.HDFS_OUTPUT + '/centers.txt';
        String newCenterPath = DataUtil.HDFS_OUTPUT + '/new_centers.txt';
        String dataPath = DataUtil.HDFS_INPUT + '/' + dataName;
        String clusterResultPath = DataUtil.HDFS_OUTPUT + '/kmeans_cluster_result.txt';

        // 初始化随机中心点
        CenterRandomAdapter.createRandomCenter(dataPath, centerPath, k);
        // 默认1000次,中途停退出
        for(int i=0;i<30;i++){
            System.out.println('round ' + i);
            KmeansAdapter.start(dataPath, centerPath, newCenterPath);
            if(KmeansAdapter.checkStop(centerPath, newCenterPath)) {
                break;
            }
        }
        KmeansAdapter.createClusterResult(dataPath, centerPath, clusterResultPath);
    }
}

代码功能:

  1. 获取参数: 从命令行参数中获取数据集名称和聚类数 k。
  2. 定义路径: 定义随机中心点、新中心点、数据集和聚类结果的路径。
  3. 初始化随机中心点: 调用 CenterRandomAdapter.createRandomCenter() 方法生成随机中心点。
  4. K-Means 算法循环:
    • 循环调用 KmeansAdapter.start() 方法进行计算,计算新的中心点。
    • 调用 KmeansAdapter.checkStop() 方法判断是否需要停止循环。
  5. 生成聚类结果: 调用 KmeansAdapter.createClusterResult() 方法生成聚类结果。

原文地址: http://www.cveoy.top/t/topic/oGFt 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录