probability

# Probability¶

## Hot Hands¶

Basketball players who make several baskets in succession are described as having a hot hand. Fans and players have long believed in the hot hand phenomenon, which refutes the assumption that each shot is independent of the next. However, a 1985 paper by Gilovich, Vallone, and Tversky collected evidence that contradicted this belief and showed that successive shots are independent events (http://www.cs.colorado.edu/~mozer/Teaching/syllabi/7782/readings/gilovich%20vallone%20tversky.pdf). This paper started a great controversy that continues to this day, as you can see by Googling hot hand basketball.

We do not expect to resolve this controversy today. However, in this lab we’ll apply one approach to answering questions like this. The goals for this lab are to (1) think about the effects of independent and dependent events, (2) learn how to simulate shooting streaks in Python, and (3) to compare a simulation to actual data in order to determine if the hot hand phenomenon appears to be real.

In :
# for Mac OS users only!
# if you run into any SSL certification issues,
# you may need to run the following command for a Mac OS installation.
# \$/Applications/Python 3.x/Install Certificates.command
import os, ssl
if (not os.environ.get('PYTHONHTTPSVERIFY', '') and
getattr(ssl, '_create_unverified_context', None)):
ssl._create_default_https_context = ssl._create_unverified_context


## Getting started¶

Our investigation will focus on the performance of one player: Kobe Bryant of the Los Angeles Lakers. His performance against the Orlando Magic in the 2009 NBA finals earned him the title Most Valuable Player and many spectators commented on how he appeared to show a hot hand. Let’s load some data from those games and look at the first several rows.

In :
import pandas as pd


Out:
vs game quarter time description basket
0 ORL 1 1 9:47 Kobe Bryant makes 4-foot two point shot H
1 ORL 1 1 9:07 Kobe Bryant misses jumper M
2 ORL 1 1 8:11 Kobe Bryant misses 7-foot jumper M
3 ORL 1 1 7:41 Kobe Bryant makes 16-foot jumper (Derek Fisher... H
4 ORL 1 1 7:03 Kobe Bryant makes driving layup H

In this data frame, every row records a shot taken by Kobe Bryant. If he hit the shot (made a basket), a hit, H, is recorded in the column named basket, otherwise a miss, M, is recorded.

Just looking at the string of hits and misses, it can be difficult to gauge whether or not it seems like Kobe was shooting with a hot hand. One way we can approach this is by considering the belief that hot hand shooters tend to go on shooting streaks. For this lab, we define the length of a shooting streak to be the number of consecutive baskets made until a miss occurs.

For example, in Game 1 Kobe had the following sequence of hits and misses from his nine shot attempts in the first quarter:

##### H M | M | H H M | M | M | M¶

To verify this use the following command:

In :
kobe['basket'][0:9]

Out:
0    H
1    M
2    M
3    H
4    H
5    M
6    M
7    M
8    M
Name: basket, dtype: object

Within the nine shot attempts, there are six streaks, which are separated by a "|" above. Their lengths are one, zero, two, zero, zero, zero (in order of occurrence).

#### Exercise 1

What does a streak length of 1 mean, i.e. how many hits and misses are in a streak of 1? What about a streak length of 0?

The custom function calc_streak() can be used to calculate the lengths of all shooting streaks.

In :
import numpy as np

def calc_streak(x):
y = np.zeros(len(x))
y[x == 'H'] = 1
y = np.insert(y, 0, 0)
y = np.append(y, 0)
wz = np.where(y == 0)
streak = np.diff(wz) - 1
streak = streak.flatten() # return a copy of the array collapsed into one dimension.
return streak

print(kobe_streak)

[1 0 2 0 0 0 3 2 0 3 0 1 3 0 0 0 0 0 1 1 0 4 1 0 1 0 1 0 1 2 0 1 2 1 0 0 1
0 0 0 1 1 0 1 0 2 0 0 0 3 0 1 0 1 2 1 0 1 0 0 1 3 3 1 1 0 0 0 0 0 1 1 0 0
0 1]

In :
import matplotlib.pyplot as plt
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
plt.style.use('ggplot')
plt.rcParams['figure.figsize'] = (10,5)

kobe_streak_counts = np.asarray(np.unique(kobe_streak, return_counts = True))
kobe_streak_counts = pd.DataFrame(data = kobe_streak_counts[1,], index = kobe_streak_counts[0,])

kobe_streak_counts.plot(kind = 'bar', legend = False)
plt.show(); Note that instead of making a histogram, we chose to make a bar plot.. A bar plot is preferable here since our variable is discrete – counts – instead of continuous.

#### Exercise 2

Describe the distribution of Kobe's streak lengths from the 2009 NBA finals. What was his typical streak length? How long was his longest streak of baskets?

## Compared to What?¶

We’ve shown that Kobe had some long shooting streaks, but are they long enough to support the belief that he had hot hands? What can we compare them to?

To answer these questions, let’s return to the idea of independence. Two processes are independent if the outcome of one process doesn’t effect the outcome of the second. If each shot that a player takes is an independent process, having made or missed your first shot will not affect the probability that you will make or miss your second shot.

A shooter with a hot hand will have shots that are not independent of one another. Specifically, if the shooter makes his first shot, the hot hand model says he will have a higher probability of making his second shot.

Let’s suppose for a moment that the hot hand model is valid for Kobe. During his career, the percentage of time Kobe makes a basket (i.e. his shooting percentage) is about 45%, or in probability notation,

#### P(shot 1 = H) = 0.45¶

If he makes the first shot and has a hot hand (not independent shots), then the probability that he makes his second shot would go up to, let’s say, 60%,

#### P(shot 2 = H|shot 1 = H) = 0.60¶

As a result of these increased probabilites, you’d expect Kobe to have longer streaks. Compare this to the skeptical perspective where Kobe does not have a hot hand, where each shot is independent of the next. If he hit his first shot, the probability that he makes the second is still 0.45.

#### P(shot 2 = H|shot 1 = H) = 0.45¶

In other words, making the first shot did nothing to effect the probability that he’d make his second shot. If Kobe’s shots are independent, then he’d have the same probability of hitting every shot regardless of his past shots: 45%.

Now that we’ve phrased the situation in terms of independent shots, let’s return to the question: how do we tell if Kobe’s shooting streaks are long enough to indicate that he has hot hands? We can compare his streak lengths to someone without hot hands: an independent shooter.

## Simulations in Python¶

While we don't have any data from a shooter we know to have independent shots, that sort of data is very easy to simulate in Python. In a simulation, you set the ground rules of a random process and then the computer uses random numbers to generate an outcome that adheres to those rules. As a simple example, you can simulate flipping a fair coin with the following:

In :
outcomes = np.array(['heads', 'tails'])
print(np.random.choice(outcomes, size = 1, replace = True))

['heads']


The vector outcomes can be thought of as a hat with two slips of paper in it: one slip says heads and the other says tails. The function random.choice() draws one slip from the hat and tells us if it was a head or a tail.

Run the second command listed above several times. Just like when flipping a coin, sometimes you’ll get a heads, sometimes you’ll get a tails, but in the long run, you’d expect to get roughly equal numbers of each.

If you wanted to simulate flipping a fair coin 100 times, you could either run the function 100 times or, more simply, adjust the size argument, which governs how many samples to draw (the replace = True argument indicates we put the slip of paper back in the hat before drawing again). Save the resulting array of heads and tails in a new object called sim_fair_coin.

In :
sim_fair_coin = np.random.choice(outcomes, size = 100, replace = True)


To view the results of this simulation, use unique() to count up the number of heads and tails:

In :
unique, counts = np.unique(sim_fair_coin, return_counts = True)
print(np.asarray((unique, counts)).T)

[['heads' '52']
['tails' '48']]


Since there are only two elements in outcomes, the probability that we "flip" a coin and it lands heads is 0.5. Say we’re trying to simulate an unfair coin that we know only lands heads 20% of the time. We can adjust for this by adding an argument called p, which provides the probabilities associated with each entry in the array.

In :
sim_unfair_coin = np.random.choice(outcomes, size = 100, replace = True, p = [0.2, 0.8])
unique, counts = np.unique(sim_unfair_coin, return_counts = True)
print(np.asarray((unique, counts)).T)

[['heads' '20']
['tails' '80']]


p = [0.2, 0.8] indicates that for the two elements in the outcomes array, we want to select the first one, heads with probability 0.2 and the second one, tails with probability 0.8. Another way of thinking about this is to think of the outcome space as a bag of 10 chips, where 2 chips are labeled "head" and 8 chips "tail". Therefore at each draw, the probability of drawing a chip that says "head" is 20%, and "tail" is 80%.

#### Exercise 3

In your simulation of flipping the unfair coin 100 times, how many flips came up heads?

In a sense, we've shrunken the size of the slip of paper that says "heads", making it less likely to be drawn and we've increased the size of the slip of paper saying "tails", making it more likely to be drawn. When we simulated the fair coin, both slips of paper were the same size. This happens by default if you don't provide a p argument; all elements in the outcomes array have an equal probability of being drawn.

## Simulating the Independent Shooter¶

Simulating a basketball player who has independent shots uses the same mechanism that we use to simulate a coin flip. To simulate a single shot from an independent shooter with a shooting percentage of 50% we type,

In :
outcomes = np.array(['H', 'M'])
sim_basket = np.random.choice(outcomes, size = 1, replace = True)


To make a valid comparison between Kobe and our simulated independent shooter, we need to align both their shooting percentage and the number of attempted shots.

#### Exercise 4

What change needs to be made to the random.choice() function so that it reflects a shooting percentage of 45%? Make this adjustment, then run a simulation to sample 133 shots. Assign the output of this simulation to a new object called sim_basket.

Note that we've named the new vector sim_basket, the same name that we gave to the previous array reflecting a shooting percentage of 50%. In this situation, Python overwrites the old object with the new one, so always make sure that you don't need the information in an old array before reassigning its name.

With the results of the simulation saved as sim_basket, we have the data necessary to compare Kobe to our independent shooter. We can look at Kobe's data alongside our simulated data.

In :
kobe['basket']

Out:
0      H
1      M
2      M
3      H
4      H
5      M
6      M
7      M
8      M
9      H
10     H
11     H
12     M
13     H
14     H
15     M
16     M
17     H
18     H
19     H
20     M
21     M
22     H
23     M
24     H
25     H
26     H
27     M
28     M
29     M
..
103    M
104    M
105    M
106    H
107    M
108    H
109    H
110    H
111    M
112    H
113    H
114    H
115    M
116    H
117    M
118    H
119    M
120    M
121    M
122    M
123    M
124    M
125    H
126    M
127    H
128    M
129    M
130    M
131    M
132    H
Name: basket, Length: 133, dtype: object
In :
print(sim_basket)

['M']


Both data sets represent the results of 133 shot attempts, each with the same shooting percentage of 45%. We know that our simulated data is from a shooter that has independent shots. That is, we know the simulated shooter does not have a hot hand.

Using calc_streak(), compute the streak lengths of sim_basket.