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

相关文章

Linux使用fdisk进行磁盘的相关操作

《Linux使用fdisk进行磁盘的相关操作》fdisk命令是Linux中用于管理磁盘分区的强大文本实用程序,这篇文章主要为大家详细介绍了如何使用fdisk进行磁盘的相关操作,需要的可以了解下... 目录简介基本语法示例用法列出所有分区查看指定磁盘的区分管理指定的磁盘进入交互式模式创建一个新的分区删除一个存

C#使用HttpClient进行Post请求出现超时问题的解决及优化

《C#使用HttpClient进行Post请求出现超时问题的解决及优化》最近我的控制台程序发现有时候总是出现请求超时等问题,通常好几分钟最多只有3-4个请求,在使用apipost发现并发10个5分钟也... 目录优化结论单例HttpClient连接池耗尽和并发并发异步最终优化后优化结论我直接上优化结论吧,

windos server2022里的DFS配置的实现

《windosserver2022里的DFS配置的实现》DFS是WindowsServer操作系统提供的一种功能,用于在多台服务器上集中管理共享文件夹和文件的分布式存储解决方案,本文就来介绍一下wi... 目录什么是DFS?优势:应用场景:DFS配置步骤什么是DFS?DFS指的是分布式文件系统(Distr

NFS实现多服务器文件的共享的方法步骤

《NFS实现多服务器文件的共享的方法步骤》NFS允许网络中的计算机之间共享资源,客户端可以透明地读写远端NFS服务器上的文件,本文就来介绍一下NFS实现多服务器文件的共享的方法步骤,感兴趣的可以了解一... 目录一、简介二、部署1、准备1、服务端和客户端:安装nfs-utils2、服务端:创建共享目录3、服

SpringBoot使用Apache Tika检测敏感信息

《SpringBoot使用ApacheTika检测敏感信息》ApacheTika是一个功能强大的内容分析工具,它能够从多种文件格式中提取文本、元数据以及其他结构化信息,下面我们来看看如何使用Ap... 目录Tika 主要特性1. 多格式支持2. 自动文件类型检测3. 文本和元数据提取4. 支持 OCR(光学

JAVA系统中Spring Boot应用程序的配置文件application.yml使用详解

《JAVA系统中SpringBoot应用程序的配置文件application.yml使用详解》:本文主要介绍JAVA系统中SpringBoot应用程序的配置文件application.yml的... 目录文件路径文件内容解释1. Server 配置2. Spring 配置3. Logging 配置4. Ma

Linux使用dd命令来复制和转换数据的操作方法

《Linux使用dd命令来复制和转换数据的操作方法》Linux中的dd命令是一个功能强大的数据复制和转换实用程序,它以较低级别运行,通常用于创建可启动的USB驱动器、克隆磁盘和生成随机数据等任务,本文... 目录简介功能和能力语法常用选项示例用法基础用法创建可启动www.chinasem.cn的 USB 驱动

C#使用yield关键字实现提升迭代性能与效率

《C#使用yield关键字实现提升迭代性能与效率》yield关键字在C#中简化了数据迭代的方式,实现了按需生成数据,自动维护迭代状态,本文主要来聊聊如何使用yield关键字实现提升迭代性能与效率,感兴... 目录前言传统迭代和yield迭代方式对比yield延迟加载按需获取数据yield break显式示迭

Python实现高效地读写大型文件

《Python实现高效地读写大型文件》Python如何读写的是大型文件,有没有什么方法来提高效率呢,这篇文章就来和大家聊聊如何在Python中高效地读写大型文件,需要的可以了解下... 目录一、逐行读取大型文件二、分块读取大型文件三、使用 mmap 模块进行内存映射文件操作(适用于大文件)四、使用 pand

使用SQL语言查询多个Excel表格的操作方法

《使用SQL语言查询多个Excel表格的操作方法》本文介绍了如何使用SQL语言查询多个Excel表格,通过将所有Excel表格放入一个.xlsx文件中,并使用pandas和pandasql库进行读取和... 目录如何用SQL语言查询多个Excel表格如何使用sql查询excel内容1. 简介2. 实现思路3