Wednesday, April 26, 2017

Python as a way of thinking

This article contains supporting material for this blog post at Scientific American. The thesis of the post is that modern programming languages (like Python) are qualitatively different from the first generation (like FORTRAN and C), in ways that make them effective tools for teaching, learning, exploring, and thinking.

I presented a longer version of this argument in a talk I presented at Olin College last fall. The slides are here:

Here are Jupyter notebooks with the code examples I mentioned in the talk:

A counter is a map from values to their frequencies. If you initialize a counter with a string, you get a map from each letter to the number of times it appears. If two words are anagrams, they yield equal Counters, so you can use Counters to test anagrams in linear time.

Multisets
A Counter is a natural representation of a multiset, which is a set where the elements can appear more than once. You can extend Counter with set operations like is_subset:

In [6]:

classMultiset(Counter):"""A multiset is a set where elements can appear more than once."""defis_subset(self,other):"""Checks whether self is a subset of other. other: Multiset returns: boolean """forchar,countinself.items():ifother[char]<count:returnFalsereturnTrue# map the <= operator to is_subset__le__=is_subset

You could use is_subset in a game like Scrabble to see if a given set of tiles can be used to spell a given word.

You can also extend Counter to represent a probability mass function (PMF).normalize computes the total of the frequencies and divides through, yielding probabilities that add to 1.__add__ enumerates all pairs of value and returns a new Pmf that represents the distribution of the sum.__hash__ and __id__ make Pmfs hashable; this is not the best way to do it, because they are mutable. So this implementation comes with a warning that if you use a Pmf as a key, you should not modify it. A better alternative would be to define a frozen Pmf.render returns the values and probabilities in a form ready for plotting

In [9]:

classPmf(Counter):"""A Counter with probabilities."""defnormalize(self):"""Normalizes the PMF so the probabilities add to 1."""total=float(sum(self.values()))forkeyinself:self[key]/=totaldef__add__(self,other):"""Adds two distributions. The result is the distribution of sums of values from the two distributions. other: Pmf returns: new Pmf """pmf=Pmf()forkey1,prob1inself.items():forkey2,prob2inother.items():pmf[key1+key2]+=prob1*prob2returnpmfdef__hash__(self):"""Returns an integer hash value."""returnid(self)def__eq__(self,other):returnselfisotherdefrender(self):"""Returns values and their probabilities, suitable for plotting."""returnzip(*sorted(self.items()))

As an example, we can make a Pmf object that represents a 6-sided die.

Using numpy.sum, we can compute the distribution for the sum of three dice.

In [14]:

# if we use the built-in sum we have to provide a Pmf additive identity value# pmf_ident = Pmf([0])# d6_thrice = sum([d6]*3, pmf_ident)# with np.sum, we don't need an identityd6_thrice=np.sum([d6,d6,d6])d6_thrice.name='three dice'

A Suite is a Pmf that represents a set of hypotheses and their probabilities; it provides bayesian_update, which updates the probability of the hypotheses based on new data.
Suite is an abstract parent class; child classes should provide a likelihood method that evaluates the likelihood of the data under a given hypothesis. update_bayesian loops through the hypothesis, evaluates the likelihood of the data under each hypothesis, and updates the probabilities accordingly. Then it re-normalizes the PMF.

In [21]:

classSuite(Pmf):"""Map from hypothesis to probability."""defbayesian_update(self,data):"""Performs a Bayesian update. Note: called bayesian_update to avoid overriding dict.update data: result of a die roll """forhypoinself:like=self.likelihood(data,hypo)self[hypo]*=likeself.normalize()

As an example, I'll use Suite to solve the "Dice Problem," from Chapter 3 of Think Bayes.
"Suppose I have a box of dice that contains a 4-sided die, a 6-sided die, an 8-sided die, a 12-sided die, and a 20-sided die. If you have ever played Dungeons & Dragons, you know what I am talking about. Suppose I select a die from the box at random, roll it, and get a 6. What is the probability that I rolled each die?"
I'll start by making a list of Pmfs to represent the dice:

Next I'll define DiceSuite, which inherits bayesian_update from Suite and provides likelihood.data is the observed die roll, 6 in the example.hypo is the hypothetical die I might have rolled; to get the likelihood of the data, I select, from the given die, the probability of the given value.

In [26]:

classDiceSuite(Suite):deflikelihood(self,data,hypo):"""Computes the likelihood of the data under the hypothesis. data: result of a die roll hypo: Pmf object representing a die """returnhypo[data]

Finally, I use the list of dice to instantiate a Suite that maps from each die to its prior probability. By default, all dice have the same prior.
Then I update the distribution with the given value and print the results:

As expected, the 4-sided die has been eliminated; it now has 0 probability. The 6-sided die is the most likely, but the 8-sided die is still quite possible.
Now suppose I roll the die again and get an 8. We can update the Suite again with the new data

Now the 6-sided die has been eliminated, the 8-sided die is most likely, and there is less than a 10% chance that I am rolling a 20-sided die.
These examples demonstrate the versatility of the Counter class, one of Python's underused data structures.