K-means 聚类算法 Reducer 实现 - Java 代码示例
该代码是 K-means 聚类算法的 Reducer 部分实现。其主要功能是将同一类别的数据元素进行求和并计算出新的中心点,然后将新的中心点存储起来。具体实现过程如下:
-
传入的 key 为数据元素所属的类别索引,values 为该类别下的所有数据元素。
-
遍历 values 列表,将其中的每个数据元素分解为一个 ArrayList
,然后将这些元素相加,得到一个新的 ArrayList ,这个新的 ArrayList 就是新的中心点。 -
调用 CalUtil 类中的 calCenter() 方法,计算新的中心点。
-
将新的中心点存储起来,调用 context.write() 方法,将新的中心点以 Text 类型的形式输出。输出的 key 为一个空的 Text 对象,value 为新的中心点的 ArrayList
转换成的字符串。 -
重复以上步骤,直到所有类别的数据元素都被处理完毕。
总体来说,这段代码的作用是将同一类别的数据元素进行求和并计算新的中心点,以便后续使用这个新的中心点进行下一轮迭代。
package com.huiluczP.cluster;
import com.huiluczP.util.CalUtil;
import com.huiluczP.util.DataUtil;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
import java.io.IOException;
import java.util.ArrayList;
// reduce,主要思路是把同一key,也就是同index的元素相加算新的中心点
public class KmeansReducer extends Reducer<Text, Text, Text, Text> {
@Override
protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
ArrayList<Double> sumElement = new ArrayList<Double>();
int num = 0;
// 遍历values相加,求新中心点
for(Text t:values){
num += 1;
ArrayList<Double> element = DataUtil.splitStringIntoArray(t.toString());
if(sumElement.size() <= 0){
sumElement = new ArrayList<Double>(element);
continue;
}
CalUtil.addElement(sumElement, element);
}
CalUtil.calCenter(num, sumElement);
// 存放新中心点
context.write(new Text(""), new Text(DataUtil.convertArrayIntoString(sumElement)));
}
}
原文地址: http://www.cveoy.top/t/topic/oGEW 著作权归作者所有。请勿转载和采集!