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

import math

actual = list(map(float, input("Actual values: ").split()))
pred = list(map(float, input("Predicted values: ").split()))

n = len(actual)
p = int(input("Number of predictors: "))

sse = 0
sst = 0
mean = sum(actual) / n

for i in range(n):
    sse += (actual[i] - pred[i]) ** 2
    sst += (actual[i] - mean) ** 2

r2 = 1 - sse / sst
adj_r2 = 1 - ((1 - r2) * (n - 1) / (n - p - 1))

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

k = int(input("Number of coefficients: "))

for i in range(k):
    b = float(input("Coefficient: "))
    se = float(input("Standard error: "))

    t = b / se
    lower = b - 1.96 * se
    upper = b + 1.96 * se

    print("t-statistic:", t)
    print("95% CI:", lower, "to", upper)

    if lower > 0 or upper < 0:
        print("Statistically significant")
    else:
        print("Not statistically significant")


import math

n = int(input("Number of features: "))

features = []

for i in range(n):
    name = input("Feature name: ")
    b = float(input("Coefficient: "))

    odds = math.exp(b)
    change = (odds - 1) * 100

    if b > 0:
        direction = "Increases odds"
    elif b < 0:
        direction = "Decreases odds"
    else:
        direction = "No effect"

    features.append([name, b, odds, change, direction])

features.sort(key=lambda x: abs(x[1]), reverse=True)

print("\nFeature\tCoefficient\tOdds Ratio\tChange (%)\tInterpretation")

for f in features:
    print(f[0], f[1], round(f[2], 2),
          round(f[3], 2), f[4])

print("\nFeature Importance Ranking:")

for i, f in enumerate(features):
    print(i + 1, f[0])
