Algorithms Exercise 3

Imports


In [37]:
%matplotlib inline
from matplotlib import pyplot as plt
import numpy as np

In [38]:
from IPython.html.widgets import interact


:0: FutureWarning: IPython widgets are experimental and may change in the future.

Character counting and entropy

Write a function char_probs that takes a string and computes the probabilities of each character in the string:

  • First do a character count and store the result in a dictionary.
  • Then divide each character counts by the total number of character to compute the normalized probabilties.
  • Return the dictionary of characters (keys) and probabilities (values).

In [39]:
def char_probs(s):
    """Find the probabilities of the unique characters in the string s.
    
    Parameters
    ----------
    s : str
        A string of characters.
    
    Returns
    -------
    probs : dict
        A dictionary whose keys are the unique characters in s and whose values
        are the probabilities of those characters.
    """
    diction=dict((x,s.count(x)/len(s)) for x in s)
    return(diction)

In [42]:
a=char_probs("abcd")

In [43]:
test1 = char_probs('aaaa')
assert np.allclose(test1['a'], 1.0)
test2 = char_probs('aabb')
assert np.allclose(test2['a'], 0.5)
assert np.allclose(test2['b'], 0.5)
test3 = char_probs('abcd')
assert np.allclose(test3['a'], 0.25)
assert np.allclose(test3['b'], 0.25)
assert np.allclose(test3['c'], 0.25)
assert np.allclose(test3['d'], 0.25)

The entropy is a quantiative measure of the disorder of a probability distribution. It is used extensively in Physics, Statistics, Machine Learning, Computer Science and Information Science. Given a set of probabilities $P_i$, the entropy is defined as:

$$H = - \Sigma_i P_i \log_2(P_i)$$

In this expression $\log_2$ is the base 2 log (np.log2), which is commonly used in information science. In Physics the natural log is often used in the definition of entropy.

Write a funtion entropy that computes the entropy of a probability distribution. The probability distribution will be passed as a Python dict: the values in the dict will be the probabilities.

To compute the entropy, you should:

  • First convert the values (probabilities) of the dict to a Numpy array of probabilities.
  • Then use other Numpy functions (np.log2, etc.) to compute the entropy.
  • Don't use any for or while loops in your code.

In [94]:
def entropy(d):
    """Compute the entropy of a dict d whose values are probabilities."""
    a=np.array(d) 
    h=0-(np.sum(d*np.log2(d)))
    return h

In [95]:
entropy([1])


Out[95]:
0.0

In [89]:
assert np.allclose(entropy({'a': 0.5, 'b': 0.5}), 1.0)
assert np.allclose(entropy({'a': 1.0}), 0.0)


['a', 'b']
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-89-2b809aa64202> in <module>()
----> 1 assert np.allclose(entropy({'a': 0.5, 'b': 0.5}), 1.0)
      2 assert np.allclose(entropy({'a': 1.0}), 0.0)

<ipython-input-87-9f919f5aeb7a> in entropy(d)
      4     print(d)
      5     a=np.array(d)
----> 6     h=0-(np.sum(d*np.log2(d)))
      7     h=int(h)
      8     return h

TypeError: Not implemented for this type

Use IPython's interact function to create a user interface that allows you to type a string into a text box and see the entropy of the character probabilities of the string.


In [96]:
def interface(d):
    a=char_probs(d)
    return entropy(a)
interact(interface,d='Type Here')


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-96-639289099523> in interface(d)
      1 def interface(d):
      2     a=char_probs(d)
----> 3     return entropy(a)
      4 interact(interface,d='Type Here')

<ipython-input-94-76d6136bab1c> in entropy(d)
      2     """Compute the entropy of a dict d whose values are probabilities."""
      3     a=np.array(d)
----> 4     h=0-(np.sum(d*np.log2(d)))
      5     return h
      6 

AttributeError: 'dict' object has no attribute 'log2'
Out[96]:
<function __main__.interface>

In [ ]:
assert True # use this for grading the pi digits histogram