hadoop下kmeans算法实现四

本文详细介绍了在Hadoop环境下实现KMeans聚类算法的过程,主要讲解了核心类KMapper的实现细节,包括数据读取、中心点初始化、距离计算以及簇分配等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

KMapper.java

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URI;
import java.util.StringTokenizer;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;


public class KMapper extends Mapper<LongWritable, Text, Text, Text> {
    
    private String[] center;
    //读取3.txt中更新的中心点坐标,并将坐标存入center数组中
    protected void setup(Context context) throws IOException,InterruptedException  //read centerlist, and save to center[]
    {
        String centerlist = "hdfs://localhost:9000/home/administrator/hadoop/kmeans/input2/3.txt"; //center文件
        Configuration conf1 = new Configuration();
        conf1.set("hadoop.job.ugi", "hadoop-user,hadoop-user");
       FileSystem fs = FileSystem.get(URI.create(centerlist),conf1);
       FSDataInputStream in = null;
       ByteArrayOutputStream out = new ByteArrayOutputStream();
       try{
             
           in = fs.open( new Path(centerlist) );
           IOUtils.copyBytes(in,out,100,false);  
           center = out.toString().split(" ");
           }finally{
                IOUtils.closeStream(in);
            }
    }
    //从hadoop接收的数据在2.txt中保存
    public void map(LongWritable key,Text value,Context context) throws IOException,InterruptedException
    {
        StringTokenizer itr = new StringTokenizer(value.toString());
        //从2.txt读入数据,以空格为分割符,一个一个处理
        while(itr.hasMoreTokens
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值