import numpy as np
from common import NAMES, load_data, normalize, poly_design, fit_ls, rms

Xtr, ttr, Xte, tte = load_data()
Xtr_n, Xte_n, mu, sd = normalize(Xtr, Xte)

Phi = poly_design(Xtr_n, 1)
w = fit_ls(Phi, ttr)

# weight per raw unit of each feature (undo the z-score), and the matching raw bias
ok = sd > 0
w_raw = np.zeros(13)
w_raw[ok] = w[1:][ok] / sd[ok]
bias_raw = w[0] - np.sum(w_raw[ok] * mu[ok])

print('degree 1 fit, first 100 rows, features z-scored with train mean/std')
print('feature #   name      weight (z-scored)   weight per raw unit')
print('  bias      w0        %10.4f          %10.4f' % (w[0], bias_raw))
for j in range(13):
    print('  %2d        %-8s  %10.4f          %10.4f' % (j + 1, NAMES[j], w[j + 1], w_raw[j]))

print()
print('check: raw-unit model reproduces z-scored predictions on train:',
      np.allclose(bias_raw + Xtr @ w_raw, Phi @ w))
print('train RMS %.4f, test RMS %.4f' % (rms(Phi @ w, ttr), rms(poly_design(Xte_n, 1) @ w, tte)))
