Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

score.py 5.6 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
  1. from typing import List, Tuple
  2. from warnings import warn
  3. import pandas as pd
  4. import numpy as np
  5. from sklearn.utils import indices_to_mask
  6. from sklearn.linear_model import Lasso, LogisticRegression
  7. from sklearn.linear_model._coordinate_descent import _alpha_grid
  8. from sklearn.model_selection import cross_val_score
  9. from imodels.util.rule import Rule
  10. def score_precision_recall(X,
  11. y,
  12. rules: List[List[str]],
  13. samples: List[List[int]],
  14. features: List[List[int]],
  15. feature_names: List[str],
  16. oob: bool = True) -> List[Rule]:
  17. scored_rules = []
  18. for curr_rules, curr_samples, curr_features in zip(rules, samples, features):
  19. # Create mask for OOB samples
  20. mask = ~indices_to_mask(curr_samples, X.shape[0])
  21. if sum(mask) == 0:
  22. if oob:
  23. warn(
  24. "OOB evaluation not possible: doing it in-bag. Performance evaluation is "
  25. "likely to be wrong (overfitting) and selected rules are likely to not "
  26. "perform well! Please use max_samples < 1."
  27. )
  28. mask = curr_samples
  29. # XXX todo: idem without dataframe
  30. X_oob = pd.DataFrame(
  31. (X[mask, :])[:, curr_features],
  32. columns=np.array(feature_names)[curr_features]
  33. )
  34. if X_oob.shape[1] <= 1: # otherwise pandas bug (cf. issue #16363)
  35. return []
  36. y_oob = y[mask]
  37. y_oob = np.array((y_oob != 0))
  38. # Add OOB performances to rules:
  39. scored_rules += [
  40. Rule(r, args=_eval_rule_perf(r, X_oob, y_oob))
  41. for r in set(curr_rules)
  42. ]
  43. return scored_rules
  44. def _eval_rule_perf(rule: str, X, y) -> Tuple[float, float]:
  45. detected_index = list(X.query(rule).index)
  46. if len(detected_index) <= 1:
  47. return (0, 0)
  48. y_detected = y[detected_index]
  49. true_pos = y_detected[y_detected > 0].sum()
  50. if true_pos == 0:
  51. return (0, 0)
  52. pos = y[y > 0].sum()
  53. return y_detected.mean(), float(true_pos) / pos
  54. def score_linear(X, y, rules: List[str],
  55. penalty='l1',
  56. prediction_task='regression',
  57. max_rules=30,
  58. alpha=None,
  59. cv=True,
  60. random_state=None) -> Tuple[List[Rule], List[float], float]:
  61. if alpha is not None:
  62. final_alpha = alpha
  63. if max_rules is not None:
  64. warn("Ignoring max_rules parameter since alpha passed explicitly")
  65. elif max_rules is not None:
  66. final_alpha = get_best_alpha_under_max_rules(X, y, rules,
  67. penalty=penalty,
  68. prediction_task=prediction_task,
  69. max_rules=max_rules,
  70. cv=cv,
  71. random_state=random_state)
  72. else:
  73. raise ValueError("Invalid alpha and max_rules passed")
  74. if prediction_task == 'regression':
  75. lin_model = Lasso(alpha=final_alpha, random_state=random_state, max_iter=2000)
  76. else:
  77. lin_model = LogisticRegression(
  78. penalty=penalty, C=(1 / final_alpha), solver='liblinear',
  79. random_state=random_state, max_iter=200)
  80. lin_model.fit(X, y)
  81. coef_ = lin_model.coef_.flatten()
  82. coefs = list(coef_[:coef_.shape[0] - len(rules)])
  83. support = np.sum(X[:, -len(rules):], axis=0) / X.shape[0]
  84. nonzero_rules = []
  85. coef_zero_threshold = 1e-6 / np.mean(np.abs(y))
  86. for r, w, s in zip(rules, coef_[-len(rules):], support):
  87. if abs(w) > coef_zero_threshold:
  88. nonzero_rules.append(Rule(r, args=[w], support=s))
  89. coefs.append(w)
  90. return nonzero_rules, coefs, lin_model.intercept_
  91. def get_best_alpha_under_max_rules(X, y, rules: List[str],
  92. penalty='l1',
  93. prediction_task='regression',
  94. max_rules=30,
  95. cv=True,
  96. random_state=None) -> float:
  97. coef_zero_threshold = 1e-6 / np.mean(np.abs(y))
  98. alpha_scores = []
  99. if prediction_task == 'regression':
  100. alphas = _alpha_grid(X, y)
  101. elif prediction_task == 'classification':
  102. # LogisticRegression accepts inverse of regularization
  103. alphas = np.flip(np.logspace(-4, 4, num=100, base=10))
  104. # alphas are sorted from highest to lowest regularization
  105. for i, alpha in enumerate(alphas):
  106. if prediction_task == 'regression':
  107. m = Lasso(alpha=alpha, random_state=random_state, max_iter=2000)
  108. cv_scoring = 'neg_mean_squared_error'
  109. else:
  110. m = LogisticRegression(
  111. penalty=penalty, C=(1 / alpha), solver='liblinear', random_state=random_state)
  112. cv_scoring = 'accuracy'
  113. m.fit(X, y)
  114. rule_coefs = m.coef_.flatten()
  115. rule_count = np.sum(np.abs(rule_coefs) > coef_zero_threshold)
  116. if rule_count > max_rules:
  117. break
  118. if cv:
  119. fold_scores = cross_val_score(m, X, y, cv=5, scoring=cv_scoring)
  120. alpha_scores.append(np.mean(fold_scores))
  121. if cv and np.all(alpha_scores != alpha_scores[0]):
  122. # check for rare case in which diff alphas lead to identical scores
  123. final_alpha = alphas[np.argmax(alpha_scores)]
  124. else:
  125. final_alpha = alphas[i - 1]
  126. return final_alpha
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...