Computes the weighted average of scores: -> log( w0 * exp(score[0]) + w1 exp(score[1]) + w1 * exp(score[2]) + .. - Java java.lang

Java examples for java.lang:Math Calculation

Description

Computes the weighted average of scores: -> log( w0 * exp(score[0]) + w1 exp(score[1]) + w1 * exp(score[2]) + ..

Demo Code

// BSD License (http://lemurproject.org/galago-license)
//package com.java2s;

public class Main {
    /**//from   w  ww. j  av a 2  s .  c om
     * Computes the weighted average of scores: -> log( w0 * exp(score[0]) + w1 *
     * exp(score[1]) + w1 * exp(score[2]) + .. )
     *
     * to avoid rounding errors, we compute the equivalent expression:
     *
     * returns: maxScore + log( w0 * exp(score[0] - max) + w1 * exp(score[1] -
     * max) + w2 * exp(score[2] - max) + .. )
     */
    public static double weightedLogSumExp(double[] weights, double[] scores) {
        if (scores.length == 0) {
            throw new RuntimeException(
                    "weightedLogSumExp was called with a zero length array of scores.");
        }

        // find max value - this score will dominate the final score
        double max = Double.NEGATIVE_INFINITY;
        for (double score : scores) {
            max = Math.max(score, max);
        }

        double sum = 0;
        for (int i = 0; i < scores.length; i++) {
            sum += weights[i] * Math.exp(scores[i] - max);
        }
        sum = max + Math.log(sum);

        return sum;
    }
}

Related Tutorials