test_logistic.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import numpy as np
  2. import pytest
  3. from irae_risk.logistic import LogisticPolyRegression
  4. @pytest.fixture
  5. def regression_data():
  6. x = np.array([-1.0, 0.0, 1.0, 2.0])
  7. y = np.array([0, 0, 1, 1])
  8. theta = np.array([-0.2, 0.8])
  9. return x, y, theta
  10. def test_goodness_of_fit_uses_unpenalized_likelihood_by_default(regression_data):
  11. x, y, theta = regression_data
  12. model = LogisticPolyRegression(degree=1, lam=(0.0, 0.5))
  13. result = model.goodness_of_fit(x, y, theta)
  14. expected_llf = -model.get_nllf(x, y, theta)
  15. k = len(theta)
  16. n = len(x)
  17. assert result["LLF"] == pytest.approx(expected_llf)
  18. assert result["AIC"] == pytest.approx(2 * k - 2 * expected_llf)
  19. assert result["BIC"] == pytest.approx(k * np.log(n) - 2 * expected_llf)
  20. def test_goodness_of_fit_can_include_regularization(regression_data):
  21. x, y, theta = regression_data
  22. model = LogisticPolyRegression(degree=1, lam=(0.0, 0.5))
  23. unregularized = model.goodness_of_fit(x, y, theta)
  24. regularized = model.goodness_of_fit(
  25. x,
  26. y,
  27. theta,
  28. regularization=True,
  29. )
  30. penalty = model.penalty(theta)
  31. assert regularized["LLF"] == pytest.approx(
  32. -model.get_cost(x, y, theta)
  33. )
  34. assert unregularized["LLF"] - regularized["LLF"] == pytest.approx(penalty)
  35. assert regularized["AIC"] - unregularized["AIC"] == pytest.approx(
  36. 2 * penalty
  37. )
  38. assert regularized["BIC"] - unregularized["BIC"] == pytest.approx(
  39. 2 * penalty
  40. )
  41. def test_regularization_switch_has_no_effect_without_penalty(regression_data):
  42. x, y, theta = regression_data
  43. model = LogisticPolyRegression(degree=1)
  44. default = model.goodness_of_fit(x, y, theta)
  45. regularized = model.goodness_of_fit(
  46. x,
  47. y,
  48. theta,
  49. regularization=True,
  50. )
  51. assert regularized == pytest.approx(default)