使用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

相关文章

HTML5 getUserMedia API网页录音实现指南示例小结

《HTML5getUserMediaAPI网页录音实现指南示例小结》本教程将指导你如何利用这一API,结合WebAudioAPI,实现网页录音功能,从获取音频流到处理和保存录音,整个过程将逐步... 目录1. html5 getUserMedia API简介1.1 API概念与历史1.2 功能与优势1.3

gitlab安装及邮箱配置和常用使用方式

《gitlab安装及邮箱配置和常用使用方式》:本文主要介绍gitlab安装及邮箱配置和常用使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1.安装GitLab2.配置GitLab邮件服务3.GitLab的账号注册邮箱验证及其分组4.gitlab分支和标签的

Java实现删除文件中的指定内容

《Java实现删除文件中的指定内容》在日常开发中,经常需要对文本文件进行批量处理,其中,删除文件中指定内容是最常见的需求之一,下面我们就来看看如何使用java实现删除文件中的指定内容吧... 目录1. 项目背景详细介绍2. 项目需求详细介绍2.1 功能需求2.2 非功能需求3. 相关技术详细介绍3.1 Ja

SpringBoot3应用中集成和使用Spring Retry的实践记录

《SpringBoot3应用中集成和使用SpringRetry的实践记录》SpringRetry为SpringBoot3提供重试机制,支持注解和编程式两种方式,可配置重试策略与监听器,适用于临时性故... 目录1. 简介2. 环境准备3. 使用方式3.1 注解方式 基础使用自定义重试策略失败恢复机制注意事项

nginx启动命令和默认配置文件的使用

《nginx启动命令和默认配置文件的使用》:本文主要介绍nginx启动命令和默认配置文件的使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录常见命令nginx.conf配置文件location匹配规则图片服务器总结常见命令# 默认配置文件启动./nginx

在Windows上使用qemu安装ubuntu24.04服务器的详细指南

《在Windows上使用qemu安装ubuntu24.04服务器的详细指南》本文介绍了在Windows上使用QEMU安装Ubuntu24.04的全流程:安装QEMU、准备ISO镜像、创建虚拟磁盘、配置... 目录1. 安装QEMU环境2. 准备Ubuntu 24.04镜像3. 启动QEMU安装Ubuntu4

使用Python和OpenCV库实现实时颜色识别系统

《使用Python和OpenCV库实现实时颜色识别系统》:本文主要介绍使用Python和OpenCV库实现的实时颜色识别系统,这个系统能够通过摄像头捕捉视频流,并在视频中指定区域内识别主要颜色(红... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间详解

Windows下C++使用SQLitede的操作过程

《Windows下C++使用SQLitede的操作过程》本文介绍了Windows下C++使用SQLite的安装配置、CppSQLite库封装优势、核心功能(如数据库连接、事务管理)、跨平台支持及性能优... 目录Windows下C++使用SQLite1、安装2、代码示例CppSQLite:C++轻松操作SQ

PostgreSQL中MVCC 机制的实现

《PostgreSQL中MVCC机制的实现》本文主要介绍了PostgreSQL中MVCC机制的实现,通过多版本数据存储、快照隔离和事务ID管理实现高并发读写,具有一定的参考价值,感兴趣的可以了解一下... 目录一 MVCC 基本原理python1.1 MVCC 核心概念1.2 与传统锁机制对比二 Postg

SpringBoot整合Flowable实现工作流的详细流程

《SpringBoot整合Flowable实现工作流的详细流程》Flowable是一个使用Java编写的轻量级业务流程引擎,Flowable流程引擎可用于部署BPMN2.0流程定义,创建这些流程定义的... 目录1、流程引擎介绍2、创建项目3、画流程图4、开发接口4.1 Java 类梳理4.2 查看流程图4