import polars as pl
import scipy as sp
import numpy as np
import patsy as pt # uv add patsy pyarrow
import matplotlib.pyplot as plt

There are two types of variables:

Levels the values a categorical variable can take on

# change penguins to carnivora
url = "https://roualdes.sfo3.digitaloceanspaces.com/data/carnivora.csv"
df = pl.read_csv(url, null_values = ["NA"]).select("Family", "BW", "LS").drop_nulls()

Linear models have the following form, for \(y \sim \text{Normal}(m, s)\)

\[m = \beta_0 + \sum_{k=1}^K \beta_k x_k\]

Also checkout the webpage on correlation.

1 Categorical Predictor: Family

np.unique(df["Family"].to_numpy())
array(['Ailuridae', 'Canidae', 'Felidae', 'Hyaenidae', 'Mustelidae',
       'Procyonidae', 'Ursidae', 'Viverridae'], dtype=object)
y, X = pt.dmatrices("BW ~ C(Family)", data = df.to_pandas())
def ll_lm(theta, data):
    X = data["X"]
    y = data["y"]
    N = np.size(y)
    lm = np.sum(X * theta, axis=1)
    d = y - lm
    return np.sum(d * d)    
init = sp.stats.norm().rvs(size = 8)
d = {"X": X, "y": y[:,0]}
o = sp.optimize.minimize(ll_lm, init, args = (d,), method = "L-BFGS-B")
o["x"]
array([104.81237579, 101.66668356, 313.2459975 , 991.69794656,
       -47.35210761,   6.28191898, 537.38883416,  -4.69154882])
(df
 .group_by("Family")
 .agg(pl.col("BW").mean().alias("mean BW"))
)
shape: (8, 2)
Family mean BW
str f64
"Felidae" 418.0625
"Viverridae" 100.125
"Ailuridae" 104.8
"Canidae" 206.481818
"Hyaenidae" 1096.5
"Ursidae" 642.2
"Procyonidae" 111.1
"Mustelidae" 57.460667

1 Quantitative Predictor: LS

y, X = pt.dmatrices("BW ~ LS", data = df.to_pandas())
init = sp.stats.norm().rvs(size = 2)
d = {"X": X, "y": y[:,0]}
o = sp.optimize.minimize(ll_lm, init, args = (d,), method = "L-BFGS-B")
thetahat = o["x"]
x = df["LS"].to_numpy()
y = df["BW"].to_numpy()
plt.scatter(x, y)
yhat = np.sum(X * thetahat, axis=1)
plt.plot(x, yhat, color = "black")

Example 2

df = pl.read_csv(url, null_values = ["NA"]).select("SW", "SB") # body weight, brain weight
x = df["SW"].to_numpy() # body weight
y = df["SB"].to_numpy() # brain weight
plt.scatter(np.log10(x), np.log10(y))

x = np.array([2, 1, 4])
o = np.argsort(x)
o, x[o]
(array([1, 0, 2]), array([1, 2, 4]))
y, X = pt.dmatrices("np.log10(SB) ~ np.log10(SW)", data = df.to_pandas())
init = sp.stats.norm().rvs(size = 2)
d = {"X": X, "y": y[:,0]}
o = sp.optimize.minimize(ll_lm, init, args = (d,), method = "L-BFGS-B")
thetahat = o["x"]
x = df["SW"].to_numpy()
y = df["SB"].to_numpy()
plt.scatter(x, y)
yhat = np.sum(X * thetahat, axis=1)
o = np.argsort(x)
plt.plot(x[o], 10 ** yhat[o], color = "black")

Example 3

y, X = pt.dmatrices("SB ~ SW + I(SW ** 2)", data = df.to_pandas())
init = sp.stats.norm().rvs(size = 3)
d = {"X": X, "y": y[:,0]}
o = sp.optimize.minimize(ll_lm, init, args = (d,), method = "L-BFGS-B")
thetahat = o["x"]
x = df["SW"].to_numpy()
y = df["SB"].to_numpy()
plt.scatter(x, y, alpha = 0.1)
xx = np.linspace(0, 350, 101)
#yhat = np.sum(X * thetahat, axis=1)
yhat = thetahat[0] + thetahat[1] * xx + thetahat[2] * xx ** 2
plt.plot(xx, yhat, color = "black")

xx = 4500 # southern elephant seal 
thetahat[0] + thetahat[1] * xx + thetahat[2] * xx ** 2
np.float64(-55691.18409999654)