如何统一样本大图?

时间:2014-01-21 00:13:30

标签: hadoop mapreduce graph-algorithm random-sample

我有一个大图,大约有4M个节点。该图由两个文件组成,一个包含节点名称,另一个包含边(每行代表一条边)。我想统一对图节点进行采样,并提出一个大至整个图形的15%的样本。考虑到图形的大小,生成这样的样本的最佳(或可能)方法是什么?

1 个答案:

答案 0 :(得分:0)

使用此java代码随机选择15%的顶点:

import java.io.IOException;
import java.util.*;

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.*;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;

public class RandomSample {

 public static class Map extends Mapper<LongWritable, Text, Text, Text> {
    private Text word = new Text();

    public void map(LongWritable key, Text value, Context context)
    throws IOException, InterruptedException {
        if (Math.random()<0.15)
            context.write(value,null);
        else
            context.write(null,null);
    context.write(value,null);
    } 
 }

 public static void main(String[] args) throws Exception {
    Configuration conf = new Configuration();

    Job job = new Job(conf, "randomsample");
    job.setJarByClass(RandomSample.class);

    job.setOutputKeyClass(Text.class);
    job.setOutputValueClass(IntWritable.class);

    job.setOutputKeyClass(Text.class);
    job.setOutputValueClass(Text.class);
    job.setInputFormatClass(TextInputFormat.class);
    job.setOutputFormatClass(TextOutputFormat.class);

    job.setNumReduceTasks(0);

    FileInputFormat.addInputPath(job, new Path(args[0]));
    FileOutputFormat.setOutputPath(job, new Path(args[1]));

    job.waitForCompletion(true);
 }

}

并使用此bash脚本运行它

echo "Running Job"
hadoop jar RandomSample.jar RandomSample $1 tmp
echo "copying result to local path (RandomSample)"
hadoop fs -getmerge tmp RandomSample
echo "Clean up"
hadoop fs -rmr tmp

例如,如果我们将脚本命名为random_sample.sh,要从文件夹/ example /中选择15%,只需运行

./random_sample.sh /example/

然后,您可以对第二个文件使用简单的grep操作来仅选择包含随机选择的顶点的边