前言

之前写过稀疏图的实现方法,这次写用矩阵存储数据的算法实现,只要会矩阵相乘的话,实现这个就很简单了。如果有不懂的可以先看一下下面两篇随笔。

MapReduce实现PageRank算法(稀疏图法)

Python+MapReduce实现矩阵相乘

算法实现

我们需要输入两个矩阵A和B,我一开始想的是两个矩阵分别存在两个文件里然后分别读取,但是我发现好像不行,无法区分打上A、B的标签。

所以我一开始就把A、B矩阵合起来存在一个文件里,一次读取。

map.py

 #!/usr/bin/env python3
import os
import sys flag = 0 # 0表示处理A矩阵,1表示处理B矩阵
current_row = 1 # 记录现在处理矩阵的第几行 def read_input():
for lines in sys.stdin:
yield lines if __name__ == '__main__':
row_a = int(os.environ.get('row_a'))
col_a = int(os.environ.get('col_a'))
row_b = int(os.environ.get('row_b'))
col_b = int(os.environ.get('col_b'))
for line in read_input():
if line.count('\n') == len(line): # 去空行
pass
data = line.strip().split('\t') if flag == 0:
for i in range(col_b):
for j in range(col_a):
print("%s,%s\tA:%s,%s" % (current_row, i+1, j+1, data[j]))
current_row += 1
if current_row > row_a:
flag = 1
current_row = 1 elif flag == 1:
for i in range(row_a):
for j in range(col_b):
print("%s,%s\tB:%s,%s" % (i+1, j+1, current_row, data[j]))
current_row += 1

reduce.py

 #!/usr/bin/env python3
import os
import sys
from itertools import groupby
from operator import itemgetter def read_input(splitstr):
for line in sys.stdin:
line = line.strip()
if len(line) == 0:
continue
yield line.split(splitstr) if __name__ == '__main__':
alpha = float(os.environ.get('alpha'))
row_b = int(os.environ.get('row_b')) data = read_input('\t')
lstg = (groupby(data, itemgetter(0)))
try:
for flag, group in lstg:
matrix_a, matrix_b = {}, {}
total = 0.0
for element, g in group:
matrix = g.split(':')[0]
pos = g.split(':')[1].split(',')[0]
value = g.split(',')[1]
if matrix == 'A':
matrix_a[pos] = value
else:
matrix_b[pos] = value
for key in matrix_a:
total += float(matrix_a[key]) * float(matrix_b[key])
page_rank = alpha * total + (1.0 - alpha) / row_b
print("%s" % page_rank)
except Exception:
pass

算法运行

由于每次迭代会产生新的值,又因为我无法分两个文件读取,所以每次迭代后我要将网络矩阵和新的pageRank值合起来再上传至HDFS。

下面的Python代码的功能就是合并和记录迭代值。

 #!/usr/bin/env python3
import sys number = sys.stdin.readline().strip() f_src = open("tmp.txt","r")
f_dst1 = open("result.txt", "a")
f_dst2 = open("B.txt", "a") mat = "{:^30}\t"
f_dst1.write('\n' + number) lines = f_src.readlines()
for line in lines:
if line.count('\n') == len(line):
continue
line = line.strip()
f_dst1.write(mat.format(line))
f_dst2.write(line)
f_dst2.write('\n')

再贴一下运行脚本run.sh

 #!/bin/bash

 pos="/usr/local/hadoop"
max=10 for i in `seq 1 $max`
do $pos/bin/hadoop jar $pos/hadoop-streaming-2.9.2.jar \
-mapper $pos/mapper.py \
-file $pos/mapper.py \
-reducer $pos/reducer.py \
-file $pos/reducer.py \
-input B.txt \
-output out \
-cmdenv "row_a=4" \
-cmdenv "col_a=4" \
-cmdenv "row_b=4" \
-cmdenv "col_b=1" \
-cmdenv "alpha=0.8" \ rm -r ~/Desktop/B.txt
cp ~/Desktop/A.txt ~/Desktop/B.txt
rm -r ~/Desktop/tmp.txt
$pos/bin/hadoop fs -get out/part-00000 ~/Desktop/tmp.txt
echo $i | ~/Desktop/slove.py $pos/bin/hadoop fs -rm B.txt
$pos/bin/hadoop fs -rm -r -f out
$pos/bin/hadoop fs -put ~/Desktop/B.txt B.txt
done

我这里就随便迭代了10次:

我感觉mapreduce用来处理迭代计算实在是太麻烦了,所以才会有twister、haloop、spark这些开源框架的出现吧。

MapReduce实现PageRank算法(邻接矩阵法)的更多相关文章

  1. Hadoop实战训练————MapReduce实现PageRank算法

    经过一段时间的学习,对于Hadoop有了一些了解,于是决定用MapReduce实现PageRank算法,以下简称PR 先简单介绍一下PR算法(摘自百度百科:https://baike.baidu.co ...

  2. MapReduce实现PageRank算法(稀疏图法)

    前言 本文用Python编写代码,并通过hadoop streaming框架运行. 算法思想 下图是一个网络: 考虑转移矩阵是一个很多的稀疏矩阵,我们可以用稀疏矩阵的形式表示,我们把web图中的每一个 ...

  3. PageRank算法简介及Map-Reduce实现

    PageRank对网页排名的算法,曾是Google发家致富的法宝.以前虽然有实验过,但理解还是不透彻,这几天又看了一下,这里总结一下PageRank算法的基本原理. 一.什么是pagerank Pag ...

  4. PageRank算法初探

    1. PageRank的由来和发展历史 0x1:源自搜索引擎的需求 Google早已成为全球最成功的互联网搜索引擎,在Google出现之前,曾出现过许多通用或专业领域搜索引擎.Google最终能击败所 ...

  5. PageRank算法--从原理到实现

    本文将介绍PageRank算法的相关内容,具体如下: 1.算法来源 2.算法原理 3.算法证明 4.PR值计算方法 4.1 幂迭代法 4.2 特征值法 4.3 代数法 5.算法实现 5.1 基于迭代法 ...

  6. PageRank算法实现

    基本原理 在互联网上,如果一个网页被很多其他网页所链接,说明它受到普遍的承认和信赖,那么它的排名就高.这就是PageRank的核心思想. 引用来自<数学之美>的简单例子: 网页Y的排名应该 ...

  7. MapReduce 模式、算法和用例

    翻译自:http://highlyscalable.wordpress.com/2012/02/01/mapreduce-patterns/ 在这篇文章里总结了几种网上或者论文中常见的MapReduc ...

  8. 【原创】机器学习之PageRank算法应用与C#实现(1)算法介绍

    考虑到知识的复杂性,连续性,将本算法及应用分为3篇文章,请关注,将在本月逐步发表. 1.机器学习之PageRank算法应用与C#实现(1)算法介绍 2.机器学习之PageRank算法应用与C#实现(2 ...

  9. MapReduce 模式、算法和用例(MapReduce Patterns, Algorithms, and Use Cases)

    在新文章“MapReduce模式.算法和用例”中,Ilya Katsov提供了一个系统化的综述,阐述了能够应用MapReduce框架解决的问题. 文章开始描述了一个非常简单的.作为通用的并行计算框架的 ...

随机推荐

  1. 利用dladdr来获得so自身的路径

    #include <dlfcn.h> //定义该函数为了dladdr获取符号信息 void fun1() { } Dl_info info; //dladdr获取某个地址的符号信息 int ...

  2. html5+css基础

    最近在学习html+css3基础教程,整理了一些基础知识点.在此与大家分享. 1.盒模型 定义:css处理网页时,它认为每个元素都包含在一个不可见的盒子里,即我们所熟知的盒模型.其中它的主要属性有:h ...

  3. 【QT】Pycharm add QT Desinger

    1. https://www.cnblogs.com/dalanjing/p/6978373.html -m PyQt5.uic.pyuic  $FileName$ -o $FileNameWitho ...

  4. seq2seq笔记

    max_encoder_seq_length = max([len(txt) for txt in input_texts]) encoder_input_data = np.zeros(     ( ...

  5. 【LeetCode每天一题】Unique Paths(唯一的路径数)

    A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).The ...

  6. 2018DDCTF misc1

    一.题目: (╯°□°)╯︵ ┻━┻ d4e8e1f4a0f7e1f3a0e6e1f3f4a1a0d4e8e5a0e6ece1e7a0e9f3baa0c4c4c3d4c6fbb9e1e6b3e3b9e ...

  7. AWS 移动推送到iOS设备,Amazon Pinpoint

    前言 第一次对接aws,遇到的坑是真多.现在记录一下.本文主要用到的是[Amazon Pinpoint]推送. 开发人员的指南:https://docs.aws.amazon.com/zh_cn/pi ...

  8. 关于eclipse常用的一些快捷键

    Ctrl+Alt+H :查看方法被哪些代码调用了 Ctrl + Shif +O :自动引导类包 Ctrl+Shift+/     : 加上段注释 Ctrl+Shift+\  : 取消段注释 ALT+/ ...

  9. 使用微软自带 SharpZipLib 进行多文件 压缩

    /// <summary> /// 指定路径打包下载 /// </summary> /// <param name="fileName">< ...

  10. SecureCRT通过密钥登录(网上也有很多教程,但是有些不详细,此教程本人亲测)

    1.先打开SecureCRT,标题标--工具---创建公钥,如图: 2.点击创建公钥,弹出选项点下一步 3.继续点下一步: 4.继续点下一步: 5.继续点下一步(密钥长度默认1024即可),生成密钥需 ...