使用MapReduce实现Bayes算法

2024-06-20 18:18

本文主要是介绍使用MapReduce实现Bayes算法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

代码如下:

NBayes.conf

4 cl1 cl2 cl3 cl4
3 p1 12 p2 16 p3 17

NBayes.train

cl1 5 6 7
cl2 3 8 4
cl1 2 5 2
cl3 7 8 7
cl4 3 8 2
cl4 9 2 7
cl2 1 8 5
cl5 2 9 4
cl3 10 3 4
cl1 4 5 6
cl3 4 6 7

NBayes.test

1 5 6 7
2 1 8 5
3 2 9 4
4 10 3 4
5 4 5 6
6 3 8 4
7 2 5 2
8 7 8 7
9 3 8 2
10 9 2 7
11 4 6 7

package naivebayes;


import java.util.ArrayList;


public class NaiveBayesConf {
public int dimen;
public int class_num;
public ArrayList<String> classNames;
public ArrayList<String> proNames;
public ArrayList<Integer> proRanges;


public NaiveBayesConf() {
dimen = class_num = 0;
classNames = new ArrayList<String>();
proNames = new ArrayList<String>();
proRanges = new ArrayList<Integer>();
}


public void ReadNaiveBayesConf(String file, Configuration conf)
throws Exception {
Path conf_path = new Path(file);
FileSystem hdfs = conf_path.getFileSystem(conf);
FSDataInputStream fsdt = hdfs.open(conf_path);
Scanner scan = new Scanner(fsdt);
String str = scan.nextLine();
String[] vals = str.split(" ");


class_num = Integer.parseInt(vals[0]);


int i;


for (i = 1; i < vals.length; i++) {
classNames.add(vals[i]);
}


str = scan.nextLine();
vals = str.split(" ");
dimen = Integer.parseInt(vals[0]);


for (i = 1; i < vals.length; i += 2) {
proNames.add(vals[i]);
proRanges.add(new Integer(vals[i + 1]));
}
fsdt.close();
scan.close();
}
}

package naivebayes;


import org.apache.hadoop.conf.Configuration;


public class NaiveBayesMain {
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
String[] otherArgs = new GenericOptionsParser(conf, args)
.getRemainingArgs();
FileSystem fs = FileSystem.get(conf);
Path path_train, path_temp, path_test, path_out;
if (otherArgs.length != 5) {
System.err
.println("Usage: NaiveBayesMain <dfs_path> <conf> <train> <test> <out>");
System.exit(2);
}


conf.set("conf", otherArgs[0] + "/" + otherArgs[1]);
conf.set("train", otherArgs[0] + "/" + otherArgs[2]);
conf.set("test", otherArgs[0] + "/" + otherArgs[3]);
conf.set("output", otherArgs[0] + "/" + otherArgs[4]);


put2HDFS(otherArgs[1], otherArgs[0] + "/" + otherArgs[1], conf);
put2HDFS(otherArgs[2], otherArgs[0] + "/" + otherArgs[2], conf);
put2HDFS(otherArgs[3], otherArgs[0] + "/" + otherArgs[3], conf);


path_train = new Path(otherArgs[0] + "/" + otherArgs[2]);
path_temp = new Path(otherArgs[0] + "/" + otherArgs[2] + ".train1");
path_test = new Path(otherArgs[0] + "/" + otherArgs[3]);
path_out = new Path(otherArgs[0] + "/" + otherArgs[4]);


{
Job job_train = new Job(conf, "naive bayse training");
job_train.setJarByClass(NaiveBayesMain.class);
job_train.setMapperClass(NaiveBayesTrain.TrainMapper.class);
job_train.setCombinerClass(NaiveBayesTrain.TrainReducer.class);
job_train.setReducerClass(NaiveBayesTrain.TrainReducer.class);
job_train.setOutputKeyClass(Text.class);
job_train.setOutputValueClass(IntWritable.class);


FileInputFormat.setInputPaths(job_train, path_train);
if (fs.exists(path_temp))
fs.delete(path_temp, true);
FileOutputFormat.setOutputPath(job_train, path_temp);
if (job_train.waitForCompletion(true) == false)
System.exit(1);


conf.set("train_result", otherArgs[0] + "/" + otherArgs[2]
+ ".train1");
}
{
Job job_test = new Job(conf, "naive bayse testing");
job_test.setJarByClass(NaiveBayesTest.class);
job_test.setMapperClass(NaiveBayesTest.TestMapper.class);
job_test.setOutputKeyClass(Text.class);
job_test.setOutputValueClass(Text.class);


FileInputFormat.setInputPaths(job_test, path_test);
if (fs.exists(path_out))
fs.delete(path_out, true);
FileOutputFormat.setOutputPath(job_test, path_out);
if (job_test.waitForCompletion(true) == false)
System.exit(1);
fs.delete(path_temp, true);
}


// getFromHDFS(otherArgs[0] + "/" + otherArgs[4], ".", conf);


fs.close();
System.exit(0);
}


public static void put2HDFS(String src, String dst, Configuration conf)
throws Exception {
Path dstPath = new Path(dst);
FileSystem hdfs = dstPath.getFileSystem(conf);


hdfs.copyFromLocalFile(false, true, new Path(src), new Path(dst));


}


public static void getFromHDFS(String src, String dst, Configuration conf)
throws Exception {
Path dstPath = new Path(dst);
FileSystem lfs = dstPath.getFileSystem(conf);
String temp[] = src.split("/");
Path ptemp = new Path(temp[temp.length - 1]);
if (lfs.exists(ptemp))
;
lfs.delete(ptemp, true);
lfs.copyToLocalFile(true, new Path(src), dstPath);


}
}

package naivebayes;


import java.util.Scanner;


public class NaiveBayesTrain {
public static class TrainMapper extends
Mapper<Object, Text, Text, IntWritable> {
public NaiveBayesConf nBConf;
private final static IntWritable one = new IntWritable(1);
private Text word;


public void setup(Context context) {
try {
nBConf = new NaiveBayesConf();
Configuration conf = context.getConfiguration();
nBConf.ReadNaiveBayesConf(conf.get("conf"), conf);
} catch (Exception ex) {
ex.printStackTrace();
System.exit(1);
}
System.out.println("setup");
}


public void map(Object key, Text value, Context context)
throws IOException, InterruptedException {
Scanner scan = new Scanner(value.toString());
String str, vals[], temp;
int i;
word = new Text();
while (scan.hasNextLine()) {
str = scan.nextLine();
vals = str.split(" ");
word.set(vals[0]);
context.write(word, one);
for (i = 1; i < vals.length; i++) {
word = new Text();
temp = vals[0] + "#" + nBConf.proNames.get(i - 1);
temp += "#" + vals[i];
word.set(temp);
context.write(word, one);
}
}
}
}


public static class TrainReducer extends
Reducer<Text, IntWritable, Text, IntWritable> {
private IntWritable result = new IntWritable();


public void reduce(Text key, Iterable<IntWritable> values,
Context context) throws IOException, InterruptedException {
int sum = 0;
for (IntWritable val : values) {
sum += val.get();
}
result.set(sum);
context.write(key, result);
}
}
}


package naivebayes;


import java.io.BufferedReader;


public class NaiveBayesTrainData {
public HashMap<String, Integer> freq;


public NaiveBayesTrainData() {
freq = new HashMap<String, Integer>();
}


public void getData(String file, Configuration conf) throws IOException {
int i;
Path data_path = new Path(file);
Path file_path;
String temp[], line;
FileSystem hdfs = data_path.getFileSystem(conf);
FileStatus[] status = hdfs.listStatus(data_path);


for (i = 0; i < status.length; i++) {
file_path = status[i].getPath();
if (hdfs.getFileStatus(file_path).isDir() == true)
continue;
line = file_path.toString();
temp = line.split("/");
if (temp[temp.length - 1].substring(0, 5).equals("part-") == false)
continue;
System.err.println(line);
FSDataInputStream fin = hdfs.open(file_path);
InputStreamReader inr = new InputStreamReader(fin);
BufferedReader bfr = new BufferedReader(inr);
while ((line = bfr.readLine()) != null) {
String res[] = line.split("\t");
freq.put(res[0], new Integer(res[1]));
System.out.println(line);
}
bfr.close();
inr.close();
fin.close();
}
}


}


package naivebayes;


import java.util.Scanner;


public class NaiveBayesTest {
public static class TestMapper extends Mapper<Object, Text, Text, Text> {
public NaiveBayesConf nBConf;
public NaiveBayesTrainData nBTData;


public void setup(Context context) {
try {
Configuration conf = context.getConfiguration();


nBConf = new NaiveBayesConf();
nBConf.ReadNaiveBayesConf(conf.get("conf"), conf);
nBTData = new NaiveBayesTrainData();
nBTData.getData(conf.get("train_result"), conf);
} catch (Exception ex) {
ex.printStackTrace();
System.exit(1);
}
}


public void map(Object key, Text value, Context context)
throws IOException, InterruptedException {
Scanner scan = new Scanner(value.toString());
String str, vals[], temp;
int i, j, k, fxyi, fyi, fyij, maxf, idx;
Text id;
Text cls;


while (scan.hasNextLine()) {
str = scan.nextLine();
vals = str.split(" ");
maxf = -100;
idx = -1;
for (i = 0; i < nBConf.class_num; i++) {
fxyi = 1;
String cl = nBConf.classNames.get(i);
Integer integer = nBTData.freq.get(cl);
if (integer == null)
fyi = 0;
else
fyi = integer.intValue();
for (j = 1; j < vals.length; j++) {
temp = cl + "#" + nBConf.proNames.get(j - 1) + "#"
+ vals[j];


integer = nBTData.freq.get(temp);
if (integer == null)
fyij = 0;
else
fyij = integer.intValue();
fxyi = fxyi * fyij;
}
if (fyi * fxyi > maxf) {
maxf = fyi * fxyi;
idx = i;
}
}
id = new Text(vals[0]);
cls = new Text(nBConf.classNames.get(idx));
context.write(id, cls);
}
}
}
}

这篇关于使用MapReduce实现Bayes算法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1078892

相关文章

使用Python实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

Python实现微信自动锁定工具

《Python实现微信自动锁定工具》在数字化办公时代,微信已成为职场沟通的重要工具,但临时离开时忘记锁屏可能导致敏感信息泄露,下面我们就来看看如何使用Python打造一个微信自动锁定工具吧... 目录引言:当微信隐私遇到自动化守护效果展示核心功能全景图技术亮点深度解析1. 无操作检测引擎2. 微信路径智能获

使用Java将各种数据写入Excel表格的操作示例

《使用Java将各种数据写入Excel表格的操作示例》在数据处理与管理领域,Excel凭借其强大的功能和广泛的应用,成为了数据存储与展示的重要工具,在Java开发过程中,常常需要将不同类型的数据,本文... 目录前言安装免费Java库1. 写入文本、或数值到 Excel单元格2. 写入数组到 Excel表格

redis中使用lua脚本的原理与基本使用详解

《redis中使用lua脚本的原理与基本使用详解》在Redis中使用Lua脚本可以实现原子性操作、减少网络开销以及提高执行效率,下面小编就来和大家详细介绍一下在redis中使用lua脚本的原理... 目录Redis 执行 Lua 脚本的原理基本使用方法使用EVAL命令执行 Lua 脚本使用EVALSHA命令

Python中pywin32 常用窗口操作的实现

《Python中pywin32常用窗口操作的实现》本文主要介绍了Python中pywin32常用窗口操作的实现,pywin32主要的作用是供Python开发者快速调用WindowsAPI的一个... 目录获取窗口句柄获取最前端窗口句柄获取指定坐标处的窗口根据窗口的完整标题匹配获取句柄根据窗口的类别匹配获取句

Java 中的 @SneakyThrows 注解使用方法(简化异常处理的利与弊)

《Java中的@SneakyThrows注解使用方法(简化异常处理的利与弊)》为了简化异常处理,Lombok提供了一个强大的注解@SneakyThrows,本文将详细介绍@SneakyThro... 目录1. @SneakyThrows 简介 1.1 什么是 Lombok?2. @SneakyThrows

在 Spring Boot 中实现异常处理最佳实践

《在SpringBoot中实现异常处理最佳实践》本文介绍如何在SpringBoot中实现异常处理,涵盖核心概念、实现方法、与先前查询的集成、性能分析、常见问题和最佳实践,感兴趣的朋友一起看看吧... 目录一、Spring Boot 异常处理的背景与核心概念1.1 为什么需要异常处理?1.2 Spring B

Python位移操作和位运算的实现示例

《Python位移操作和位运算的实现示例》本文主要介绍了Python位移操作和位运算的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 位移操作1.1 左移操作 (<<)1.2 右移操作 (>>)注意事项:2. 位运算2.1

如何在 Spring Boot 中实现 FreeMarker 模板

《如何在SpringBoot中实现FreeMarker模板》FreeMarker是一种功能强大、轻量级的模板引擎,用于在Java应用中生成动态文本输出(如HTML、XML、邮件内容等),本文... 目录什么是 FreeMarker 模板?在 Spring Boot 中实现 FreeMarker 模板1. 环

Qt实现网络数据解析的方法总结

《Qt实现网络数据解析的方法总结》在Qt中解析网络数据通常涉及接收原始字节流,并将其转换为有意义的应用层数据,这篇文章为大家介绍了详细步骤和示例,感兴趣的小伙伴可以了解下... 目录1. 网络数据接收2. 缓冲区管理(处理粘包/拆包)3. 常见数据格式解析3.1 jsON解析3.2 XML解析3.3 自定义