# GLM: Logistic Regression¶

- This is a reproduction with a few slight alterations of Bayesian Log Reg by J. Benjamin Cook
- Author: Peadar Coyle and J. Benjamin Cook
- How likely am I to make more than $50,000 US Dollars?
- Exploration of model selection techniques too - I use WAIC to select the best model.
- The convenience functions are all taken from Jon Sedars work.
- This example also has some explorations of the features so serves as a good example of Exploratory Data Analysis and how that can guide the model creation/ model selection process.

```
In [1]:
```

```
%matplotlib inline
import pandas as pd
import numpy as np
import pymc3 as pm
import matplotlib.pyplot as plt
import seaborn
import warnings
warnings.filterwarnings('ignore')
from collections import OrderedDict
from time import time
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.optimize import fmin_powell
from scipy import integrate
import theano as thno
import theano.tensor as T
```

```
In [2]:
```

```
def run_models(df, upper_order=5):
'''
Convenience function:
Fit a range of pymc3 models of increasing polynomial complexity.
Suggest limit to max order 5 since calculation time is exponential.
'''
models, traces = OrderedDict(), OrderedDict()
for k in range(1,upper_order+1):
nm = 'k{}'.format(k)
fml = create_poly_modelspec(k)
with pm.Model() as models[nm]:
print('\nRunning: {}'.format(nm))
pm.glm.GLM.from_formula(fml, df,
family=pm.glm.families.Binomial())
traces[nm] = pm.sample(1000, tune=1000, init='adapt_diag')
return models, traces
def plot_traces(traces, retain=0):
'''
Convenience function:
Plot traces with overlaid means and values
'''
ax = pm.traceplot(traces[-retain:],
lines=tuple([(k, {}, v['mean'])
for k, v in pm.summary(traces[-retain:]).iterrows()]))
for i, mn in enumerate(pm.summary(traces[-retain:])['mean']):
ax[i,0].annotate('{:.2f}'.format(mn), xy=(mn,0), xycoords='data'
,xytext=(5,10), textcoords='offset points', rotation=90
,va='bottom', fontsize='large', color='#AA0022')
def create_poly_modelspec(k=1):
'''
Convenience function:
Create a polynomial modelspec string for patsy
'''
return ('income ~ educ + hours + age ' + ' '.join(['+ np.power(age,{})'.format(j)
for j in range(2,k+1)])).strip()
```

The Adult Data Set is commonly used to benchmark machine learning algorithms. The goal is to use demographic features, or variables, to predict whether an individual makes more than \$50,000 per year. The data set is almost 20 years old, and therefore, not perfect for determining the probability that I will make more than $50K, but it is a nice, simple dataset that can be used to showcase a few benefits of using Bayesian logistic regression over its frequentist counterpart.

The motivation for myself to reproduce this piece of work was to learn how to use Odd Ratio in Bayesian Regression.

```
In [3]:
```

```
raw_data = pd.read_csv("https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data",
header=None,
names=['age', 'workclass', 'fnlwgt',
'education-categorical', 'educ',
'marital-status', 'occupation',
'relationship', 'race', 'sex',
'captial-gain', 'capital-loss',
'hours', 'native-country',
'income'])
```

```
In [4]:
```

```
raw_data.head(10)
```

```
Out[4]:
```

age | workclass | fnlwgt | education-categorical | educ | marital-status | occupation | relationship | race | sex | captial-gain | capital-loss | hours | native-country | income | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|

0 | 39 | State-gov | 77516 | Bachelors | 13 | Never-married | Adm-clerical | Not-in-family | White | Male | 2174 | 0 | 40 | United-States | <=50K |

1 | 50 | Self-emp-not-inc | 83311 | Bachelors | 13 | Married-civ-spouse | Exec-managerial | Husband | White | Male | 0 | 0 | 13 | United-States | <=50K |

2 | 38 | Private | 215646 | HS-grad | 9 | Divorced | Handlers-cleaners | Not-in-family | White | Male | 0 | 0 | 40 | United-States | <=50K |

3 | 53 | Private | 234721 | 11th | 7 | Married-civ-spouse | Handlers-cleaners | Husband | Black | Male | 0 | 0 | 40 | United-States | <=50K |

4 | 28 | Private | 338409 | Bachelors | 13 | Married-civ-spouse | Prof-specialty | Wife | Black | Female | 0 | 0 | 40 | Cuba | <=50K |

5 | 37 | Private | 284582 | Masters | 14 | Married-civ-spouse | Exec-managerial | Wife | White | Female | 0 | 0 | 40 | United-States | <=50K |

6 | 49 | Private | 160187 | 9th | 5 | Married-spouse-absent | Other-service | Not-in-family | Black | Female | 0 | 0 | 16 | Jamaica | <=50K |

7 | 52 | Self-emp-not-inc | 209642 | HS-grad | 9 | Married-civ-spouse | Exec-managerial | Husband | White | Male | 0 | 0 | 45 | United-States | >50K |

8 | 31 | Private | 45781 | Masters | 14 | Never-married | Prof-specialty | Not-in-family | White | Female | 14084 | 0 | 50 | United-States | >50K |

9 | 42 | Private | 159449 | Bachelors | 13 | Married-civ-spouse | Exec-managerial | Husband | White | Male | 5178 | 0 | 40 | United-States | >50K |

## Scrubbing and cleaning¶

We need to remove any null entries in Income. And we also want to restrict this study to the United States.

```
In [5]:
```

```
data = raw_data[~pd.isnull(raw_data['income'])]
```

```
In [6]:
```

```
data[data['native-country']==" United-States"].sample(5)
```

```
Out[6]:
```

age | workclass | fnlwgt | education-categorical | educ | marital-status | occupation | relationship | race | sex | captial-gain | capital-loss | hours | native-country | income | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|

8868 | 40 | Private | 390369 | HS-grad | 9 | Divorced | Craft-repair | Own-child | White | Male | 0 | 0 | 40 | United-States | <=50K |

2693 | 24 | Private | 145964 | Bachelors | 13 | Never-married | Exec-managerial | Not-in-family | White | Male | 0 | 0 | 40 | United-States | <=50K |

28530 | 60 | Local-gov | 101110 | Assoc-voc | 11 | Divorced | Prof-specialty | Unmarried | White | Male | 0 | 0 | 40 | United-States | >50K |

12561 | 45 | Private | 190088 | HS-grad | 9 | Married-spouse-absent | Adm-clerical | Unmarried | White | Female | 0 | 0 | 30 | United-States | <=50K |

13542 | 74 | Private | 145463 | 1st-4th | 2 | Widowed | Priv-house-serv | Not-in-family | Black | Female | 0 | 0 | 15 | United-States | <=50K |

```
In [7]:
```

```
income = 1 * (data['income'] == " >50K")
```

```
In [8]:
```

```
data = data[['age', 'educ', 'hours']]
# Scale age by 10, it helps with model convergence.
data['age'] = data['age']/10.
data['age2'] = np.square(data['age'])
data['income'] = income
```

```
In [9]:
```

```
income.value_counts()
```

```
Out[9]:
```

```
0 24720
1 7841
Name: income, dtype: int64
```

## Exploring the data¶

Let us get a feel for the parameters. * We see that age is a tailed distribution. Certainly not Gaussian! * We don’t see much of a correlation between many of the features, with the exception of Age and Age2. * Hours worked has some interesting behaviour. How would one describe this distribution?

```
In [10]:
```

```
g = seaborn.pairplot(data)
```

```
In [11]:
```

```
# Compute the correlation matrix
corr = data.corr()
# Generate a mask for the upper triangle
mask = np.zeros_like(corr, dtype=np.bool)
mask[np.triu_indices_from(mask)] = True
# Set up the matplotlib figure
f, ax = plt.subplots(figsize=(11, 9))
# Generate a custom diverging colormap
cmap = seaborn.diverging_palette(220, 10, as_cmap=True)
# Draw the heatmap with the mask and correct aspect ratio
seaborn.heatmap(corr, mask=mask, cmap=cmap, vmax=.3,
linewidths=.5, cbar_kws={"shrink": .5}, ax=ax);
```

We see here not many strong correlations. The highest is 0.30 according to this plot. We see a weak-correlation between hours and income (which is logical), we see a slighty stronger correlation between education and income (which is the kind of question we are answering).

## The model¶

We will use a simple model, which assumes that the probability of making more than $50K is a function of age, years of education and hours worked per week. We will use PyMC3 do inference.

In Bayesian statistics, we treat everything as a random variable and we want to know the posterior probability distribution of the parameters (in this case the regression coefficients) The posterior is equal to the likelihood

Because the denominator is a notoriously difficult integral, $p(D) = :raw-latex:`\int `p(D \| :raw-latex:`theta`) p(:raw-latex:`\theta`) d :raw-latex:`theta `$ we would prefer to skip computing it. Fortunately, if we draw examples from the parameter space, with probability proportional to the height of the posterior at any given point, we end up with an empirical distribution that converges to the posterior as the number of samples approaches infinity.

What this means in practice is that we only need to worry about the numerator.

Getting back to logistic regression, we need to specify a prior and a likelihood in order to draw samples from the posterior. We could use sociological knowledge about the effects of age and education on income, but instead, let’s use the default prior specification for GLM coefficients that PyMC3 gives us, which is \(p(θ)=N(0,10^{12}I)\). This is a very vague prior that will let the data speak for themselves.

The likelihood is the product of n Bernoulli trials, \(\prod^{n}_{i=1} p_{i}^{y} (1 - p_{i})^{1-y_{i}}\), where \(p_i = \frac{1}{1 + e^{-z_i}}\),

\(z_{i} = \beta_{0} + \beta_{1}(age)_{i} + \beta_2(age)^{2}_{i} + \beta_{3}(educ)_{i} + \beta_{4}(hours)_{i}\) and \(y_{i} = 1\) if income is greater than 50K and \(y_{i} = 0\) otherwise.

With the math out of the way we can get back to the data. Here I use PyMC3 to draw samples from the posterior. The sampling algorithm used is NUTS, which is a form of Hamiltonian Monte Carlo, in which parameteres are tuned automatically. Notice, that we get to borrow the syntax of specifying GLM’s from R, very convenient! I use a convenience function from above to plot the trace infromation from the first 1000 parameters.

```
In [12]:
```

```
with pm.Model() as logistic_model:
pm.glm.GLM.from_formula('income ~ age + age2 + educ + hours',
data,
family=pm.glm.families.Binomial())
trace = pm.sample(1000, tune=1000, init='adapt_diag')
```

```
Auto-assigning NUTS sampler...
Initializing NUTS using adapt_diag...
Multiprocess sampling (2 chains in 2 jobs)
NUTS: [hours, educ, age2, age, Intercept]
Sampling 2 chains: 100%|██████████| 4000/4000 [15:04<00:00, 3.06draws/s]
```

```
In [14]:
```

```
plot_traces(trace);
```

## Some results¶

One of the major benefits that makes Bayesian data analysis worth the extra computational effort in many circumstances is that we can be explicit about our uncertainty. Maximum likelihood returns a number, but how certain can we be that we found the right number? Instead, Bayesian inference returns a distribution over parameter values.

I’ll use seaborn to look at the distribution of some of these factors.

```
In [15]:
```

```
plt.figure(figsize=(9,7))
seaborn.jointplot(trace['age'], trace['educ'], kind="hex", color="#4CB391")
plt.xlabel("beta_age")
plt.ylabel("beta_educ");
```

```
<Figure size 648x504 with 0 Axes>
```

So how do age and education affect the probability of making more than $\(50K?\) To answer this question, we can show how the probability of making more than $50K changes with age for a few different education levels. Here, we assume that the number of hours worked per week is fixed at 50. PyMC3 gives us a convenient way to plot the posterior predictive distribution. We need to give the function a linear model and a set of points to evaluate. We will pass in three different linear models: one with educ == 12 (finished high school), one with educ == 16 (finished undergrad) and one with educ == 19 (three years of grad school).

```
In [16]:
```

```
def lm_full(trace, age, educ, hours):
shape = np.broadcast(age, educ, hours).shape
x_norm = np.asarray([np.broadcast_to(x, shape)
for x in [age/10., educ, hours]])
return 1 / (1 + np.exp(-(trace['Intercept'] +
trace['age']*x_norm[0] +
trace['age2']*(x_norm[0]**2) +
trace['educ']*x_norm[1] +
trace['hours']*x_norm[2])))
# Linear model with hours == 50 and educ == 12
lm = lambda x, samples: lm_full(samples, x, 12., 50.)
# Linear model with hours == 50 and educ == 16
lm2 = lambda x, samples: lm_full(samples, x, 16., 50.)
# Linear model with hours == 50 and educ == 19
lm3 = lambda x, samples: lm_full(samples, x, 19., 50.)
```

Each curve shows how the probability of earning more than $ 50K$ changes with age. The red curve represents 19 years of education, the green curve represents 16 years of education and the blue curve represents 12 years of education. For all three education levels, the probability of making more than $50K increases with age until approximately age 60, when the probability begins to drop off. Notice that each curve is a little blurry. This is because we are actually plotting 100 different curves for each level of education. Each curve is a draw from our posterior distribution. Because the curves are somewhat translucent, we can interpret dark, narrow portions of a curve as places where we have low uncertainty and light, spread out portions of the curve as places where we have somewhat higher uncertainty about our coefficient values.

```
In [17]:
```

```
# Plot the posterior predictive distributions of P(income > $50K) vs. age
pm.plot_posterior_predictive_glm(trace, eval=np.linspace(
25, 75, 1000), lm=lm, samples=100, color="blue", alpha=.15)
pm.plot_posterior_predictive_glm(trace, eval=np.linspace(
25, 75, 1000), lm=lm2, samples=100, color="green", alpha=.15)
pm.plot_posterior_predictive_glm(trace, eval=np.linspace(
25, 75, 1000), lm=lm3, samples=100, color="red", alpha=.15)
import matplotlib.lines as mlines
blue_line = mlines.Line2D(['lm'], [], color='b', label='High School Education')
green_line = mlines.Line2D(['lm2'], [], color='g', label='Bachelors')
red_line = mlines.Line2D(['lm3'], [], color='r', label='Grad School')
plt.legend(handles=[blue_line, green_line, red_line], loc='lower right')
plt.ylabel("P(Income > $50K)")
plt.xlabel("Age")
plt.show()
```

```
In [18]:
```

```
b = trace['educ']
plt.hist(np.exp(b), bins=20, normed=True)
plt.xlabel("Odds Ratio")
plt.show()
```

Finally, we can find a credible interval (remember kids - credible intervals are Bayesian and confidence intervals are frequentist) for this quantity. This may be the best part about Bayesian statistics: we get to interpret credibility intervals the way we’ve always wanted to interpret them. We are 95% confident that the odds ratio lies within our interval!

```
In [19]:
```

```
lb, ub = np.percentile(b, 2.5), np.percentile(b, 97.5)
print("P(%.3f < O.R. < %.3f) = 0.95" % (np.exp(lb),np.exp(ub)))
```

```
P(1.377 < O.R. < 1.414) = 0.95
```

## Model selection¶

One question that was immediately asked was what effect does age have on the model, and why should it be \(age^2\) versus age? We’ll run the model with a few changes to see what effect higher order terms have on this model in terms of WAIC.

```
In [20]:
```

```
models_lin, traces_lin = run_models(data, 3)
```

```
Running: k1
```

```
Auto-assigning NUTS sampler...
Initializing NUTS using adapt_diag...
Multiprocess sampling (2 chains in 2 jobs)
NUTS: [age, hours, educ, Intercept]
Sampling 2 chains: 100%|██████████| 4000/4000 [05:01<00:00, 6.39draws/s]
```

```
Running: k2
```

```
Auto-assigning NUTS sampler...
Initializing NUTS using adapt_diag...
Multiprocess sampling (2 chains in 2 jobs)
NUTS: [np.power(age, 2), age, hours, educ, Intercept]
Sampling 2 chains: 100%|██████████| 4000/4000 [16:13<00:00, 3.05draws/s]
```

```
Running: k3
```

```
Auto-assigning NUTS sampler...
Initializing NUTS using adapt_diag...
Multiprocess sampling (2 chains in 2 jobs)
NUTS: [np.power(age, 3), np.power(age, 2), age, hours, educ, Intercept]
Sampling 2 chains: 100%|██████████| 4000/4000 [56:48<00:00, 1.12s/draws]
```

```
In [21]:
```

```
model_trace_dict = dict()
for nm in ['k1', 'k2', 'k3']:
models_lin[nm].name = nm
model_trace_dict.update({models_lin[nm]: traces_lin[nm]})
dfwaic = pm.compare(model_trace_dict, ic='WAIC')
pm.compareplot(dfwaic);
```

```
Out[21]:
```

```
<matplotlib.axes._subplots.AxesSubplot at 0x7ff70d0d9ac8>
```

WAIC confirms our decision to use age^2.