#!/usr/local/bin/perl -w # report the mutual information between two variables # expected input is a joint distribution, e.g. # # 1 1 # 1 0 # # or # 80 7 3 # 0 7 3 # $verbose = 1 ; $laplace = 0 ; $row = 0 ; if ( $verbose ) { printf "Mutual information between X (horizontal) and Y (vertical)\n" ; } $py[0] = 0 ; # total counts READROWS: while( <> ) { s/^\s*// ; ( @counts ) = split ; if ( $#counts <= 0 ) { print "skipping this - $_" ;next READROWS ; } $row ++ ; if ($row==1) { $W = $#counts + 1; # this first row is the marginal } else { if ($W!=$#counts+1) { print "warning $W!=$#counts\n" ; } } $c = 0 ; foreach $count ( @counts ) { $c += ($count+$laplace) ; } $py[$row] = $c ; $py[0] += $c ; $w = 0 ; $h = 0 ; foreach $count ( @counts ) { $w ++ ; if ( $row == 1 ) { $px[$w] = ($count+$laplace) ; } else { $px[$w] += ($count+$laplace) ; } if ( $c >= 0.0 ) { # $x = ($count+$laplace)/$c ; } else { $x = 0.0 ; } $l = 0.0 ; if ( $x > 0.0 ) { $l = - log ($x) / log ( 2.0 ) ; $h += $x * $l ; # conditional entropy H(X|y) } } printf " H(X|y=%d) = %9.6f\n", $row , $h ; $Hxgy[$row] = $h ; } $rows = $row ; # # once we have finished all rows, find H(rows) and add up # print "\n$rows rows, " ; print "$W columns. Total count $py[0]\n\n" ; # find H(X) print "marginal over X\n " ; $h = 0.0; for ( $w = 1 ; $w <= $W ; $w ++ ) { $px[$w] /= $py[0] ; $x = $px[$w] ; printf "%8.5f " , $x ; print "\n" if ( $w == $W ) ; $l = 0.0 ; if ( $x > 0.0 ) { $l = - log ($x) / log ( 2.0 ) ; $h += $x * $l ; # entropy H(X) } } $HX = $h ; print "marginal over Y\n " ; $h = 0.0; $HXgY = 0.0 ; for ( $row = 1 ; $row <= $rows ; $row ++ ) { $py[$row] /= $py[0] ; $x = $py[$row] ; printf "%8.5f " , $x ; print "\n" if ( $w == $W ) ; $l = 0.0 ; if ( $x > 0.0 ) { $l = - log ($x) / log ( 2.0 ) ; $h += $x * $l ; # entropy H(Y) } $HXgY += $x * $Hxgy[$row] ; # conditional entropy H(X|Y) } printf "\nconditional entropy H(X|Y) = %9.6f\n" , $HXgY ; printf "marginal entropy H(Y) = %9.6f\n" , $h ; printf "marginal entropy H(X) = %9.6f\n" , $HX ; $I = $HX - $HXgY ; printf "mutual information H(X;Y) = %9.6f\n" , $I ; exit(0);