如何对一个大图形进行统一采样?

0h4hbjxa  于 2021-06-03  发布在  Hadoop
关注(0)|答案(1)|浏览(388)

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

wswtfjt7

wswtfjt71#

使用以下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\u sample.sh,要从folder/example/中选择15%,只需运行

./random_sample.sh /example/

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

相关问题