calculate Entropy - Java java.lang

Java examples for java.lang:Math Algorithm

Description

calculate Entropy

Demo Code


//package com.java2s;
import java.util.HashMap;
import java.util.Map;

public class Main {
    public static double calculateEntropy(int[][] data, int startx,
            int starty, int endx, int endy) {
        // counting frequency
        int elementsCount = (endx - startx) * (endy - starty);
        Map<Integer, Integer> frequencyMap = new HashMap<Integer, Integer>();
        for (int row = startx; row < endx; ++row) {
            for (int col = starty; col < endy; ++col) {
                increaseCount(frequencyMap, data[row][col]);
            }/*from w  ww  .ja va  2 s  .c  o m*/
        }

        // probability is symbolCount/elementsCount
        // so counting entropy as summ(-p(x)*log(p(x))) where log base is two
        double result = 0;
        for (Integer symbolCount : frequencyMap.values()) {
            double p = (double) symbolCount / elementsCount;
            result -= p * log2(p);
        }

        return result;
    }

    private static void increaseCount(Map<Integer, Integer> data,
            int element) {
        Integer value = data.get(element);
        if (value == null) {
            value = new Integer(0);
            data.put(element, value);
        }
        data.put(element, ++value);
    }

    public static double log2(double num) {
        return (Math.log(num) / Math.log(2));
    }
}

Related Tutorials