Elffuss BraidHub

kikocis/auto-code-rover public

main · 3.0 KiBRawPermalink
1NCA fails in GridSearch due to too strict parameter checks
2NCA checks its parameters to have a specific type, which can easily fail in a GridSearch due to how param grid is made.
3
4Here is an example:
5```python
6import numpy as np
7
8from sklearn.pipeline import Pipeline
9from sklearn.model_selection import GridSearchCV
10from sklearn.neighbors import NeighborhoodComponentsAnalysis
11from sklearn.neighbors import KNeighborsClassifier
12
13X = np.random.random_sample((100, 10))
14y = np.random.randint(2, size=100)
15
16nca = NeighborhoodComponentsAnalysis()
17knn = KNeighborsClassifier()
18
19pipe = Pipeline([('nca', nca),
20 ('knn', knn)])
21
22params = {'nca__tol': [0.1, 0.5, 1],
23 'nca__n_components': np.arange(1, 10)}
24
25gs = GridSearchCV(estimator=pipe, param_grid=params, error_score='raise')
26gs.fit(X,y)
27```
28
29The issue is that for `tol`: 1 is not a float, and for `n_components`: np.int64 is not int
30
31Before proposing a fix for this specific situation, I'd like to have your general opinion about parameter checking.
32I like this idea of common parameter checking tool introduced with the NCA PR. What do you think about extending it across the code-base (or at least for new or recent estimators) ?
33
34Currently parameter checking is not always done or often partially done, and is quite redundant. For instance, here is the input validation of lda:
35```python
36def _check_params(self):
37 """Check model parameters."""
38 if self.n_components <= 0:
39 raise ValueError("Invalid 'n_components' parameter: %r"
40 % self.n_components)
41
42 if self.total_samples <= 0:
43 raise ValueError("Invalid 'total_samples' parameter: %r"
44 % self.total_samples)
45
46 if self.learning_offset < 0:
47 raise ValueError("Invalid 'learning_offset' parameter: %r"
48 % self.learning_offset)
49
50 if self.learning_method not in ("batch", "online"):
51 raise ValueError("Invalid 'learning_method' parameter: %r"
52 % self.learning_method)
53```
54most params aren't checked and for those who are there's a lot of duplicated code.
55
56A propose to be upgrade the new tool to be able to check open/closed intervals (currently only closed) and list membership.
57
58The api would be something like that:
59```
60check_param(param, name, valid_options)
61```
62where valid_options would be a dict of `type: constraint`. e.g for the `beta_loss` param of `NMF`, it can be either a float or a string in a list, which would give
63```
64valid_options = {numbers.Real: None, # None for no constraint
65 str: ['frobenius', 'kullback-leibler', 'itakura-saito']}
66```
67Sometimes a parameter can only be positive or within a given interval, e.g. `l1_ratio` of `LogisticRegression` must be between 0 and 1, which would give
68```
69valid_options = {numbers.Real: Interval(0, 1, closed='both')}
70```
71positivity of e.g. `max_iter` would be `numbers.Integral: Interval(left=1)`.