Example usage for org.apache.mahout.math.function IntIntDoubleFunction IntIntDoubleFunction

List of usage examples for org.apache.mahout.math.function IntIntDoubleFunction IntIntDoubleFunction

Introduction

In this page you can find the example usage for org.apache.mahout.math.function IntIntDoubleFunction IntIntDoubleFunction.

Prototype

IntIntDoubleFunction

Source Link

Usage

From source file:org.carrot2.matrix.MatrixUtils.java

License:Open Source License

/**
 * Normalizes column vectors of a sparse matrix <code>A</code> so that their L2 norm
 * (Euclidean distance) is equal to 1.0.
 * /*  w ww.  j a v  a  2  s  . c  o  m*/
 * @param A matrix to normalize
 * @param work a temporary array of <code>A.columns()</code> doubles that will be
 *            overwritten with column's original L2 norms. Supply a non-null pointer
 *            to avoid continuous allocation/freeing of memory when doing calculations
 *            in a loop. If this parameter is <code>null</code>, a new array will be
 *            allocated every time this method is called.
 * @return A with length-normalized columns (for convenience only)
 */
public static DoubleMatrix2D normalizeSparseColumnL2(final DoubleMatrix2D A, final double[] work) {
    final double[] w = prepareWork(A, work);

    A.forEachNonZero(new IntIntDoubleFunction() {
        @Override
        public double apply(int row, int column, double value) {
            w[column] += value * value;
            return value;
        }
    });

    // Take the square root
    for (int c = 0; c < A.columns(); c++) {
        w[c] = Math.sqrt(w[c]);
    }

    // Normalize
    A.forEachNonZero(new IntIntDoubleFunction() {
        @Override
        public double apply(int row, int column, double value) {
            A.setQuick(row, column, value / w[column]);
            return 0;
        }
    });

    return A;
}