草庐IT

java - 在 Reducer 中查找最常见的键,错误 : java. lang.ArrayIndexOutOfBoundsException:1

coder 2024-01-08 原文

我需要在 Reducer 中找到 Mapper 发出的最常见的键。我的 reducer 以这种方式工作正常:

public static class MyReducer extends Reducer<NullWritable, Text, NullWritable, Text> {
    private Text result = new Text();
    private TreeMap<Double, Text> k_closest_points= new TreeMap<Double, Text>();
    public void reduce(NullWritable key, Iterable<Text> values, Context context)
            throws IOException, InterruptedException {

        Configuration conf = context.getConfiguration();
        int K = Integer.parseInt(conf.get("K"));
        for (Text value : values) {
            String v[] = value.toString().split("@");    //format of value from mapper: "Key@1.2345"
            double distance = Double.parseDouble(v[1]);
            k_closest_points.put(distance, new Text(value));    //finds the K smallest distances
            if (k_closest_points.size() > K)
                k_closest_points.remove(k_closest_points.lastKey());
        }
        for (Text t : k_closest_points.values())    //it perfectly emits the K smallest distances and keys
            context.write(NullWritable.get(), t);
    }
}

它找到距离最小的 K 个实例并写入输出文件。但我需要在我的 TreeMap 中找到最常用的键。所以我正在尝试如下:

public static class MyReducer extends Reducer<NullWritable, Text, NullWritable, Text> {
    private Text result = new Text();
    private TreeMap<Double, Text> k_closest_points = new TreeMap<Double, Text>();

    public void reduce(NullWritable key, Iterable<Text> values, Context context)
            throws IOException, InterruptedException {

        Configuration conf = context.getConfiguration();
        int K = Integer.parseInt(conf.get("K"));
        for (Text value : values) {
            String v[] = value.toString().split("@");
            double distance = Double.parseDouble(v[1]);
            k_closest_points.put(distance, new Text(value));
            if (k_closest_points.size() > K)
                k_closest_points.remove(k_closest_points.lastKey());
        }
        TreeMap<String, Integer> class_counts = new TreeMap<String, Integer>();
        for (Text value : k_closest_points.values()) {
            String[] tmp = value.toString().split("@");
            if (class_counts.containsKey(tmp[0]))
                class_counts.put(tmp[0], class_counts.get(tmp[0] + 1));
            else
                class_counts.put(tmp[0], 1);
        }
        context.write(NullWritable.get(), new Text(class_counts.lastKey()));
    }
}

然后我得到这个错误:

Error: java.lang.ArrayIndexOutOfBoundsException: 1
        at KNN$MyReducer.reduce(KNN.java:108)
        at KNN$MyReducer.reduce(KNN.java:98)
        at org.apache.hadoop.mapreduce.Reducer.run(Reducer.java:171)

你能帮我解决这个问题吗?

最佳答案

一些事情......首先,你的问题在这里:

double distance = Double.parseDouble(v[1]);

你正在 split "@"它可能不在字符串中。如果不是,它会抛出 OutOfBoundsException。 .我会添加一个子句:

if(v.length < 2)
    continue;

其次(除非我疯了,否则这甚至不应该编译),tmpString[] , 但在这里你实际上只是连接 '1'put操作(这是一个括号问题):

class_counts.put(tmp[0], class_counts.get(tmp[0] + 1));

应该是:

class_counts.put(tmp[0], class_counts.get(tmp[0]) + 1);

在可能很大的 Map 中查找 key 两次也很昂贵.以下是我将如何根据您提供给我们的内容重写您的 reducer (这完全未经测试):

public static class MyReducer extends Reducer<NullWritable, Text, NullWritable, Text> {
    private Text result = new Text();
    private TreeMap<Double, Text> k_closest_points = new TreeMap<Double, Text>();

    public void reduce(NullWritable key, Iterable<Text> values, Context context)
            throws IOException, InterruptedException {

        Configuration conf = context.getConfiguration();
        int K = Integer.parseInt(conf.get("K"));

        for (Text value : values) {
            String v[] = value.toString().split("@");
            if(v.length < 2)
                continue; // consider adding an enum counter

            double distance = Double.parseDouble(v[1]);
            k_closest_points.put(distance, new Text(v[0])); // you've already split once, why do it again later?

            if (k_closest_points.size() > K)
                k_closest_points.remove(k_closest_points.lastKey());
        }


        // exit early if nothing found
        if(k_closest_points.isEmpty())
            return;


        TreeMap<String, Integer> class_counts = new TreeMap<String, Integer>();
        for (Text value : k_closest_points.values()) {
            String tmp = value.toString();
            Integer current_count = class_counts.get(tmp);

            if (null != current_count) // avoid second lookup
                class_counts.put(tmp, current_count + 1);
            else
                class_counts.put(tmp, 1);
        }

        context.write(NullWritable.get(), new Text(class_counts.lastKey()));
    }
}

接下来,从语义上讲,您将使用 TreeMap 执行 KNN 运算。作为您选择的数据结构。虽然这是有道理的,因为它在内部按比较顺序存储 key ,但使用 Map 没有意义。对于几乎毫无疑问需要打破联系的操作。原因如下:

int k = 2;
TreeMap<Double, Text> map = new TreeMap<>();
map.put(1.0, new Text("close"));
map.put(1.0, new Text("equally close"));
map.put(1500.0, new Text("super far"));
// ... your popping logic...

您保留的最近的两个点是哪两个? "equally close""super far" .这是因为您不能拥有同一 key 的两个实例。因此,您的算法无法打破平局。您可以采取一些措施来解决此问题:

首先,如果您准备在 Reducer 中执行此操作并且您知道您的传入数据不会导致 OutOfMemoryError , 考虑使用不同的排序结构,如 TreeSet并构建自定义 Comparable它将排序的对象:

static class KNNEntry implements Comparable<KNNEntry> {
    final Text text;
    final Double dist;

    KNNEntry(Text text, Double dist) {
        this.text = text;
        this.dist = dist;
    }

    @Override
    public int compareTo(KNNEntry other) {
        int comp = this.dist.compareTo(other.dist);
        if(0 == comp)
            return this.text.compareTo(other.text);
        return comp;
    }
}

然后代替你的 TreeMap , 使用 TreeSet<KNNEntry> ,它将根据 Comparator 在内部对自身进行排序我们刚刚在上面构建的逻辑。然后在你完成所有键之后,只需遍历第一个 k ,按顺序保留它们。但是,这有一个缺点:如果您的数据确实很大,您可以通过将所有值从 reducer 加载到内存中来溢出堆空间。

第二个选项:制作KNNEntry我们在上面构建了工具 WritableComparable ,并从你的 Mapper 发出, 然后使用 secondary sorting处理条目的排序。这变得有点复杂,因为您必须使用大量映射器,然后只使用一个缩减器来捕获第一个 k。 .如果您的数据足够小,请尝试第一个选项以允许打破平局。

但是,回到你原来的问题,你得到一个 OutOfBoundsException因为您尝试访问的索引不存在,即输入中没有“@”String .

关于java - 在 Reducer 中查找最常见的键,错误 : java. lang.ArrayIndexOutOfBoundsException:1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36220211/

有关java - 在 Reducer 中查找最常见的键,错误 : java. lang.ArrayIndexOutOfBoundsException:1的更多相关文章

  1. ruby-on-rails - Rails 常用字符串(用于通知和错误信息等) - 2

    大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje

  2. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  3. ruby-on-rails - 迷你测试错误 : "NameError: uninitialized constant" - 2

    我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test

  4. ruby - 检查字符串是否包含散列中的任何键并返回它包含的键的值 - 2

    我有一个包含多个键的散列和一个字符串,该字符串不包含散列中的任何键或包含一个键。h={"k1"=>"v1","k2"=>"v2","k3"=>"v3"}s="thisisanexamplestringthatmightoccurwithakeysomewhereinthestringk1(withspecialcharacterslike(^&*$#@!^&&*))"检查s是否包含h中的任何键的最佳方法是什么,如果包含,则返回它包含的键的值?例如,对于上面的h和s的例子,输出应该是v1。编辑:只有字符串是用户定义的。哈希将始终相同。 最佳答案

  5. ruby-on-rails - 如何在 Rails View 上显示错误消息? - 2

    我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c

  6. 使用 ACL 调用 upload_file 时出现 Ruby S3 "Access Denied"错误 - 2

    我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file

  7. ruby-on-rails - 错误 : Error installing pg: ERROR: Failed to build gem native extension - 2

    我克隆了一个rails仓库,我现在正尝试捆绑安装背景:OSXElCapitanruby2.2.3p173(2015-08-18修订版51636)[x86_64-darwin15]rails-v在您的Gemfile中列出的或native可用的任何gem源中找不到gem'pg(>=0)ruby​​'。运行bundleinstall以安装缺少的gem。bundleinstallFetchinggemmetadatafromhttps://rubygems.org/............Fetchingversionmetadatafromhttps://rubygems.org/...Fe

  8. ruby - #之间? Cooper 的 *Beginning Ruby* 中的错误或异常 - 2

    在Cooper的书BeginningRuby中,第166页有一个我无法重现的示例。classSongincludeComparableattr_accessor:lengthdef(other)@lengthother.lengthenddefinitialize(song_name,length)@song_name=song_name@length=lengthendenda=Song.new('Rockaroundtheclock',143)b=Song.new('BohemianRhapsody',544)c=Song.new('MinuteWaltz',60)a.betwee

  9. ruby - 当使用::指定模块时,为什么 Ruby 不在更高范围内查找类? - 2

    我刚刚被困在这个问题上一段时间了。以这个基地为例:moduleTopclassTestendmoduleFooendend稍后,我可以通过这样做在Foo中定义扩展Test的类:moduleTopmoduleFooclassSomeTest但是,如果我尝试通过使用::指定模块来最小化缩进:moduleTop::FooclassFailure这失败了:NameError:uninitializedconstantTop::Foo::Test这是一个错误,还是仅仅是Ruby解析变量名的方式的逻辑结果? 最佳答案 Isthisabug,or

  10. ruby-on-rails - 每次我尝试部署时,我都会得到 - (gcloud.preview.app.deploy) 错误响应 : [4] DEADLINE_EXCEEDED - 2

    我是Google云的新手,我正在尝试对其进行首次部署。我的第一个部署是RubyonRails项目。我基本上是在关注thisguideinthegoogleclouddocumentation.唯一的区别是我使用的是我自己的项目,而不是他们提供的“helloworld”项目。这是我的app.yaml文件runtime:customvm:trueentrypoint:bundleexecrackup-p8080-Eproductionconfig.ruresources:cpu:0.5memory_gb:1.3disk_size_gb:10当我转到我的项目目录并运行gcloudprevie

随机推荐