-
Notifications
You must be signed in to change notification settings - Fork 23
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Cross validation of Pipeline/estimators using MLDataset / xarray.Dataset #221
Closed
Closed
Changes from 6 commits
Commits
Show all changes
27 commits
Select commit
Hold shift + click to select a range
55959a5
cross validation of MLDataset Pipeline
396f9aa
changes with CV sampling
33bac56
changes to cv_cache
b422e68
closer to working cross validation for MLDataset
d45d4e1
CV / xarray experimentation - work in progress
92054c9
MLDataset cross validation working for pipeline of 1 step that is uns…
35450c1
wrapped sklearn classes need to wrap score methods as fit, predict, o…
f86a079
update tests;fix cross validation with most data structures
5cf646f
a couple tests for Python 2.7
744109a
avoid dask-searchcv test in conda.recipe;add test_config.yml to MANIF…
1e7bec8
remove print statement
83437f5
ensure test_config.yaml included in pkg
de9efd0
remove elm.mldataset.cross_validation - modify environment.yml for el…
6267041
fix usage of is_arr utility to separate X, y tuple
66013e6
1850 passing tests
a91caf6
dask-searchcv in meta.yaml
e9b5d85
use elm/label/dev and elm for CI installs
f6ef7c8
change earthio version for fixing CI build
948efe5
ensure EARTHIO_CHANNEL_STR is set correctly in .travis.yml
edbe1f5
ensure ANACONDA_UPLOAD_USER is defined in .travis for pkg upload
6304e37
change order of channels to ensure dask-searchcv comes from elm
8a6d46f
subset the number of tests being run in CI
21a18d9
better diagnostics on upload failure in CI
8ad7b4c
remove earthio from CI
9a1734d
be sure to create env from elm's conda build output
dc47f65
remove diagnostic print from deploy section
00ea1be
refactor to simplify changes in dask-searchcv
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
from elm.mldataset.util import is_mldataset | ||
from elm.mldataset.cross_validation import * # uses __all__ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,114 @@ | ||
from sklearn.model_selection import KFold | ||
from dask_searchcv.methods import CVCache | ||
from xarray_filters.pipeline import Step | ||
from sklearn.model_selection import GroupKFold as _GroupKFold | ||
from sklearn.model_selection import GroupShuffleSplit as _GroupShuffleSplit | ||
from sklearn.model_selection import KFold as _KFold | ||
from sklearn.model_selection import LeaveOneGroupOut as _LeaveOneGroupOut | ||
from sklearn.model_selection import LeavePGroupsOut as _LeavePGroupsOut | ||
from sklearn.model_selection import LeaveOneOut as _LeaveOneOut | ||
from sklearn.model_selection import LeavePOut as _LeavePOut | ||
from sklearn.model_selection import PredefinedSplit as _PredefinedSplit | ||
from sklearn.model_selection import RepeatedKFold as _RepeatedKFold | ||
from sklearn.model_selection import RepeatedStratifiedKFold as _RepeatedStratifiedKFold | ||
from sklearn.model_selection import ShuffleSplit as _ShuffleSplit | ||
from sklearn.model_selection import StratifiedKFold as _StratifiedKFold | ||
from sklearn.model_selection import StratifiedShuffleSplit as _StratifiedShuffleSplit | ||
from sklearn.model_selection import TimeSeriesSplit as _TimeSeriesSplit | ||
|
||
CV_CLASSES = [ | ||
'GroupKFold', | ||
'GroupShuffleSplit', | ||
'KFold', | ||
'LeaveOneGroupOut', | ||
'LeavePGroupsOut', | ||
'LeaveOneOut', | ||
'LeavePOut', | ||
'PredefinedSplƒit', | ||
'RepeatedKFold', | ||
'RepeatedStratifiedKFold', | ||
'ShuffleSplit', | ||
'StratifiedKFold', | ||
'StratifiedShuffleSplit', | ||
'TimeSeriesSplit', | ||
'MLDatasetMixin', | ||
'CVCacheSampleId', | ||
] | ||
|
||
__all__ = CV_CLASSES + ['CVCacheSampleId', 'MLDatasetMixin', 'CV_CLASSES'] | ||
|
||
class CVCacheSampleId(CVCache): | ||
def __init__(self, sampler, splits, pairwise=False, cache=True): | ||
self.sampler = sampler | ||
super(CVCacheSampleId, self).__init__(splits, pairwise=pairwise, | ||
cache=cache) | ||
|
||
def _post_splits(self, X, y=None, n=None, is_x=True, is_train=False): | ||
if y is not None: | ||
raise ValueError('Expected y to be None (returned by Sampler() instance or similar.') | ||
return self.sampler.fit_transform(X) | ||
|
||
|
||
class MLDatasetMixin: | ||
def split(self, *args, **kw): | ||
for test, train in super(cls, self).split(*args, **kw): | ||
for a, b in zip(test, train): | ||
yield a, b | ||
|
||
|
||
class GroupKFold(_GroupKFold, MLDatasetMixin): | ||
pass | ||
|
||
|
||
class GroupShuffleSplit(_GroupShuffleSplit, MLDatasetMixin): | ||
pass | ||
|
||
|
||
class KFold(_KFold, MLDatasetMixin): | ||
pass | ||
|
||
|
||
class LeaveOneGroupOut(_LeaveOneGroupOut, MLDatasetMixin): | ||
pass | ||
|
||
|
||
class LeavePGroupsOut(_LeavePGroupsOut, MLDatasetMixin): | ||
pass | ||
|
||
|
||
class LeaveOneOut(_LeaveOneOut, MLDatasetMixin): | ||
pass | ||
|
||
|
||
class LeavePOut(_LeavePOut, MLDatasetMixin): | ||
pass | ||
|
||
|
||
class PredefinedSplƒit(_PredefinedSplit, MLDatasetMixin): | ||
pass | ||
|
||
|
||
class RepeatedKFold(_RepeatedKFold, MLDatasetMixin): | ||
pass | ||
|
||
|
||
class RepeatedStratifiedKFold(_RepeatedStratifiedKFold, MLDatasetMixin): | ||
pass | ||
|
||
|
||
class ShuffleSplit(_ShuffleSplit, MLDatasetMixin): | ||
pass | ||
|
||
|
||
class StratifiedKFold(_StratifiedKFold, MLDatasetMixin): | ||
pass | ||
|
||
|
||
class StratifiedShuffleSplit(_StratifiedShuffleSplit, MLDatasetMixin): | ||
pass | ||
|
||
|
||
class TimeSeriesSplit(_TimeSeriesSplit, MLDatasetMixin): | ||
pass | ||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
import numpy as np | ||
import dask.array as da | ||
|
||
|
||
def is_mldataset(arr, raise_err=False): | ||
try: | ||
from xarray_filters import MLDataset | ||
from xarray import Dataset | ||
return True | ||
except Exception as e: | ||
MLDataset = Dataset = None | ||
if not raise_err: | ||
return False | ||
# Much of the ML logic | ||
# wrapping Xarray would fail | ||
# if only xarray and not Xarray_filters | ||
# is installed, but when xarray_filters | ||
# is installed, xarray.Dataset can be | ||
# used | ||
raise ValueError('Cannot use cross validation for xarray Dataset without xarray_filters') | ||
return MLDataset and isinstance(arr, (MLDataset, Dataset)) | ||
|
||
|
||
def is_arr(arr, raise_err=False): | ||
is_ml = is_mldataset(arr, raise_err=raise_err) | ||
return is_ml or isinstance(arr, (np.ndarray, da.Array)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,104 @@ | ||
from __future__ import print_function, unicode_literals, division | ||
|
||
from collections import OrderedDict | ||
import datetime | ||
|
||
from sklearn.metrics import r2_score, mean_squared_error, make_scorer | ||
from sklearn.model_selection import StratifiedShuffleSplit | ||
from xarray_filters import MLDataset | ||
from xarray_filters.datasets import make_regression | ||
from xarray_filters.pipeline import Generic, Step | ||
import numpy as np | ||
import pytest | ||
|
||
|
||
from elm.mldataset import CV_CLASSES | ||
from elm.model_selection import EaSearchCV | ||
from elm.model_selection.sorting import pareto_front | ||
from elm.pipeline import Pipeline | ||
from elm.pipeline.predict_many import predict_many | ||
from elm.pipeline.steps import linear_model,cluster | ||
import elm.mldataset.cross_validation as cross_validation | ||
|
||
START_DATE = datetime.datetime(2000, 1, 1, 0, 0, 0) | ||
MAX_TIME_STEPS = 144 | ||
DATES = np.array([START_DATE - datetime.timedelta(hours=hr) | ||
for hr in range(MAX_TIME_STEPS)]) | ||
DATE_GROUPS = np.linspace(0, 5, DATES.size).astype(np.int32) | ||
|
||
|
||
# TODO - also test regressors | ||
param_distributions = { | ||
'estimator__fit_intercept': [True, False], | ||
} | ||
|
||
param_distributions = { | ||
'estimator__n_clusters': [4,5,6,7,8, 10, 12], | ||
'estimator__init': ['k-means++', 'random'], | ||
'estimator__copy_x': [False], | ||
'estimator__algorithm': ["auto", "full", "auto"], | ||
} | ||
|
||
model_selection = { | ||
'select_method': 'selNSGA2', | ||
'crossover_method': 'cxTwoPoint', | ||
'mutate_method': 'mutUniformInt', | ||
'init_pop': 'random', | ||
'indpb': 0.5, | ||
'mutpb': 0.9, | ||
'cxpb': 0.3, | ||
'eta': 20, | ||
'ngen': 2, | ||
'mu': 16, | ||
'k': 8, # TODO ensure that k is not ignored - make elm issue if it is | ||
'early_stop': None | ||
} | ||
|
||
def example_function(date): | ||
dset = make_regression() | ||
dset.attrs['example_function_argument'] = date | ||
# TODO - this is not really testing | ||
# MLDataset as X because of .features.values below | ||
return dset.to_features(keep_attrs=True).features.values | ||
|
||
|
||
class Sampler(Step): | ||
def transform(self, X, y=None, **kw): | ||
return example_function(X) | ||
|
||
|
||
class GetY(Step): | ||
layer = 'y' | ||
def transform(self, X, y=None, **kw): | ||
layer = self.get_params()['layer'] | ||
y = getattr(X, layer).values.ravel() | ||
X = MLDataset(OrderedDict([(k, v) for k, v in X.data_vars.items() | ||
if k != layer])).to_features() | ||
return X.features.values, y | ||
|
||
pipe = Pipeline([ # TODO see note above about supervised models | ||
('get_y', GetY()), | ||
('estimator', linear_model.LinearRegression(n_jobs=-1)), | ||
]) | ||
|
||
pipe = Pipeline([ | ||
#('get_y', GetY()), # TODO this wasn't working but should | ||
('estimator', cluster.KMeans(n_jobs=1)), | ||
]) | ||
|
||
@pytest.mark.parametrize('cls', CV_CLASSES) | ||
def test_each_cv(cls): | ||
cv = getattr(cross_validation, cls)() | ||
ea = EaSearchCV(pipe, | ||
param_distributions=param_distributions, | ||
sampler=Sampler(), | ||
ngen=2, | ||
model_selection=model_selection, | ||
cv=cv, | ||
refit=False) # TODO refit = True | ||
|
||
print(ea.get_params()) | ||
ea.fit(DATES, groups=DATE_GROUPS) | ||
results = getattr(ea, 'cv_results_', None) | ||
assert isinstance(results, dict) and 'gen' in results and all(getattr(v,'size',v) for v in results.values()) | ||
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is just checking that we are getting
StandardScaler
or similar from thesklearn
module where it is actually defined, not some other one where it is imported for internal usage.