Preface

In [0]:
import pandas as pd
import seaborn as sns
import torch

import pyro
import pyro.distributions as dist

from rethinking import LM, coef

Code 0.1

In [1]:
print("All models are wrong, but some are useful.")
Out[1]:
All models are wrong, but some are useful.

Code 0.2

In [2]:
x = torch.arange(1., 3)
x = x * 10
x = x.log()
x = x.sum()
x = x.exp()
x
Out[2]:
tensor(200.0000)

Code 0.3

In [3]:
print(torch.tensor(0.01).pow(200).log())
print(200 * torch.tensor(0.01).log())
Out[3]:
tensor(-inf)
tensor(-921.0341)

Code 0.4

In [4]:
# Load the data:
# car braking distances in feet paired with speeds in km/h
# see cars.info() for details
cars = pd.read_csv("../data/cars.csv")

# fit a linear regression of distance on speed
m = LM("dist ~ speed", data=cars).run()

# estimated coefficients from the model
print(coef(m))

# plot residuals against speed
y = coef(m)["Intercept"].item() + coef(m)["speed"].item() * cars["speed"]
resid = cars["dist"] - y
ax = sns.scatterplot(cars["speed"], resid)
ax.set(xlabel="speed", ylabel="residual");
Out[4]:
{'Intercept': tensor(-17.4259), 'speed': tensor(3.9238), 'sigma': tensor(15.0173)}
Out[4]:

Code 0.5

pip install jupyter pandas pyro-ppl seaborn torch