hadoop集群运行MR程序、mahout程序

2024-03-03 23:08

本文主要是介绍hadoop集群运行MR程序、mahout程序,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

hadoop集群运行MR程序

  • 1. 启动集群
  • 2. 上传程序资源到hdfs
  • 3. 修改程序文件路径
  • 4. 安装mahout
  • 5. 提交程序到集群

本教程在配置完hadoop,可以正常运行的前提下进行

1. 启动集群

# 启动hdfs
sbin/start-dfs.sh# 启动yarn
sbin/start-yarn.sh

使用jps命令,看到如下图所示,启动成功。
进程


2. 上传程序资源到hdfs

  1. 第一步:把文件上传到服务器。
  2. 第二步:把文件上传到hdfs集群。
bin/hadoop dfs -put ../train_data /

看到如下图所示,上传成功。
hdfs文件目录


3. 修改程序文件路径

把程序读取文件的路径,修改为从参数中获取,本程序需要修改为如下代码:

package com.demo;import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;import java.io.IOException;
import java.util.*;/*** @author affable* @description 处理数据* @date 2020/5/13 10:30*/
public class DataAnalysis {/*** 解析文件,取出userId*/static class ParseTxtMapper extends Mapper<LongWritable, Text, Text, Text> {Text k = new Text();Text v = new Text();@Overrideprotected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {// 切分获取每个字段值String[] fields = value.toString().split(",");// k -> userId// v -> workId,actionk.set(fields[0]);v.set(fields[1] + "," + fields[2]);context.write(k, v);}}/*** 按每个userId进行reducer*/static class ScoreReducer extends Reducer<Text, Text, Text, Text> {// 此userId对于所有浏览职位的actionMap<String, Integer> workActions = new HashMap<>();// 此userId对于所有已投递职位的actionMap<String, Integer> deliveryWorks = new HashMap<>();// 最大值double maxWorkAction = 0.0D;double maxDeliveryWorkAction = 0.0D;// 这次的userIdString userId;Text k = new Text();Text v = new Text();@Overrideprotected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {userId = key.toString();for (Text value : values) {String[] fields = value.toString().split(",");if ("2".equals(fields[1])) {// 如果投递了该职位// 如果map中没有,则放入1,如果有,则在此基础加1deliveryWorks.merge(fields[0], 1, Integer::sum);Integer count = deliveryWorks.get(fields[0]);maxDeliveryWorkAction = count > maxDeliveryWorkAction ? count : maxDeliveryWorkAction;} else {// 只是浏览了职位workActions.merge(fields[0], 1, Integer::sum);Integer count = workActions.get(fields[0]);maxWorkAction = count > maxWorkAction ? count : maxWorkAction;}}// 从浏览职位中去除已投递的deliveryWorks.forEach((k, v) -> workActions.remove(k));// 计算分数// 规则://     浏览量/最大浏览量*4  (0, 4]//     投递量/最大投递量+4  (4, 5]for (Map.Entry<String, Integer> entry : workActions.entrySet()) {String workId = entry.getKey();Integer count = entry.getValue();k.set(userId + "\t" + workId);v.set(String.format("%.2f", count / maxWorkAction * 4));context.write(k, v);}for (Map.Entry<String, Integer> entry : deliveryWorks.entrySet()) {String workId = entry.getKey();Integer count = entry.getValue();k.set(userId + "\t" + workId);v.set(String.format("%.2f", 4.0 + count / maxDeliveryWorkAction));context.write(k, v);}// 清空数据workActions.clear();deliveryWorks.clear();maxWorkAction = 0.0D;maxDeliveryWorkAction = 0.0D;}}public static void main(String[] args) throws Exception {String inputPath = args[0];String outputPath = args[1];Configuration conf = new Configuration();Job job = Job.getInstance(conf, "cal_user_score");job.setJarByClass(DataAnalysis.class);job.setMapperClass(ParseTxtMapper.class);job.setReducerClass(ScoreReducer.class);job.setOutputKeyClass(Text.class);job.setOutputValueClass(Text.class);job.setNumReduceTasks(1);// 设置输入输出路径FileInputFormat.setInputPaths(job, new Path(inputPath));FileOutputFormat.setOutputPath(job, new Path(outputPath));System.exit(job.waitForCompletion(true) ? 0 : 1);}}
package com.demo;import org.apache.commons.csv.CSVParser;
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.mahout.cf.taste.common.TasteException;
import org.apache.mahout.cf.taste.impl.common.FastByIDMap;
import org.apache.mahout.cf.taste.impl.common.LongPrimitiveIterator;
import org.apache.mahout.cf.taste.impl.model.GenericDataModel;
import org.apache.mahout.cf.taste.impl.model.GenericPreference;
import org.apache.mahout.cf.taste.impl.model.GenericUserPreferenceArray;
import org.apache.mahout.cf.taste.impl.model.MemoryIDMigrator;
import org.apache.mahout.cf.taste.impl.recommender.svd.ALSWRFactorizer;
import org.apache.mahout.cf.taste.impl.recommender.svd.SVDRecommender;
import org.apache.mahout.cf.taste.model.DataModel;
import org.apache.mahout.cf.taste.model.Preference;
import org.apache.mahout.cf.taste.model.PreferenceArray;
import org.apache.mahout.cf.taste.recommender.RecommendedItem;
import org.apache.mahout.cf.taste.recommender.Recommender;import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;/*** @author affable* @description 职位推荐* @date 2020/5/11 10:02*/
public class WorkRecommend {private static final int SIZE = 20;/*** 获取文件系统*/private static FileSystem getFiledSystem() throws IOException {Configuration configuration = new Configuration();return FileSystem.get(configuration);}/*** 读取hdfs文件* @param filePath 文件路径* @return 返回读取文件流*/private static BufferedReader readHDFSFile(String filePath) throws FileNotFoundException {FSDataInputStream fsDataInputStream = null;BufferedReader reader = null;try {Path path = new Path(filePath);fsDataInputStream = getFiledSystem().open(path);reader = new BufferedReader(new InputStreamReader(fsDataInputStream));} catch (IOException e) {e.printStackTrace();}return reader;}public static void main(String[] args) throws TasteException, IOException {// *******************************处理开始******************************************// 使用推荐模型之前,对数据的userId和workId映射成long类型// 防止模型把userId和workId转为long,出现数据异常// 数据存储路径String dataPath = args[0];Map<Long,List<Preference>> preferecesOfUsers = new HashMap<>(16);// 读取原始数据并处理BufferedReader reader = readHDFSFile(dataPath);CSVParser parser = new CSVParser(reader, '\t');String[] line;MemoryIDMigrator userIdMigrator = new MemoryIDMigrator();MemoryIDMigrator workIdMigrator = new MemoryIDMigrator();while((line = parser.getLine()) != null) {// string 转 longlong userIdLong = userIdMigrator.toLongID(line[0]);long workIdLong = workIdMigrator.toLongID(line[1]);userIdMigrator.storeMapping(userIdLong, line[0]);workIdMigrator.storeMapping(workIdLong, line[1]);List<Preference> userPrefList;if((userPrefList = preferecesOfUsers.get(userIdLong)) == null) {userPrefList = new ArrayList<>();preferecesOfUsers.put(userIdLong, userPrefList);}userPrefList.add(new GenericPreference(userIdLong, workIdLong, Float.parseFloat(line[2])));}FastByIDMap<PreferenceArray> preferecesOfUsersFastMap = new FastByIDMap<>();for(Map.Entry<Long, List<Preference>> entry : preferecesOfUsers.entrySet()) {preferecesOfUsersFastMap.put(entry.getKey(), new GenericUserPreferenceArray(entry.getValue()));}// ***********************************处理完成**************************************// 读取数据DataModel dataModel = new GenericDataModel(preferecesOfUsersFastMap);// 使用als求损失函数ALSWRFactorizer factorizer = new ALSWRFactorizer(dataModel, 5, 0.2, 200);// 使用SVD算法进行推荐Recommender recommender = new SVDRecommender(dataModel, factorizer);// 推荐测试LongPrimitiveIterator userIdIterator = dataModel.getUserIDs();int i = 0;while (userIdIterator.hasNext()) {long userIdLong = userIdIterator.nextLong();String userId = userIdMigrator.toStringID(userIdLong);List<RecommendedItem> recommendedItems = recommender.recommend(userIdLong, SIZE);for (RecommendedItem item : recommendedItems) {// 写出到mysql// MysqlUtils.insert(userId, workIdMigrator.toStringID(item.getItemID()), item.getValue());System.out.println(String.format("userId: %s, itemId: %s, score: %.2f",userId, workIdMigrator.toStringID(item.getItemID()), item.getValue()));i++;}}System.out.println(i);// 释放资源// MysqlUtils.release();reader.close();}}

4. 安装mahout

  1. 下载安装包。
  2. 上传到服务器,并解压。
  3. 修改环境变量,在/etc/profile中做如下修改,并重新加载profile文件。

修改环境变量

source /etc/profile
  1. 修改mahout配置(或者添加HADOOP_CONF_DIR环境变量也可以)
vim bin/mahout

修改配置
6. 在命令行输入 mahout,测试是否可以正常运行。


5. 提交程序到集群

  1. 本地使用以下命令对程序打包,并上传到服务器。
    最好把后缀为-with-dependencies.jar的包上传到服务器,防止hadoop集群没有对应的依赖包
# maven程序打包
mvn clean package
  1. 运行数据分析处理程序。
# 最后两个参数为:待处理数据路径,处理后结果的保存路径
bin/hadoop jar ../work-recommend-1.0.0-Release-jar-with-dependencies.jar com.demo.DataAnalysis /train_data/user_action.csv /work_out/user_score

如下图所示,运行成功。
成功
成功
3. 运行预测程序。

mahout hadoop jar ../work-recommend-1.0.0-Release-jar-with-dependencies.jar com.demo.WorkRecommend hdfs://localhost:9000/work_out/user_score/part-r-00000

执行结果如下
运行结果

这篇关于hadoop集群运行MR程序、mahout程序的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

python编写朋克风格的天气查询程序

《python编写朋克风格的天气查询程序》这篇文章主要为大家详细介绍了一个基于Python的桌面应用程序,使用了tkinter库来创建图形用户界面并通过requests库调用Open-MeteoAPI... 目录工具介绍工具使用说明python脚本内容如何运行脚本工具介绍这个天气查询工具是一个基于 Pyt

Ubuntu设置程序开机自启动的操作步骤

《Ubuntu设置程序开机自启动的操作步骤》在部署程序到边缘端时,我们总希望可以通电即启动我们写好的程序,本篇博客用以记录如何在ubuntu开机执行某条命令或者某个可执行程序,需要的朋友可以参考下... 目录1、概述2、图形界面设置3、设置为Systemd服务1、概述测试环境:Ubuntu22.04 带图

Java -jar命令如何运行外部依赖JAR包

《Java-jar命令如何运行外部依赖JAR包》在Java应用部署中,java-jar命令是启动可执行JAR包的标准方式,但当应用需要依赖外部JAR文件时,直接使用java-jar会面临类加载困... 目录引言:外部依赖JAR的必要性一、问题本质:类加载机制的限制1. Java -jar的默认行为2. 类加

java -jar命令运行 jar包时运行外部依赖jar包的场景分析

《java-jar命令运行jar包时运行外部依赖jar包的场景分析》:本文主要介绍java-jar命令运行jar包时运行外部依赖jar包的场景分析,本文给大家介绍的非常详细,对大家的学习或工作... 目录Java -jar命令运行 jar包时如何运行外部依赖jar包场景:解决:方法一、启动参数添加: -Xb

Python程序打包exe,单文件和多文件方式

《Python程序打包exe,单文件和多文件方式》:本文主要介绍Python程序打包exe,单文件和多文件方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录python 脚本打成exe文件安装Pyinstaller准备一个ico图标打包方式一(适用于文件较少的程

Python程序的文件头部声明小结

《Python程序的文件头部声明小结》在Python文件的顶部声明编码通常是必须的,尤其是在处理非ASCII字符时,下面就来介绍一下两种头部文件声明,具有一定的参考价值,感兴趣的可以了解一下... 目录一、# coding=utf-8二、#!/usr/bin/env python三、运行Python程序四、

eclipse如何运行springboot项目

《eclipse如何运行springboot项目》:本文主要介绍eclipse如何运行springboot项目问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目js录当在eclipse启动spring boot项目时出现问题解决办法1.通过cmd命令行2.在ecl

无法启动此程序因为计算机丢失api-ms-win-core-path-l1-1-0.dll修复方案

《无法启动此程序因为计算机丢失api-ms-win-core-path-l1-1-0.dll修复方案》:本文主要介绍了无法启动此程序,详细内容请阅读本文,希望能对你有所帮助... 在计算机使用过程中,我们经常会遇到一些错误提示,其中之一就是"api-ms-win-core-path-l1-1-0.dll丢失

使用nohup和--remove-source-files在后台运行rsync并记录日志方式

《使用nohup和--remove-source-files在后台运行rsync并记录日志方式》:本文主要介绍使用nohup和--remove-source-files在后台运行rsync并记录日... 目录一、什么是 --remove-source-files?二、示例命令三、命令详解1. nohup2.

SpringBoot后端实现小程序微信登录功能实现

《SpringBoot后端实现小程序微信登录功能实现》微信小程序登录是开发者通过微信提供的身份验证机制,获取用户唯一标识(openid)和会话密钥(session_key)的过程,这篇文章给大家介绍S... 目录SpringBoot实现微信小程序登录简介SpringBoot后端实现微信登录SpringBoo