# XAI Experiment 1: Linear & Logistic Regression: R², adjusted R², t-statistic, CI, odds ratios  [lab notebook version]
# Requires: exam: none (math) | lab: numpy, pandas
# ===========================================================================

import numpy as np
import pandas as pd


import numpy as np

data = np.array([
    [1000, 2, 20, 50],
    [1200, 3, 18, 58],
    [1300, 3, 15, 63],
    [1500, 3, 12, 70],
    [1600, 4, 10, 78],
    [1700, 4, 9, 82],
    [1800, 4, 8, 87],
    [1900, 5, 7, 93],
    [2100, 5, 5, 102],
    [2300, 5, 3, 112]
])

X_train = data[:, :-1]
y_train = data[:, -1]

n = X_train.shape[0]
p = X_train.shape[1]

beta = np.array([5, 0.040, 4.5, -0.75])

y_pred = []

# Prediction
for i in range(n):
    t = beta[0] + X_train[i][0]*beta[1] + X_train[i][1]*beta[2] + X_train[i][2]*beta[3]
    y_pred.append(t)

sse, sst = 0, 0
y_mean = np.mean(y_train)

for i in range(len(y_pred)):
    sse += (y_train[i] - y_pred[i]) ** 2
    sst += (y_train[i] - y_mean) ** 2

r2 = 1 - (sse / sst)

adjr2 = 1 - ((1-r2)*(n-1))/(n-p-1)

print("R2:", r2)
print("Adjusted R2:", adjr2)

# Standard Error
sigma = np.sqrt(sse / (n-p-1))

se = []

for j in range(p):
    x_sum = 0

    for i in range(n):
        x_sum += X_train[i][j]

    x_mean = x_sum / n

    t = 0

    for i in range(n):
        t += (X_train[i][j] - x_mean)**2

    se.append(sigma / np.sqrt(t))

print("Standard Errors:", se)

t_stat = []

for i in range(1, p+1):
    t_stat.append(beta[i]/se[i-1])
print("T stat: ", t_stat)

ci = []

for i in range(1, p+1):
    lb = beta[i] - 2.447*se[i-1]
    ub = beta[i] + 2.447*se[i-1]

    ci.append((lb, ub))

print("CI: ", ci)

features = ["Age", "Income", "Loan Amount", "Credit Score"]
coefficients = np.array([0.06, 0.85, -0.40, 1.25])

for i in range(len(coefficients)):
    odds_ratio = np.exp(coefficients[i])
    change = (odds_ratio-1) * 100

    print(f"{odds_ratio}, {change}")
