Adults dataset
The adults dataset is comprised of census data from 1994 in United States.
The goal is to use demographic variables to predict whether an individual makes more than $50,000 per year.
The following is a description of the variables in the dataset.
- age: Individual’s age
- workclass: Labor class.
- fnlwgt: It is not specified, but we guess it is a final sampling weight.
- education: Education level as a categorical variable.
- educational_num: Education level as numerical variable. It does not reflect years of education.
- marital_status: Marital status.
- occupation: Occupation.
- relationship: Relationship with the head of household.
- race: Individual’s race.
- sex: Individual’s sex.
- capital_gain: Capital gain during unspecified period of time.
- capital_loss: Capital loss during unspecified period of time.
- hs_week: Hours of work per week.
- native_country: Country of birth.
- income: Income as a binary variable (either below or above 50K per year).
We are only using the following variables in this example: income, sex, race, age, and hs_week. This subset is comprised of both categorical and numerical variables which allows us to visualize how to incorporate both types in a logistic regression model while helping to keep the analysis simpler.
Code
%config InlineBackend.figure_format = "retina"
%config InlineBackend.print_figure_kwargs = {'bbox_inches': None}
import arviz as az
import bambi as bmb
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
plt.style.use("bambi.mplstyle")
seed = sum(map(ord, "model_comparison"))
rng = np.random.default_rng(seed)
data = bmb.load_data("adults")
data.info()
data.head()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 32561 entries, 0 to 32560
Data columns (total 5 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 income 32561 non-null object
1 sex 32561 non-null object
2 race 32561 non-null object
3 age 32561 non-null int64
4 hs_week 32561 non-null int64
dtypes: int64(2), object(3)
memory usage: 1.2+ MB
|
income |
sex |
race |
age |
hs_week |
| 0 |
<=50K |
Male |
White |
39 |
40 |
| 1 |
<=50K |
Male |
White |
50 |
13 |
| 2 |
<=50K |
Male |
White |
38 |
40 |
| 3 |
<=50K |
Male |
Black |
53 |
40 |
| 4 |
<=50K |
Female |
Black |
28 |
40 |
Categorical variables are presented as from type object. In this step we convert them to category.
data["age"] = data["age"].astype("float")
categorical_cols = data.columns[data.dtypes == object].tolist()
for col in categorical_cols:
data[col] = data[col].astype("category")
data.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 32561 entries, 0 to 32560
Data columns (total 5 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 income 32561 non-null category
1 sex 32561 non-null category
2 race 32561 non-null category
3 age 32561 non-null float64
4 hs_week 32561 non-null int64
dtypes: category(3), float64(1), int64(1)
memory usage: 604.7 KB
Instead of going straight to fitting models, we’re going to do a some exploratory analysis of the variables in the dataset. First we have some plots, and then some conclusions about the information in the plots.
# Just a utilitary function to truncate labels and avoid overlapping in plots
def truncate_labels(ticklabels, width=8):
def truncate(label, width):
if len(label) > width - 3:
return label[0 : (width - 4)] + "..."
else:
return label
labels = [truncate(lbl, width) for lbl in ticklabels]
return labels
fig, axes = plt.subplots(3, 2, figsize=(7, 8))
sns.countplot(x="income", color="C0", data=data, ax=axes[0, 0], saturation=1)
sns.countplot(x="sex", color="C0", data=data, ax=axes[0, 1], saturation=1)
sns.countplot(x="race", color="C0", data=data, ax=axes[1, 0], saturation=1)
axes[1, 0].set(
xticks=np.arange(len(data["race"].cat.categories)),
xticklabels=truncate_labels(data["race"].cat.categories),
)
axes[1, 1].hist(data["age"], bins=20)
axes[1, 1].set(xlabel="Age")
axes[2, 0].hist(data["hs_week"], bins=20)
axes[2, 0].set(xlabel="Hours of work / week")
axes[2, 1].axis("off");
Highlights
- Approximately 25% of the people make more than 50K a year.
- Two thirds of the subjects are males.
- The great majority of the subjects are white, only a minority are black and the other categories are very infrequent.
- The distribution of age is skewed to the right, as one might expect.
- The distribution of hours of work per week looks weird at first sight. But what is a typical workload per week? You got it, 40 hours :).
We only keep the races black and white to simplify the analysis. The other categories don’t appear very often in our data.
Now, we see the distribution of income for the different levels of our explanatory variables. Numerical variables are binned to make the analysis possible.
data = data[data["race"].isin(["Black", "White"])]
data["race"] = data["race"].cat.remove_unused_categories()
age_bins = [17, 25, 35, 45, 65, 90]
data["age_binned"] = pd.cut(data["age"], age_bins)
hours_bins = [0, 20, 40, 60, 100]
data["hs_week_binned"] = pd.cut(data["hs_week"], hours_bins)
fig, axes = plt.subplots(3, 2, figsize=(7, 6))
sns.countplot(x="income", color="C0", data=data, ax=axes[0, 0])
sns.countplot(x="sex", hue="income", data=data, legend=None, ax=axes[0, 1])
sns.countplot(x="race", hue="income", data=data, ax=axes[1, 0])
sns.countplot(x="age_binned", hue="income", data=data, legend=None, ax=axes[1, 1])
sns.countplot(x="hs_week_binned", hue="income", data=data, ax=axes[2, 0])
axes[2, 1].axis("off");
Some quick and gross info from the plots
- The probability of making more than $50k a year is larger if you are a Male.
- A person also has more probability of making more than $50k/yr if she/he is White.
- For age, we see the probability of making more than $50k a year increases as the variable increases, up to a point where it starts to decrease.
- Also, the more hours a person works per week, the higher the chance of making more than $50k/yr. There’s a big jump in that probability when the hours of work per week jump from the (20, 40] bin to the (40, 60] one.
The model
We will use a logistic regression model to estimate the probability of making more than \$50K as a function of age, hours of work per week, sex, race and education level.
If we have a binary response variable Y and a set of predictors or explanatory variables X_1, X_2, \cdots, X_p the logistic regression model can be defined as follows:
\log{\left(\frac{\pi}{1 - \pi}\right)} = \beta_0 + \beta_1 X_1 + \beta_2 X_2 + \cdots + \beta_p X_p
where \pi = P(Y = 1) (a.k.a. probability of success) and \beta_0, \beta_1, \cdots \beta_p are unknown parameters. The term on the left side is the logarithm of the odds ratio or simply known as the log-odds. With little effort, the expression can be re-arranged to express our probability of interest, \pi, as a function of the betas and the predictors.
\pi = \frac{e^{\beta_0 + \beta_1 X_1 + \cdots + \beta_p X_p}}{1 + e^{\beta_0 + \beta_1 X_1 + \cdots + \beta_p X_p}}
= \frac{1}{1 + e^{-(\beta_0 + \beta_1 X_1 + \cdots + \beta_p X_p)}}
We need to specify a prior and a likelihood in order to draw samples from the posterior distribution. We could use sociological knowledge about the effects of age and education on income, but instead, let’s use the default prior specification in Bambi.
The likelihood is the product of n Bernoulli trials, \prod_{i=1}^{n}{p_i^y(1-p_i)^{1-y_i}} where p_i = P(Y=1).
In our case, we have
Y =
\left\{
\begin{array}{ll}
1 & \textrm{if the person makes more than 50K per year} \\
0 & \textrm{if the person makes less than 50K per year}
\end{array}
\right.
\pi = P(Y=1)
But this is a Bambi example, right? Let’s see how Bambi can helps us to build a logistic regression model.
Model 1:
\log{\left(\frac{\pi}{1 - \pi}\right)} = \beta_0 + \beta_1 X_1 + \beta_2 X_2 + \beta_3 X_3 + \beta_4 X_4
Where:
\begin{split}
X_1 &= \displaystyle \frac{\text{Age} - \text{mean(Age)}}{\text{std(Age)}} \\
X_2 &= \displaystyle \frac{\text{Hours week} - \text{mean(Hours week)}}{\text{std(Hours week)}} \\
X_3 &=
\left\{
\begin{array}{ll}
1 & \textrm{if the person is male} \\
0 & \textrm{if the person is female}
\end{array}
\right. \\
X_4 &=
\left\{
\begin{array}{ll}
1 & \textrm{if the person is white} \\
0 & \textrm{if the person is black}
\end{array}
\right.
\end{split}
model1 = bmb.Model(
"income['>50K'] ~ sex + race + scale(age) + scale(hs_week)",
data,
family="bernoulli",
)
fitted1 = model1.fit(random_seed=seed, tune=500, draws=400)
model1.compute_log_likelihood(fitted1)
Modeling the probability that income==>50K
NUTS[nutpie]: [sex, race, scale(age), scale(hs_week), Intercept_centered]
az.plot_trace(fitted1, figure_kwargs={"figsize": (7, 5)}, col_wrap=2);
|
mean |
sd |
eti89_lb |
eti89_ub |
ess_bulk |
ess_tail |
r_hat |
mcse_mean |
mcse_sd |
| sex[Male] |
1.018 |
0.035 |
0.96 |
1.1 |
1735 |
1484 |
1.00 |
0.00085 |
0.00061 |
| race[White] |
0.628 |
0.059 |
0.54 |
0.72 |
2070 |
1367 |
1.00 |
0.0013 |
0.0009 |
| scale(age) |
0.5787 |
0.0151 |
0.55 |
0.6 |
1921 |
1336 |
1.00 |
0.00035 |
0.00024 |
| scale(hs_week) |
0.5043 |
0.0152 |
0.48 |
0.53 |
1863 |
1424 |
1.00 |
0.00035 |
0.00024 |
| Intercept_centered |
-1.3853 |
0.0168 |
-1.4 |
-1.4 |
1722 |
1397 |
1.00 |
0.0004 |
0.00028 |
| Intercept |
-2.632 |
0.063 |
-2.7 |
-2.5 |
1837 |
1194 |
1.00 |
0.0015 |
0.001 |
Model 2
\log{\left(\frac{\pi}{1 - \pi}\right)} = \beta_0 + \beta_1 X_1 + \beta_2 X_1^2 + \beta_3 X_2 + \beta_4 X_2^2
+ \beta_5 X_3 + \beta_6 X_4
Where:
\begin{aligned}
X_1 &= \displaystyle \frac{\text{Age} - \text{mean(Age)}}{\text{std(Age)}} \\
X_2 &= \displaystyle \frac{\text{Hours week} - \text{mean(Hours week)}}{\text{std(Hours week)}} \\
X_3 &=
\left\{
\begin{array}{ll}
1 & \textrm{if the person is male} \\
0 & \textrm{if the person is female}
\end{array}
\right. \\
X_4 &=
\left\{
\begin{array}{ll}
1 & \textrm{if the person is white} \\
0 & \textrm{if the person is black}
\end{array}
\right. \\
\end{aligned}
model2 = bmb.Model(
"income['>50K'] ~ sex + race + scale(age) + I(scale(age) ** 2) + scale(hs_week) + I(scale(hs_week) ** 2)",
data,
family="bernoulli",
)
fitted2 = model2.fit(random_seed=seed, tune=500, draws=400)
model2.compute_log_likelihood(fitted2)
Modeling the probability that income==>50K
NUTS[nutpie]: [sex, race, scale(age), I(scale(age) ** 2), scale(hs_week), I(scale(hs_week) ** 2), Intercept_centered]
az.plot_trace(fitted2, figure_kwargs={"figsize": (7, 5)}, col_wrap=2);
|
mean |
sd |
eti89_lb |
eti89_ub |
ess_bulk |
ess_tail |
r_hat |
mcse_mean |
mcse_sd |
| sex[Male] |
1.006 |
0.038 |
0.94 |
1.1 |
1492 |
1168 |
1.00 |
0.00098 |
0.00067 |
| race[White] |
0.703 |
0.059 |
0.61 |
0.8 |
1575 |
1310 |
1.00 |
0.0015 |
0.0011 |
| scale(age) |
1.069 |
0.023 |
1 |
1.1 |
939 |
1020 |
1.00 |
0.00075 |
0.00051 |
| I(scale(age) ** 2) |
-0.538 |
0.0174 |
-0.57 |
-0.51 |
1027 |
1126 |
1.00 |
0.00054 |
0.00038 |
| scale(hs_week) |
0.5 |
0.0218 |
0.47 |
0.53 |
1205 |
1185 |
1.00 |
0.00063 |
0.00046 |
| I(scale(hs_week) ** 2) |
-0.0878 |
0.0086 |
-0.1 |
-0.074 |
1200 |
905 |
1.00 |
0.00025 |
0.00017 |
| Intercept_centered |
-1.603 |
0.0199 |
-1.6 |
-1.6 |
1071 |
1196 |
1.01 |
0.00061 |
0.00045 |
| Intercept |
-2.284 |
0.063 |
-2.4 |
-2.2 |
1451 |
1263 |
1.00 |
0.0017 |
0.0011 |
Model 3
\log{\left(\frac{\pi}{1 - \pi}\right)} = \beta_0 + \beta_1 X_1 + \beta_2 X_1^2 + \beta_3 X_1^3 + \beta_4 X_2
+ \beta_5 X_2^2 + \beta_6 X_2^3 + \beta_7 X_3 + \beta_8 X_4
Where:
\begin{aligned}
X_1 &= \displaystyle \frac{\text{Age} - \text{mean(Age)}}{\text{std(Age)}} \\
X_2 &= \displaystyle \frac{\text{Hours week} - \text{mean(Hours week)}}{\text{std(Hours week)}} \\
X_3 &=
\left\{
\begin{array}{ll}
1 & \textrm{if the person is male} \\
0 & \textrm{if the person is female}
\end{array}
\right. \\
X_4 &=
\left\{
\begin{array}{ll}
1 & \textrm{if the person is white} \\
0 & \textrm{if the person is black}
\end{array}
\right.
\end{aligned}
parts = [
"scale(age)",
"I(scale(age) ** 2)",
"I(scale(age) ** 3)",
"scale(hs_week)",
"I(scale(hs_week) ** 2)",
"I(scale(hs_week) ** 3)",
]
model3 = bmb.Model(
"income['>50K'] ~ sex + race + " + " + ".join(parts), data, family="bernoulli"
)
fitted3 = model3.fit(random_seed=seed, tune=500, draws=400)
model3.compute_log_likelihood(fitted3)
Modeling the probability that income==>50K
NUTS[nutpie]: [sex, race, scale(age), I(scale(age) ** 2), I(scale(age) ** 3), scale(hs_week), I(scale(hs_week) ** 2), I(scale(hs_week) ** 3), Intercept_centered]
az.plot_trace(fitted3, figure_kwargs={"figsize": (7, 6)}, col_wrap=2);
|
mean |
sd |
eti89_lb |
eti89_ub |
ess_bulk |
ess_tail |
r_hat |
mcse_mean |
mcse_sd |
| sex[Male] |
0.983 |
0.038 |
0.92 |
1 |
2210 |
1225 |
1.00 |
0.00082 |
0.00059 |
| race[White] |
0.678 |
0.062 |
0.58 |
0.78 |
2494 |
1236 |
1.00 |
0.0012 |
0.00086 |
| scale(age) |
0.961 |
0.0269 |
0.92 |
1 |
1335 |
1196 |
1.00 |
0.00074 |
0.00049 |
| I(scale(age) ** 2) |
-0.891 |
0.03 |
-0.94 |
-0.84 |
510 |
711 |
1.01 |
0.0013 |
0.00093 |
| I(scale(age) ** 3) |
0.1742 |
0.0107 |
0.16 |
0.19 |
514 |
779 |
1.01 |
0.00047 |
0.00032 |
| scale(hs_week) |
0.612 |
0.024 |
0.57 |
0.65 |
1088 |
1082 |
1.00 |
0.00073 |
0.00053 |
| I(scale(hs_week) ** 2) |
-0.0108 |
0.01 |
-0.027 |
0.0049 |
1288 |
1079 |
1.00 |
0.00028 |
0.0002 |
| I(scale(hs_week) ** 3) |
-0.0348 |
0.0035 |
-0.041 |
-0.029 |
925 |
908 |
1.00 |
0.00011 |
8e-05 |
| Intercept_centered |
-1.689 |
0.022 |
-1.7 |
-1.7 |
720 |
834 |
1.00 |
0.00083 |
0.00059 |
| Intercept |
-2.142 |
0.064 |
-2.2 |
-2 |
2510 |
1023 |
1.00 |
0.0013 |
0.00097 |
Model comparison
We can perform a Bayesian model comparison very easily with az.compare(). Here we pass a dictionary with the InferenceData objects that Model.fit() returned and az.compare() returns a data frame that is ordered from best to worst according to the criteria used. By default, ArviZ uses loo, which is an estimation of leave one out cross validation. Another option is the widely applicable information criterion (WAIC). For more information about the information criteria available and other options within the function see the docs.
models_dict = {"model1": fitted1, "model2": fitted2, "model3": fitted3}
df_compare = az.compare(models_dict)
df_compare
|
rank |
elpd_diff |
dse |
p_worse |
diag_diff |
diag_elpd |
p |
elpd |
se |
weight |
| model3 |
0 |
0.0 |
0.0 |
NaN |
|
|
9.6 |
-14000.0 |
89.0 |
1.0 |
| model2 |
1 |
-170.0 |
20.0 |
1.0 |
|
|
8.1 |
-14200.0 |
91.0 |
0.0 |
| model1 |
2 |
-930.0 |
39.0 |
1.0 |
|
|
5.0 |
-14900.0 |
91.0 |
0.0 |
az.plot_compare(df_compare, figure_kwargs={"figsize": (7, 2)});
There is a difference in the point estimations (empty circles) between the model with cubic terms (model 3) and the model with quadratic terms (model 2) but there is some overlap between their interval estimations. This time, we are going to select model 2 and do some extra little work with it because from previous experience with this dataset we know there is no substantial difference between them, and model 2 is simpler. However, as we mention in the final remarks, this is not the best you can achieve with this dataset. If you want, you could also try to add other predictors, such as education level and see how it impacts in the model comparison :).
Probability estimation
In this section we plot age vs the probability of making more than 50K a year given different sex and race combinations using plot_predictions from the interpret sub-package.
bmb.interpret.plot_predictions(
model=model3,
idata=fitted3,
conditional={
"age": np.arange(18, 75),
"sex": ["Male", "Female"],
"race": ["Black", "White"],
"hs_week": [40],
},
prob=[0.5, 0.95],
subplot_kwargs={"main": "age", "group": "sex", "panel": "race"},
fig_kwargs={"theme": {"figure.figsize": (7, 3)}, "ylabel": "P(Income > $50K)"},
)
The highest posterior density bands show how the probability of earning more than 50K changes with age for a given profile. In all the cases, we see the probability of making more than $50K increases with age until approximately age 52, when the probability begins to drop off. We can interpret narrow portions of a curve as places where we have low uncertainty and spread out portions of the bands as places where we have somewhat higher uncertainty about our coefficient values.