classification Package¶
classification
Package¶
AdvancedSampler
Module¶
- class WORC.classification.AdvancedSampler.AdvancedSampler(param_distributions, n_iter, random_state=None, method='Halton')[source]¶
Bases:
object
Generator on parameters sampled from given distributions using numerical sequences. Based on the sklearn ParameterSampler.
Non-deterministic iterable over random candidate combinations for hyper- parameter search. If all parameters are presented as a list, sampling without replacement is performed. If at least one parameter is given as a distribution, sampling with replacement is used. It is highly recommended to use continuous distributions for continuous parameters.
Note that before SciPy 0.16, the
scipy.stats.distributions
do not accept a custom RNG instance and always use the singleton RNG fromnumpy.random
. Hence settingrandom_state
will not guarantee a deterministic iteration wheneverscipy.stats
distributions are used to define the parameter search space. Deterministic behavior is however guaranteed from SciPy 0.16 onwards.Read more in the User Guide.
- param_distributionsdict
Dictionary where the keys are parameters and values are distributions from which a parameter is to be sampled. Distributions either have to provide a
rvs
function to sample from them, or can be given as a list of values, where a uniform distribution is assumed.- n_iterinteger
Number of parameter settings that are produced.
- random_stateint or RandomState
Pseudo random number generator state used for random uniform sampling from lists of possible values instead of scipy.stats distributions.
- paramsdict of string to any
Yields dictionaries mapping each estimator parameter to as sampled value.
>>> from WORC.classification.AdvancedSampler import HaltonSampler >>> from scipy.stats.distributions import expon >>> import numpy as np >>> np.random.seed(0) >>> param_grid = {'a':[1, 2], 'b': expon()} >>> param_list = list(HaltonSampler(param_grid, n_iter=4)) >>> rounded_list = [dict((k, round(v, 6)) for (k, v) in d.items()) ... for d in param_list] >>> rounded_list == [{'b': 0.89856, 'a': 1}, ... {'b': 0.923223, 'a': 1}, ... {'b': 1.878964, 'a': 2}, ... {'b': 1.038159, 'a': 2}] True
- __dict__ = mappingproxy({'__module__': 'WORC.classification.AdvancedSampler', '__doc__': "Generator on parameters sampled from given distributions using\n numerical sequences. Based on the sklearn ParameterSampler.\n\n Non-deterministic iterable over random candidate combinations for hyper-\n parameter search. If all parameters are presented as a list,\n sampling without replacement is performed. If at least one parameter\n is given as a distribution, sampling with replacement is used.\n It is highly recommended to use continuous distributions for continuous\n parameters.\n\n Note that before SciPy 0.16, the ``scipy.stats.distributions`` do not\n accept a custom RNG instance and always use the singleton RNG from\n ``numpy.random``. Hence setting ``random_state`` will not guarantee a\n deterministic iteration whenever ``scipy.stats`` distributions are used to\n define the parameter search space. Deterministic behavior is however\n guaranteed from SciPy 0.16 onwards.\n\n Read more in the :ref:`User Guide <search>`.\n\n Parameters\n ----------\n param_distributions : dict\n Dictionary where the keys are parameters and values\n are distributions from which a parameter is to be sampled.\n Distributions either have to provide a ``rvs`` function\n to sample from them, or can be given as a list of values,\n where a uniform distribution is assumed.\n\n n_iter : integer\n Number of parameter settings that are produced.\n\n random_state : int or RandomState\n Pseudo random number generator state used for random uniform sampling\n from lists of possible values instead of scipy.stats distributions.\n\n Returns\n -------\n params : dict of string to any\n **Yields** dictionaries mapping each estimator parameter to\n as sampled value.\n\n Examples\n --------\n >>> from WORC.classification.AdvancedSampler import HaltonSampler\n >>> from scipy.stats.distributions import expon\n >>> import numpy as np\n >>> np.random.seed(0)\n >>> param_grid = {'a':[1, 2], 'b': expon()}\n >>> param_list = list(HaltonSampler(param_grid, n_iter=4))\n >>> rounded_list = [dict((k, round(v, 6)) for (k, v) in d.items())\n ... for d in param_list]\n >>> rounded_list == [{'b': 0.89856, 'a': 1},\n ... {'b': 0.923223, 'a': 1},\n ... {'b': 1.878964, 'a': 2},\n ... {'b': 1.038159, 'a': 2}]\n True\n ", '__init__': <function AdvancedSampler.__init__>, '__iter__': <function AdvancedSampler.__iter__>, '__len__': <function AdvancedSampler.__len__>, '__dict__': <attribute '__dict__' of 'AdvancedSampler' objects>, '__weakref__': <attribute '__weakref__' of 'AdvancedSampler' objects>, '__annotations__': {}})¶
- __init__(param_distributions, n_iter, random_state=None, method='Halton')[source]¶
Initialize self. See help(type(self)) for accurate signature.
- __module__ = 'WORC.classification.AdvancedSampler'¶
- __weakref__¶
list of weak references to the object (if defined)
- class WORC.classification.AdvancedSampler.boolean_uniform(loc=0, scale=1, threshold=0.5)[source]¶
Bases:
object
Uniform distribution thresholded at a certain value to output booleans.
Note: as Booleans cannot be saved in JSOn, which WORC later does, this object returns strings.
- __dict__ = mappingproxy({'__module__': 'WORC.classification.AdvancedSampler', '__doc__': '\n Uniform distribution thresholded at a certain value to output booleans.\n\n Note: as Booleans cannot be saved in JSOn, which WORC later does, this\n object returns strings.\n\n ', '__init__': <function boolean_uniform.__init__>, 'rvs': <function boolean_uniform.rvs>, '__dict__': <attribute '__dict__' of 'boolean_uniform' objects>, '__weakref__': <attribute '__weakref__' of 'boolean_uniform' objects>, '__annotations__': {}})¶
- __init__(loc=0, scale=1, threshold=0.5)[source]¶
Initialize self. See help(type(self)) for accurate signature.
- __module__ = 'WORC.classification.AdvancedSampler'¶
- __weakref__¶
list of weak references to the object (if defined)
- class WORC.classification.AdvancedSampler.discrete_uniform(loc=- 1, scale=0)[source]¶
Bases:
object
- __dict__ = mappingproxy({'__module__': 'WORC.classification.AdvancedSampler', '__init__': <function discrete_uniform.__init__>, 'rvs': <function discrete_uniform.rvs>, '__dict__': <attribute '__dict__' of 'discrete_uniform' objects>, '__weakref__': <attribute '__weakref__' of 'discrete_uniform' objects>, '__doc__': None, '__annotations__': {}})¶
- __module__ = 'WORC.classification.AdvancedSampler'¶
- __weakref__¶
list of weak references to the object (if defined)
- class WORC.classification.AdvancedSampler.exp_uniform(loc=- 1, scale=0, base=2.718281828459045)[source]¶
Bases:
object
- __dict__ = mappingproxy({'__module__': 'WORC.classification.AdvancedSampler', '__init__': <function exp_uniform.__init__>, 'rvs': <function exp_uniform.rvs>, '__dict__': <attribute '__dict__' of 'exp_uniform' objects>, '__weakref__': <attribute '__weakref__' of 'exp_uniform' objects>, '__doc__': None, '__annotations__': {}})¶
- __init__(loc=- 1, scale=0, base=2.718281828459045)[source]¶
Initialize self. See help(type(self)) for accurate signature.
- __module__ = 'WORC.classification.AdvancedSampler'¶
- __weakref__¶
list of weak references to the object (if defined)
- class WORC.classification.AdvancedSampler.log_uniform(loc=- 1, scale=0, base=10)[source]¶
Bases:
object
- __dict__ = mappingproxy({'__module__': 'WORC.classification.AdvancedSampler', '__init__': <function log_uniform.__init__>, 'rvs': <function log_uniform.rvs>, '__dict__': <attribute '__dict__' of 'log_uniform' objects>, '__weakref__': <attribute '__weakref__' of 'log_uniform' objects>, '__doc__': None, '__annotations__': {}})¶
- __init__(loc=- 1, scale=0, base=10)[source]¶
Initialize self. See help(type(self)) for accurate signature.
- __module__ = 'WORC.classification.AdvancedSampler'¶
- __weakref__¶
list of weak references to the object (if defined)
ObjectSampler
Module¶
- class WORC.classification.ObjectSampler.ObjectSampler(method, random_seed, sampling_strategy='auto', n_jobs=1, n_neighbors=3, k_neighbors=5, threshold_cleaning=0.5, verbose=True)[source]¶
Bases:
object
Samples objects for learning based on various under-, over- and combined sampling methods.
The choice of included methods is largely based on:
He, Haibo, and Edwardo A. Garcia. “Learning from imbalanced data.” IEEE Transactions on Knowledge & Data Engineering 9 (2008): 1263-1284.
- __dict__ = mappingproxy({'__module__': 'WORC.classification.ObjectSampler', '__doc__': '\n Samples objects for learning based on various under-, over- and combined sampling methods.\n\n The choice of included methods is largely based on:\n\n He, Haibo, and Edwardo A. Garcia. "Learning from imbalanced data."\n IEEE Transactions on Knowledge & Data Engineering 9 (2008): 1263-1284.\n\n ', '__init__': <function ObjectSampler.__init__>, 'init_RandomUnderSampling': <function ObjectSampler.init_RandomUnderSampling>, 'init_NearMiss': <function ObjectSampler.init_NearMiss>, 'init_NeighbourhoodCleaningRule': <function ObjectSampler.init_NeighbourhoodCleaningRule>, 'init_RandomOverSampling': <function ObjectSampler.init_RandomOverSampling>, 'init_ADASYN': <function ObjectSampler.init_ADASYN>, 'init_BorderlineSMOTE': <function ObjectSampler.init_BorderlineSMOTE>, 'init_SMOTE': <function ObjectSampler.init_SMOTE>, 'init_SMOTEENN': <function ObjectSampler.init_SMOTEENN>, 'init_SMOTETomek': <function ObjectSampler.init_SMOTETomek>, 'fit': <function ObjectSampler.fit>, 'transform': <function ObjectSampler.transform>, '__dict__': <attribute '__dict__' of 'ObjectSampler' objects>, '__weakref__': <attribute '__weakref__' of 'ObjectSampler' objects>, '__annotations__': {}})¶
- __init__(method, random_seed, sampling_strategy='auto', n_jobs=1, n_neighbors=3, k_neighbors=5, threshold_cleaning=0.5, verbose=True)[source]¶
Initialize object.
- __module__ = 'WORC.classification.ObjectSampler'¶
- __weakref__¶
list of weak references to the object (if defined)
RankedSVM
Module¶
- WORC.classification.RankedSVM.RankSVM_test(test_data, num_class, Weights, Bias, SVs, svm='Poly', gamma=0.05, coefficient=0.05, degree=3)[source]¶
- WORC.classification.RankedSVM.RankSVM_test_original(test_data, test_target, Weights, Bias, SVs, svm='Poly', gamma=0.05, coefficient=0.05, degree=3)[source]¶
- WORC.classification.RankedSVM.RankSVM_train(train_data, train_target, cost=1, lambda_tol=1e-06, norm_tol=0.0001, max_iter=500, svm='Poly', gamma=0.05, coefficient=0.05, degree=3)[source]¶
- WORC.classification.RankedSVM.RankSVM_train_old(train_data, train_target, cost=1, lambda_tol=1e-06, norm_tol=0.0001, max_iter=500, svm='Poly', gamma=0.05, coefficient=0.05, degree=3)[source]¶
Weights,Bias,SVs = RankSVM_train(train_data,train_target,cost,lambda_tol,norm_tol,max_iter,svm,gamma,coefficient,degree)
Description
- RankSVM_train takes,
train_data - An MxN array, the ith instance of training instance is stored in train_data[i,:] train_target - A QxM array, if the ith training instance belongs to the jth class, then train_target[j,i] equals +1, otherwise train_target(j,i) equals -1
- svm - svm gives the type of svm used in training, which can take the value of ‘RBF’, ‘Poly’ or ‘Linear’; svm.para gives the corresponding parameters used for the svm:
if svm is ‘RBF’, then gamma gives the value of gamma, where the kernel is exp(-Gamma*|x[i]-x[j]|^2)
if svm is ‘Poly’, then three values are used gamma, coefficient, and degree respectively, where the kernel is (gamma*<x[i],x[j]>+coefficient)^degree.
if svm is ‘Linear’, then svm is [].
cost - The value of ‘C’ used in the SVM, default=1 lambda_tol - The tolerance value for lambda described in the appendix of [1]; default value is 1e-6 norm_tol - The tolerance value for difference between alpha(p+1) and alpha(p) described in the appendix of [1]; default value is 1e-4 max_iter - The maximum number of iterations for RankSVM, default=500
- and returns,
Weights - The value for beta[ki] as described in the appendix of [1] is stored in Weights[k,i] Bias - The value for b[i] as described in the appendix of [1] is stored in Bias[1,i] SVs - The ith support vector is stored in SVs[:,i]
For more details,please refer to [1] and [2].
SearchCV
Module¶
- class WORC.classification.SearchCV.BaseSearchCV(param_distributions={}, n_iter=10, scoring=None, fit_params=None, n_jobs=1, iid=True, refit=True, cv=None, verbose=0, pre_dispatch='2*n_jobs', random_state=None, error_score='raise', return_train_score=True, n_jobspercore=100, maxlen=100, fastr_plugin=None, memory='2G', ranking_score='test_score', refit_workflows=False)[source]¶
Bases:
sklearn.base.BaseEstimator
,sklearn.base.MetaEstimatorMixin
Base class for hyper parameter search with cross-validation.
- __abstractmethods__ = frozenset({'__init__'})¶
- abstract __init__(param_distributions={}, n_iter=10, scoring=None, fit_params=None, n_jobs=1, iid=True, refit=True, cv=None, verbose=0, pre_dispatch='2*n_jobs', random_state=None, error_score='raise', return_train_score=True, n_jobspercore=100, maxlen=100, fastr_plugin=None, memory='2G', ranking_score='test_score', refit_workflows=False)[source]¶
Initialize SearchCV Object.
- __module__ = 'WORC.classification.SearchCV'¶
- create_ensemble(X_train, Y_train, verbose=None, initialize=True, scoring=None, method=50, overfit_scaler=False)[source]¶
Create ensemble of multiple workflows.
Create an (optimal) ensemble of a combination of hyperparameter settings and the associated groupsels, PCAs, estimators etc.
Based on Caruana et al. 2004, but a little different:
Recreate the training/validation splits for a n-fold cross validation.
- For each fold:
Start with an empty ensemble
Create starting ensemble by adding N individually best performing models on the validation set. N is tuned on the validation set.
Add model that improves ensemble performance on validation set the most, with replacement.
Repeat (c) untill performance does not increase
The performance metric is the same as for the original hyperparameter search, i.e. probably the F1-score for classification and r2-score for regression. However, we recommend using the SAR score, as this is more universal.
Method: top50 or Caruana
- decision_function(X)[source]¶
Call decision_function on the estimator with the best found parameters.
Only available if
refit=True
and the underlying estimator supportsdecision_function
.- Xindexable, length n_samples
Must fulfill the input assumptions of the underlying estimator.
- inverse_transform(Xt)[source]¶
Call inverse_transform on the estimator with the best found params.
Only available if the underlying estimator implements
inverse_transform
andrefit=True
.- Xtindexable, length n_samples
Must fulfill the input assumptions of the underlying estimator.
- predict(X)[source]¶
Call predict on the estimator with the best found parameters.
Only available if
refit=True
and the underlying estimator supportspredict
.- Xindexable, length n_samples
Must fulfill the input assumptions of the underlying estimator.
- predict_log_proba(X)[source]¶
Call predict_log_proba on the estimator with the best found parameters.
Only available if
refit=True
and the underlying estimator supportspredict_log_proba
.- Xindexable, length n_samples
Must fulfill the input assumptions of the underlying estimator.
- predict_proba(X)[source]¶
Call predict_proba on the estimator with the best found parameters.
Only available if
refit=True
and the underlying estimator supportspredict_proba
.- Xindexable, length n_samples
Must fulfill the input assumptions of the underlying estimator.
- preprocess(X, y=None, training=False)[source]¶
Apply the available preprocssing methods to the features.
- process_fit(n_splits, parameters_all, test_sample_counts, test_score_dicts, train_score_dicts, fit_time, score_time, cv_iter, X, y, fitted_workflows=None)[source]¶
Process a fit.
Process the outcomes of a SearchCV fit and find the best settings over all cross validations from all hyperparameters tested
Very similar to the _format_results function or the original SearchCV.
- refit_and_score(X, y, parameters_all, train, test, verbose=None)[source]¶
Refit the base estimator and attributes such as GroupSel.
- X: array, mandatory
Array containingfor each object (rows) the feature values (1st Column) and the associated feature label (2nd Column).
- y: list(?), mandatory
List containing the labels of the objects.
- parameters_all: dictionary, mandatory
Contains the settings used for the all preprocessing functions and the fitting. TODO: Create a default object and show the fields.
- train: list, mandatory
Indices of the objects to be used as training set.
- test: list, mandatory
Indices of the objects to be used as testing set.
- score(X, y=None)[source]¶
Compute the score (i.e. probability) on a given data.
This uses the score defined by
scoring
where provided, and thebest_estimator_.score
method otherwise.- Xarray-like, shape = [n_samples, n_features]
Input data, where n_samples is the number of samples and n_features is the number of features.
- yarray-like, shape = [n_samples] or [n_samples, n_output], optional
Target relative to X for classification or regression; None for unsupervised learning.
score : float
- class WORC.classification.SearchCV.BaseSearchCVJoblib(param_distributions={}, n_iter=10, scoring=None, fit_params=None, n_jobs=1, iid=True, refit=True, cv=None, verbose=0, pre_dispatch='2*n_jobs', random_state=None, error_score='raise', return_train_score=True, n_jobspercore=100, maxlen=100, fastr_plugin=None, memory='2G', ranking_score='test_score', refit_workflows=False)[source]¶
Bases:
WORC.classification.SearchCV.BaseSearchCV
Base class for hyper parameter search with cross-validation.
- __abstractmethods__ = frozenset({'__init__'})¶
- __module__ = 'WORC.classification.SearchCV'¶
- class WORC.classification.SearchCV.BaseSearchCVfastr(param_distributions={}, n_iter=10, scoring=None, fit_params=None, n_jobs=1, iid=True, refit=True, cv=None, verbose=0, pre_dispatch='2*n_jobs', random_state=None, error_score='raise', return_train_score=True, n_jobspercore=100, maxlen=100, fastr_plugin=None, memory='2G', ranking_score='test_score', refit_workflows=False)[source]¶
Bases:
WORC.classification.SearchCV.BaseSearchCV
Base class for hyper parameter search with cross-validation.
- __abstractmethods__ = frozenset({'__init__'})¶
- __module__ = 'WORC.classification.SearchCV'¶
- class WORC.classification.SearchCV.Ensemble(estimators)[source]¶
Bases:
sklearn.base.BaseEstimator
,sklearn.base.MetaEstimatorMixin
Ensemble of BaseSearchCV Estimators.
- __abstractmethods__ = frozenset({})¶
- __module__ = 'WORC.classification.SearchCV'¶
- decision_function(X)[source]¶
Call decision_function on the estimator with the best found parameters.
Only available if
refit=True
and the underlying estimator supportsdecision_function
.- Xindexable, length n_samples
Must fulfill the input assumptions of the underlying estimator.
- inverse_transform(Xt)[source]¶
Call inverse_transform on the estimator with the best found params.
Only available if the underlying estimator implements
inverse_transform
andrefit=True
.- Xtindexable, length n_samples
Must fulfill the input assumptions of the underlying estimator.
- predict(X)[source]¶
Call predict on the estimator with the best found parameters.
Only available if
refit=True
and the underlying estimator supportspredict
.- Xindexable, length n_samples
Must fulfill the input assumptions of the underlying estimator.
- predict_log_proba(X)[source]¶
Call predict_log_proba on the estimator with the best found parameters.
Only available if
refit=True
and the underlying estimator supportspredict_log_proba
.- Xindexable, length n_samples
Must fulfill the input assumptions of the underlying estimator.
- class WORC.classification.SearchCV.GridSearchCVJoblib(estimator, param_grid, scoring=None, fit_params=None, n_jobs=1, iid=True, refit=True, cv=None, verbose=0, pre_dispatch='2*n_jobs', error_score='raise', return_train_score=True)[source]¶
Bases:
WORC.classification.SearchCV.BaseSearchCVJoblib
Exhaustive search over specified parameter values for an estimator.
Important members are fit, predict.
GridSearchCV implements a “fit” and a “score” method. It also implements “predict”, “predict_proba”, “decision_function”, “transform” and “inverse_transform” if they are implemented in the estimator used.
The parameters of the estimator used to apply these methods are optimized by cross-validated grid-search over a parameter grid.
Read more in the sklearn user guide.
- estimatorestimator object.
This is assumed to implement the scikit-learn estimator interface. Either estimator needs to provide a
score
function, orscoring
must be passed.- param_griddict or list of dictionaries
Dictionary with parameters names (string) as keys and lists of parameter settings to try as values, or a list of such dictionaries, in which case the grids spanned by each dictionary in the list are explored. This enables searching over any sequence of parameter settings.
- scoringstring, callable or None, default=None
A string (see model evaluation documentation) or a scorer callable object / function with signature
scorer(estimator, X, y)
. IfNone
, thescore
method of the estimator is used.- fit_paramsdict, optional
Parameters to pass to the fit method.
- n_jobsint, default=1
Number of jobs to run in parallel.
- pre_dispatchint, or string, optional
Controls the number of jobs that get dispatched during parallel execution. Reducing this number can be useful to avoid an explosion of memory consumption when more jobs get dispatched than CPUs can process. This parameter can be:
None, in which case all the jobs are immediately created and spawned. Use this for lightweight and fast-running jobs, to avoid delays due to on-demand spawning of the jobs
An int, giving the exact number of total jobs that are spawned
A string, giving an expression as a function of n_jobs, as in ‘2*n_jobs’
- iidboolean, default=True
If True, the data is assumed to be identically distributed across the folds, and the loss minimized is the total loss per sample, and not the mean loss across the folds.
- cvint, cross-validation generator or an iterable, optional
Determines the cross-validation splitting strategy. Possible inputs for cv are:
None, to use the default 3-fold cross validation,
integer, to specify the number of folds in a (Stratified)KFold,
An object to be used as a cross-validation generator.
An iterable yielding train, test splits.
For integer/None inputs, if the estimator is a classifier and
y
is either binary or multiclass,StratifiedKFold
is used. In all other cases,KFold
is used.Refer sklearn user guide for the various cross-validation strategies that can be used here.
- refitboolean, default=True
Refit the best estimator with the entire dataset. If “False”, it is impossible to make predictions using this GridSearchCV instance after fitting.
- verboseinteger
Controls the verbosity: the higher, the more messages.
- error_score‘raise’ (default) or numeric
Value to assign to the score if an error occurs in estimator fitting. If set to ‘raise’, the error is raised. If a numeric value is given, FitFailedWarning is raised. This parameter does not affect the refit step, which will always raise the error.
- return_train_scoreboolean, default=True
If
'False'
, thecv_results_
attribute will not include training scores.
>>> from sklearn import svm, datasets >>> from sklearn.model_selection import GridSearchCV >>> iris = datasets.load_iris() >>> parameters = {'kernel':('linear', 'rbf'), 'C':[1, 10]} >>> svr = svm.SVC() >>> clf = GridSearchCV(svr, parameters) >>> clf.fit(iris.data, iris.target) ... GridSearchCV(cv=None, error_score=..., estimator=SVC(C=1.0, cache_size=..., class_weight=..., coef0=..., decision_function_shape=None, degree=..., gamma=..., kernel='rbf', max_iter=-1, probability=False, random_state=None, shrinking=True, tol=..., verbose=False), fit_params={}, iid=..., n_jobs=1, param_grid=..., pre_dispatch=..., refit=..., return_train_score=..., scoring=..., verbose=...) >>> sorted(clf.cv_results_.keys()) ... ['mean_fit_time', 'mean_score_time', 'mean_test_score',... 'mean_train_score', 'param_C', 'param_kernel', 'params',... 'rank_test_score', 'split0_test_score',... 'split0_train_score', 'split1_test_score', 'split1_train_score',... 'split2_test_score', 'split2_train_score',... 'std_fit_time', 'std_score_time', 'std_test_score', 'std_train_score'...]
- cv_results_dict of numpy (masked) ndarrays
A dict with keys as column headers and values as columns, that can be imported into a pandas
DataFrame
.For instance the below given table
param_kernel
param_gamma
param_degree
split0_test_score
…
rank_….
‘poly’
–
2
0.8
…
2
‘poly’
–
3
0.7
…
4
‘rbf’
0.1
–
0.8
…
3
‘rbf’
0.2
–
0.9
…
1
will be represented by a
cv_results_
dict of:{ 'param_kernel': masked_array(data = ['poly', 'poly', 'rbf', 'rbf'], mask = [False False False False]...) 'param_gamma': masked_array(data = [-- -- 0.1 0.2], mask = [ True True False False]...), 'param_degree': masked_array(data = [2.0 3.0 -- --], mask = [False False True True]...), 'split0_test_score' : [0.8, 0.7, 0.8, 0.9], 'split1_test_score' : [0.82, 0.5, 0.7, 0.78], 'mean_test_score' : [0.81, 0.60, 0.75, 0.82], 'std_test_score' : [0.02, 0.01, 0.03, 0.03], 'rank_test_score' : [2, 4, 3, 1], 'split0_train_score' : [0.8, 0.9, 0.7], 'split1_train_score' : [0.82, 0.5, 0.7], 'mean_train_score' : [0.81, 0.7, 0.7], 'std_train_score' : [0.03, 0.03, 0.04], 'mean_fit_time' : [0.73, 0.63, 0.43, 0.49], 'std_fit_time' : [0.01, 0.02, 0.01, 0.01], 'mean_score_time' : [0.007, 0.06, 0.04, 0.04], 'std_score_time' : [0.001, 0.002, 0.003, 0.005], 'params' : [{'kernel': 'poly', 'degree': 2}, ...], }
NOTE that the key
'params'
is used to store a list of parameter settings dict for all the parameter candidates.The
mean_fit_time
,std_fit_time
,mean_score_time
andstd_score_time
are all in seconds.- best_estimator_estimator
Estimator that was chosen by the search, i.e. estimator which gave highest score (or smallest loss if specified) on the left out data. Not available if refit=False.
- best_score_float
Score of best_estimator on the left out data.
- best_params_dict
Parameter setting that gave the best results on the hold out data.
- best_index_int
The index (of the
cv_results_
arrays) which corresponds to the best candidate parameter setting.The dict at
search.cv_results_['params'][search.best_index_]
gives the parameter setting for the best model, that gives the highest mean score (search.best_score_
).- scorer_function
Scorer function used on the held out data to choose the best parameters for the model.
- n_splits_int
The number of cross-validation splits (folds/iterations).
The parameters selected are those that maximize the score of the left out data, unless an explicit score is passed in which case it is used instead.
If n_jobs was set to a value higher than one, the data is copied for each point in the grid (and not n_jobs times). This is done for efficiency reasons if individual jobs take very little time, but may raise errors if the dataset is large and not enough memory is available. A workaround in this case is to set pre_dispatch. Then, the memory is copied only pre_dispatch many times. A reasonable value for pre_dispatch is 2 * n_jobs.
ParameterGrid
:generates all the combinations of a hyperparameter grid.
sklearn.model_selection.train_test_split()
:utility function to split the data into a development set usable for fitting a GridSearchCV instance and an evaluation set for its final evaluation.
sklearn.metrics.make_scorer()
:Make a scorer from a performance metric or loss function.
- __abstractmethods__ = frozenset({})¶
- __init__(estimator, param_grid, scoring=None, fit_params=None, n_jobs=1, iid=True, refit=True, cv=None, verbose=0, pre_dispatch='2*n_jobs', error_score='raise', return_train_score=True)[source]¶
Initialize SearchCV Object.
- __module__ = 'WORC.classification.SearchCV'¶
- fit(X, y=None, groups=None)[source]¶
Run fit with all sets of parameters.
- Xarray-like, shape = [n_samples, n_features]
Training vector, where n_samples is the number of samples and n_features is the number of features.
- yarray-like, shape = [n_samples] or [n_samples, n_output], optional
Target relative to X for classification or regression; None for unsupervised learning.
- groupsarray-like, with shape (n_samples,), optional
Group labels for the samples used while splitting the dataset into train/test set.
- class WORC.classification.SearchCV.GridSearchCVfastr(estimator, param_grid, scoring=None, fit_params=None, n_jobs=1, iid=True, refit=True, cv=None, verbose=0, pre_dispatch='2*n_jobs', error_score='raise', return_train_score=True)[source]¶
Bases:
WORC.classification.SearchCV.BaseSearchCVfastr
Exhaustive search over specified parameter values for an estimator.
Important members are fit, predict.
GridSearchCV implements a “fit” and a “score” method. It also implements “predict”, “predict_proba”, “decision_function”, “transform” and “inverse_transform” if they are implemented in the estimator used.
The parameters of the estimator used to apply these methods are optimized by cross-validated grid-search over a parameter grid.
Read more in the sklearn user guide.
- estimatorestimator object.
This is assumed to implement the scikit-learn estimator interface. Either estimator needs to provide a
score
function, orscoring
must be passed.- param_griddict or list of dictionaries
Dictionary with parameters names (string) as keys and lists of parameter settings to try as values, or a list of such dictionaries, in which case the grids spanned by each dictionary in the list are explored. This enables searching over any sequence of parameter settings.
- scoringstring, callable or None, default=None
A string (see model evaluation documentation) or a scorer callable object / function with signature
scorer(estimator, X, y)
. IfNone
, thescore
method of the estimator is used.- fit_paramsdict, optional
Parameters to pass to the fit method.
- n_jobsint, default=1
Number of jobs to run in parallel.
- pre_dispatchint, or string, optional
Controls the number of jobs that get dispatched during parallel execution. Reducing this number can be useful to avoid an explosion of memory consumption when more jobs get dispatched than CPUs can process. This parameter can be:
None, in which case all the jobs are immediately created and spawned. Use this for lightweight and fast-running jobs, to avoid delays due to on-demand spawning of the jobs
An int, giving the exact number of total jobs that are spawned
A string, giving an expression as a function of n_jobs, as in ‘2*n_jobs’
- iidboolean, default=True
If True, the data is assumed to be identically distributed across the folds, and the loss minimized is the total loss per sample, and not the mean loss across the folds.
- cvint, cross-validation generator or an iterable, optional
Determines the cross-validation splitting strategy. Possible inputs for cv are:
None, to use the default 3-fold cross validation,
integer, to specify the number of folds in a (Stratified)KFold,
An object to be used as a cross-validation generator.
An iterable yielding train, test splits.
For integer/None inputs, if the estimator is a classifier and
y
is either binary or multiclass,StratifiedKFold
is used. In all other cases,KFold
is used.Refer the sklearn user guide for the various cross-validation strategies that can be used here.
- refitboolean, default=True
Refit the best estimator with the entire dataset. If “False”, it is impossible to make predictions using this GridSearchCV instance after fitting.
- verboseinteger
Controls the verbosity: the higher, the more messages.
- error_score‘raise’ (default) or numeric
Value to assign to the score if an error occurs in estimator fitting. If set to ‘raise’, the error is raised. If a numeric value is given, FitFailedWarning is raised. This parameter does not affect the refit step, which will always raise the error.
- return_train_scoreboolean, default=True
If
'False'
, thecv_results_
attribute will not include training scores.
>>> from sklearn import svm, datasets >>> from sklearn.model_selection import GridSearchCV >>> iris = datasets.load_iris() >>> parameters = {'kernel':('linear', 'rbf'), 'C':[1, 10]} >>> svr = svm.SVC() >>> clf = GridSearchCV(svr, parameters) >>> clf.fit(iris.data, iris.target) ... GridSearchCV(cv=None, error_score=..., estimator=SVC(C=1.0, cache_size=..., class_weight=..., coef0=..., decision_function_shape=None, degree=..., gamma=..., kernel='rbf', max_iter=-1, probability=False, random_state=None, shrinking=True, tol=..., verbose=False), fit_params={}, iid=..., n_jobs=1, param_grid=..., pre_dispatch=..., refit=..., return_train_score=..., scoring=..., verbose=...) >>> sorted(clf.cv_results_.keys()) ... ['mean_fit_time', 'mean_score_time', 'mean_test_score',... 'mean_train_score', 'param_C', 'param_kernel', 'params',... 'rank_test_score', 'split0_test_score',... 'split0_train_score', 'split1_test_score', 'split1_train_score',... 'split2_test_score', 'split2_train_score',... 'std_fit_time', 'std_score_time', 'std_test_score', 'std_train_score'...]
- cv_results_dict of numpy (masked) ndarrays
A dict with keys as column headers and values as columns, that can be imported into a pandas
DataFrame
.For instance the below given table
param_kernel
param_gamma
param_degree
split0_test_score
…
rank_….
‘poly’
–
2
0.8
…
2
‘poly’
–
3
0.7
…
4
‘rbf’
0.1
–
0.8
…
3
‘rbf’
0.2
–
0.9
…
1
will be represented by a
cv_results_
dict of:{ 'param_kernel': masked_array(data = ['poly', 'poly', 'rbf', 'rbf'], mask = [False False False False]...) 'param_gamma': masked_array(data = [-- -- 0.1 0.2], mask = [ True True False False]...), 'param_degree': masked_array(data = [2.0 3.0 -- --], mask = [False False True True]...), 'split0_test_score' : [0.8, 0.7, 0.8, 0.9], 'split1_test_score' : [0.82, 0.5, 0.7, 0.78], 'mean_test_score' : [0.81, 0.60, 0.75, 0.82], 'std_test_score' : [0.02, 0.01, 0.03, 0.03], 'rank_test_score' : [2, 4, 3, 1], 'split0_train_score' : [0.8, 0.9, 0.7], 'split1_train_score' : [0.82, 0.5, 0.7], 'mean_train_score' : [0.81, 0.7, 0.7], 'std_train_score' : [0.03, 0.03, 0.04], 'mean_fit_time' : [0.73, 0.63, 0.43, 0.49], 'std_fit_time' : [0.01, 0.02, 0.01, 0.01], 'mean_score_time' : [0.007, 0.06, 0.04, 0.04], 'std_score_time' : [0.001, 0.002, 0.003, 0.005], 'params' : [{'kernel': 'poly', 'degree': 2}, ...], }
NOTE that the key
'params'
is used to store a list of parameter settings dict for all the parameter candidates.The
mean_fit_time
,std_fit_time
,mean_score_time
andstd_score_time
are all in seconds.- best_estimator_estimator
Estimator that was chosen by the search, i.e. estimator which gave highest score (or smallest loss if specified) on the left out data. Not available if refit=False.
- best_score_float
Score of best_estimator on the left out data.
- best_params_dict
Parameter setting that gave the best results on the hold out data.
- best_index_int
The index (of the
cv_results_
arrays) which corresponds to the best candidate parameter setting.The dict at
search.cv_results_['params'][search.best_index_]
gives the parameter setting for the best model, that gives the highest mean score (search.best_score_
).- scorer_function
Scorer function used on the held out data to choose the best parameters for the model.
- n_splits_int
The number of cross-validation splits (folds/iterations).
The parameters selected are those that maximize the score of the left out data, unless an explicit score is passed in which case it is used instead.
If n_jobs was set to a value higher than one, the data is copied for each point in the grid (and not n_jobs times). This is done for efficiency reasons if individual jobs take very little time, but may raise errors if the dataset is large and not enough memory is available. A workaround in this case is to set pre_dispatch. Then, the memory is copied only pre_dispatch many times. A reasonable value for pre_dispatch is 2 * n_jobs.
ParameterGrid
:generates all the combinations of a hyperparameter grid.
sklearn.model_selection.train_test_split()
:utility function to split the data into a development set usable for fitting a GridSearchCV instance and an evaluation set for its final evaluation.
sklearn.metrics.make_scorer()
:Make a scorer from a performance metric or loss function.
- __abstractmethods__ = frozenset({})¶
- __init__(estimator, param_grid, scoring=None, fit_params=None, n_jobs=1, iid=True, refit=True, cv=None, verbose=0, pre_dispatch='2*n_jobs', error_score='raise', return_train_score=True)[source]¶
Initialize SearchCV Object.
- __module__ = 'WORC.classification.SearchCV'¶
- fit(X, y=None, groups=None)[source]¶
Run fit with all sets of parameters.
- Xarray-like, shape = [n_samples, n_features]
Training vector, where n_samples is the number of samples and n_features is the number of features.
- yarray-like, shape = [n_samples] or [n_samples, n_output], optional
Target relative to X for classification or regression; None for unsupervised learning.
- groupsarray-like, with shape (n_samples,), optional
Group labels for the samples used while splitting the dataset into train/test set.
- class WORC.classification.SearchCV.RandomizedSearchCVJoblib(param_distributions={}, n_iter=10, scoring=None, fit_params=None, n_jobs=1, iid=True, refit=True, cv=None, verbose=0, pre_dispatch='2*n_jobs', random_state=None, error_score='raise', return_train_score=True, n_jobspercore=100, maxlen=100, ranking_score='test_score')[source]¶
Bases:
WORC.classification.SearchCV.BaseSearchCVJoblib
Randomized search on hyper parameters.
RandomizedSearchCV implements a “fit” and a “score” method. It also implements “predict”, “predict_proba”, “decision_function”, “transform” and “inverse_transform” if they are implemented in the estimator used.
The parameters of the estimator used to apply these methods are optimized by cross-validated search over parameter settings.
In contrast to GridSearchCV, not all parameter values are tried out, but rather a fixed number of parameter settings is sampled from the specified distributions. The number of parameter settings that are tried is given by n_iter.
If all parameters are presented as a list, sampling without replacement is performed. If at least one parameter is given as a distribution, sampling with replacement is used. It is highly recommended to use continuous distributions for continuous parameters.
Read more in the sklearn user guide.
- estimatorestimator object.
A object of that type is instantiated for each grid point. This is assumed to implement the scikit-learn estimator interface. Either estimator needs to provide a
score
function, orscoring
must be passed.- param_distributionsdict
Dictionary with parameters names (string) as keys and distributions or lists of parameters to try. Distributions must provide a
rvs
method for sampling (such as those from scipy.stats.distributions). If a list is given, it is sampled uniformly.- n_iterint, default=10
Number of parameter settings that are sampled. n_iter trades off runtime vs quality of the solution.
- scoringstring, callable or None, default=None
A string (see model evaluation documentation) or a scorer callable object / function with signature
scorer(estimator, X, y)
. IfNone
, thescore
method of the estimator is used.- fit_paramsdict, optional
Parameters to pass to the fit method.
- n_jobsint, default=1
Number of jobs to run in parallel.
- pre_dispatchint, or string, optional
Controls the number of jobs that get dispatched during parallel execution. Reducing this number can be useful to avoid an explosion of memory consumption when more jobs get dispatched than CPUs can process. This parameter can be:
None, in which case all the jobs are immediately created and spawned. Use this for lightweight and fast-running jobs, to avoid delays due to on-demand spawning of the jobs
An int, giving the exact number of total jobs that are spawned
A string, giving an expression as a function of n_jobs, as in ‘2*n_jobs’
- iidboolean, default=True
If True, the data is assumed to be identically distributed across the folds, and the loss minimized is the total loss per sample, and not the mean loss across the folds.
- cvint, cross-validation generator or an iterable, optional
Determines the cross-validation splitting strategy. Possible inputs for cv are:
None, to use the default 3-fold cross validation,
integer, to specify the number of folds in a (Stratified)KFold,
An object to be used as a cross-validation generator.
An iterable yielding train, test splits.
For integer/None inputs, if the estimator is a classifier and
y
is either binary or multiclass,StratifiedKFold
is used. In all other cases,KFold
is used.Refer sklearn user guide for the various cross-validation strategies that can be used here.
- refitboolean, default=True
Refit the best estimator with the entire dataset. If “False”, it is impossible to make predictions using this RandomizedSearchCV instance after fitting.
- verboseinteger
Controls the verbosity: the higher, the more messages.
- random_stateint or RandomState
Pseudo random number generator state used for random uniform sampling from lists of possible values instead of scipy.stats distributions.
- error_score‘raise’ (default) or numeric
Value to assign to the score if an error occurs in estimator fitting. If set to ‘raise’, the error is raised. If a numeric value is given, FitFailedWarning is raised. This parameter does not affect the refit step, which will always raise the error.
- return_train_scoreboolean, default=True
If
'False'
, thecv_results_
attribute will not include training scores.
- cv_results_dict of numpy (masked) ndarrays
A dict with keys as column headers and values as columns, that can be imported into a pandas
DataFrame
.For instance the below given table
param_kernel
param_gamma
split0_test_score
…
rank_test_score
‘rbf’
0.1
0.8
…
2
‘rbf’
0.2
0.9
…
1
‘rbf’
0.3
0.7
…
1
will be represented by a
cv_results_
dict of:{ 'param_kernel' : masked_array(data = ['rbf', 'rbf', 'rbf'], mask = False), 'param_gamma' : masked_array(data = [0.1 0.2 0.3], mask = False), 'split0_test_score' : [0.8, 0.9, 0.7], 'split1_test_score' : [0.82, 0.5, 0.7], 'mean_test_score' : [0.81, 0.7, 0.7], 'std_test_score' : [0.02, 0.2, 0.], 'rank_test_score' : [3, 1, 1], 'split0_train_score' : [0.8, 0.9, 0.7], 'split1_train_score' : [0.82, 0.5, 0.7], 'mean_train_score' : [0.81, 0.7, 0.7], 'std_train_score' : [0.03, 0.03, 0.04], 'mean_fit_time' : [0.73, 0.63, 0.43, 0.49], 'std_fit_time' : [0.01, 0.02, 0.01, 0.01], 'mean_score_time' : [0.007, 0.06, 0.04, 0.04], 'std_score_time' : [0.001, 0.002, 0.003, 0.005], 'params' : [{'kernel' : 'rbf', 'gamma' : 0.1}, ...], }
NOTE that the key
'params'
is used to store a list of parameter settings dict for all the parameter candidates.The
mean_fit_time
,std_fit_time
,mean_score_time
andstd_score_time
are all in seconds.- best_estimator_estimator
Estimator that was chosen by the search, i.e. estimator which gave highest score (or smallest loss if specified) on the left out data. Not available if refit=False.
- best_score_float
Score of best_estimator on the left out data.
- best_params_dict
Parameter setting that gave the best results on the hold out data.
- best_index_int
The index (of the
cv_results_
arrays) which corresponds to the best candidate parameter setting.The dict at
search.cv_results_['params'][search.best_index_]
gives the parameter setting for the best model, that gives the highest mean score (search.best_score_
).- scorer_function
Scorer function used on the held out data to choose the best parameters for the model.
- n_splits_int
The number of cross-validation splits (folds/iterations).
The parameters selected are those that maximize the score of the held-out data, according to the scoring parameter.
If n_jobs was set to a value higher than one, the data is copied for each parameter setting(and not n_jobs times). This is done for efficiency reasons if individual jobs take very little time, but may raise errors if the dataset is large and not enough memory is available. A workaround in this case is to set pre_dispatch. Then, the memory is copied only pre_dispatch many times. A reasonable value for pre_dispatch is 2 * n_jobs.
GridSearchCV
:Does exhaustive search over a grid of parameters.
ParameterSampler
:A generator over parameter settins, constructed from param_distributions.
- __abstractmethods__ = frozenset({})¶
- __init__(param_distributions={}, n_iter=10, scoring=None, fit_params=None, n_jobs=1, iid=True, refit=True, cv=None, verbose=0, pre_dispatch='2*n_jobs', random_state=None, error_score='raise', return_train_score=True, n_jobspercore=100, maxlen=100, ranking_score='test_score')[source]¶
Initialize SearchCV Object.
- __module__ = 'WORC.classification.SearchCV'¶
- fit(X, y=None, groups=None)[source]¶
Run fit on the estimator with randomly drawn parameters.
- Xarray-like, shape = [n_samples, n_features]
Training vector, where n_samples in the number of samples and n_features is the number of features.
- yarray-like, shape = [n_samples] or [n_samples, n_output], optional
Target relative to X for classification or regression; None for unsupervised learning.
- groupsarray-like, with shape (n_samples,), optional
Group labels for the samples used while splitting the dataset into train/test set.
- class WORC.classification.SearchCV.RandomizedSearchCVfastr(param_distributions={}, n_iter=10, scoring=None, fit_params=None, n_jobs=1, iid=True, refit=True, cv=None, verbose=0, pre_dispatch='2*n_jobs', random_state=None, error_score='raise', return_train_score=True, n_jobspercore=100, fastr_plugin=None, memory='2G', maxlen=100, ranking_score='test_score', refit_workflows=False)[source]¶
Bases:
WORC.classification.SearchCV.BaseSearchCVfastr
Randomized search on hyper parameters.
RandomizedSearchCV implements a “fit” and a “score” method. It also implements “predict”, “predict_proba”, “decision_function”, “transform” and “inverse_transform” if they are implemented in the estimator used.
The parameters of the estimator used to apply these methods are optimized by cross-validated search over parameter settings.
In contrast to GridSearchCV, not all parameter values are tried out, but rather a fixed number of parameter settings is sampled from the specified distributions. The number of parameter settings that are tried is given by n_iter.
If all parameters are presented as a list, sampling without replacement is performed. If at least one parameter is given as a distribution, sampling with replacement is used. It is highly recommended to use continuous distributions for continuous parameters.
Read more in the sklearn user guide.
- estimatorestimator object.
A object of that type is instantiated for each grid point. This is assumed to implement the scikit-learn estimator interface. Either estimator needs to provide a
score
function, orscoring
must be passed.- param_distributionsdict
Dictionary with parameters names (string) as keys and distributions or lists of parameters to try. Distributions must provide a
rvs
method for sampling (such as those from scipy.stats.distributions). If a list is given, it is sampled uniformly.- n_iterint, default=10
Number of parameter settings that are sampled. n_iter trades off runtime vs quality of the solution.
- scoringstring, callable or None, default=None
A string (see model evaluation documentation) or a scorer callable object / function with signature
scorer(estimator, X, y)
. IfNone
, thescore
method of the estimator is used.- fit_paramsdict, optional
Parameters to pass to the fit method.
- n_jobsint, default=1
Number of jobs to run in parallel.
- pre_dispatchint, or string, optional
Controls the number of jobs that get dispatched during parallel execution. Reducing this number can be useful to avoid an explosion of memory consumption when more jobs get dispatched than CPUs can process. This parameter can be:
None, in which case all the jobs are immediately created and spawned. Use this for lightweight and fast-running jobs, to avoid delays due to on-demand spawning of the jobs
An int, giving the exact number of total jobs that are spawned
A string, giving an expression as a function of n_jobs, as in ‘2*n_jobs’
- iidboolean, default=True
If True, the data is assumed to be identically distributed across the folds, and the loss minimized is the total loss per sample, and not the mean loss across the folds.
- cvint, cross-validation generator or an iterable, optional
Determines the cross-validation splitting strategy. Possible inputs for cv are:
None, to use the default 3-fold cross validation,
integer, to specify the number of folds in a (Stratified)KFold,
An object to be used as a cross-validation generator.
An iterable yielding train, test splits.
For integer/None inputs, if the estimator is a classifier and
y
is either binary or multiclass,StratifiedKFold
is used. In all other cases,KFold
is used.Refer the sklearn user guide for the various cross-validation strategies that can be used here.
- refitboolean, default=True
Refit the best estimator with the entire dataset. If “False”, it is impossible to make predictions using this RandomizedSearchCV instance after fitting.
- verboseinteger
Controls the verbosity: the higher, the more messages.
- random_stateint or RandomState
Pseudo random number generator state used for random uniform sampling from lists of possible values instead of scipy.stats distributions.
- error_score‘raise’ (default) or numeric
Value to assign to the score if an error occurs in estimator fitting. If set to ‘raise’, the error is raised. If a numeric value is given, FitFailedWarning is raised. This parameter does not affect the refit step, which will always raise the error.
- return_train_scoreboolean, default=True
If
'False'
, thecv_results_
attribute will not include training scores.
- cv_results_dict of numpy (masked) ndarrays
A dict with keys as column headers and values as columns, that can be imported into a pandas
DataFrame
.For instance the below given table
param_kernel
param_gamma
split0_test_score
…
rank_test_score
‘rbf’
0.1
0.8
…
2
‘rbf’
0.2
0.9
…
1
‘rbf’
0.3
0.7
…
1
will be represented by a
cv_results_
dict of:{ 'param_kernel' : masked_array(data = ['rbf', 'rbf', 'rbf'], mask = False), 'param_gamma' : masked_array(data = [0.1 0.2 0.3], mask = False), 'split0_test_score' : [0.8, 0.9, 0.7], 'split1_test_score' : [0.82, 0.5, 0.7], 'mean_test_score' : [0.81, 0.7, 0.7], 'std_test_score' : [0.02, 0.2, 0.], 'rank_test_score' : [3, 1, 1], 'split0_train_score' : [0.8, 0.9, 0.7], 'split1_train_score' : [0.82, 0.5, 0.7], 'mean_train_score' : [0.81, 0.7, 0.7], 'std_train_score' : [0.03, 0.03, 0.04], 'mean_fit_time' : [0.73, 0.63, 0.43, 0.49], 'std_fit_time' : [0.01, 0.02, 0.01, 0.01], 'mean_score_time' : [0.007, 0.06, 0.04, 0.04], 'std_score_time' : [0.001, 0.002, 0.003, 0.005], 'params' : [{'kernel' : 'rbf', 'gamma' : 0.1}, ...], }
NOTE that the key
'params'
is used to store a list of parameter settings dict for all the parameter candidates.The
mean_fit_time
,std_fit_time
,mean_score_time
andstd_score_time
are all in seconds.- best_estimator_estimator
Estimator that was chosen by the search, i.e. estimator which gave highest score (or smallest loss if specified) on the left out data. Not available if refit=False.
- best_score_float
Score of best_estimator on the left out data.
- best_params_dict
Parameter setting that gave the best results on the hold out data.
- best_index_int
The index (of the
cv_results_
arrays) which corresponds to the best candidate parameter setting.The dict at
search.cv_results_['params'][search.best_index_]
gives the parameter setting for the best model, that gives the highest mean score (search.best_score_
).- scorer_function
Scorer function used on the held out data to choose the best parameters for the model.
- n_splits_int
The number of cross-validation splits (folds/iterations).
The parameters selected are those that maximize the score of the held-out data, according to the scoring parameter.
If n_jobs was set to a value higher than one, the data is copied for each parameter setting(and not n_jobs times). This is done for efficiency reasons if individual jobs take very little time, but may raise errors if the dataset is large and not enough memory is available. A workaround in this case is to set pre_dispatch. Then, the memory is copied only pre_dispatch many times. A reasonable value for pre_dispatch is 2 * n_jobs.
GridSearchCV
:Does exhaustive search over a grid of parameters.
ParameterSampler
:A generator over parameter settings, constructed from param_distributions.
- __abstractmethods__ = frozenset({})¶
- __init__(param_distributions={}, n_iter=10, scoring=None, fit_params=None, n_jobs=1, iid=True, refit=True, cv=None, verbose=0, pre_dispatch='2*n_jobs', random_state=None, error_score='raise', return_train_score=True, n_jobspercore=100, fastr_plugin=None, memory='2G', maxlen=100, ranking_score='test_score', refit_workflows=False)[source]¶
Initialize SearchCV Object.
- __module__ = 'WORC.classification.SearchCV'¶
- fit(X, y=None, groups=None)[source]¶
Randomized model selection and hyperparameter search.
- Xarray-like, shape = [n_samples, n_features]
Training vector, where n_samples in the number of samples and n_features is the number of features.
- yarray-like, shape = [n_samples] or [n_samples, n_output], optional
Target relative to X for classification or regression; None for unsupervised learning.
- groupsarray-like, with shape (n_samples,), optional
Group labels for the samples used while splitting the dataset into train/test set.
construct_classifier
Module¶
- WORC.classification.construct_classifier.construct_SVM(config, regression=False)[source]¶
Construct a SVM classifier.
- Args:
config (dict): Dictionary of the required config settings features (pandas dataframe): A pandas dataframe containing the features
to be used for classification
- Returns:
SVM/SVR classifier, parameter grid
- WORC.classification.construct_classifier.construct_classifier(config)[source]¶
Interface to create classification.
Different classifications can be created using this common interface
- config: dict, mandatory
Contains the required config settings. See the Github Wiki for all available fields.
- Returns:
Constructed classifier
createfixedsplits
Module¶
crossval
Module¶
- WORC.classification.crossval.LOO_cross_validation(image_features, feature_labels, classes, patient_ids, param_grid, config, modus, test_size, start=0, save_data=None, tempsave=False, tempfolder=None, fixedsplits=None, fixed_seed=False, use_fastr=None, fastr_plugin=None)[source]¶
Cross-validation in which each sample is once used as the test set.
Mostly based on the default sklearn object.
- WORC.classification.crossval.crossval(config, label_data, image_features, param_grid=None, use_fastr=False, fastr_plugin=None, tempsave=False, fixedsplits=None, ensemble={'Use': False}, outputfolder=None, modus='singlelabel')[source]¶
Constructs multiple individual classifiers based on the label settings.
- config: dict, mandatory
Dictionary with config settings. See the Github Wiki for the available fields and formatting.
- label_data: dict, mandatory
Should contain the following: patient_ids (list): ids of the patients, used to keep track of test and
training sets, and label data
- label (list): List of lists, where each list contains the
label status for that patient for each label
- label_name (list): Contains the different names that are stored
in the label object
- image_features: numpy array, mandatory
Consists of a tuple of two lists for each patient: (feature_values, feature_labels)
- param_grid: dictionary, optional
Contains the parameters and their values wich are used in the grid or randomized search hyperparamater optimization. See the construct_classifier function for some examples.
- use_fastr: boolean, default False
If False, parallel execution through Joblib is used for fast execution of the hyperparameter optimization. Especially suited for execution on mutlicore (H)PC’s. The settings used are specified in the config.ini file in the IOparser folder, which you can adjust to your system.
If True, fastr is used to split the hyperparameter optimization in separate jobs. Parameters for the splitting can be specified in the config file. Especially suited for clusters.
- fastr_plugin: string, default None
Determines which plugin is used for fastr executions. When None, uses the default plugin from the fastr config.
- tempsave: boolean, default False
If True, create a .hdf5 file after each Cross-validation containing the classifier and results from that that split. This is written to the GSOut folder in your fastr output mount. If False, only the result of all combined Cross-validations will be saved to a .hdf5 file. This will also be done if set to True.
- fixedsplits: string, optional
By default, random split Cross-validation is used to train and evaluate the machine learning methods. Optionally, you can provide a .xlsx file containing fixed splits to be used. See the Github Wiki for the format.
- ensemble: dictionary, optional
Contains the configuration for constructing an ensemble.
- modus: string, default ‘singlelabel’
Determine whether one-vs-all classification (or regression) for each single label is used (‘singlelabel’) or if multilabel classification is performed (‘multilabel’).
- panda_data: pandas dataframe
Contains all information on the trained classifier.
- WORC.classification.crossval.nocrossval(config, label_data_train, label_data_test, image_features_train, image_features_test, param_grid=None, use_fastr=False, fastr_plugin=None, ensemble={'Use': False}, modus='singlelabel', do_test_RS_Ensemble=False)[source]¶
Constructs multiple individual classifiers based on the label settings.
- Arguments:
config (Dict): Dictionary with config settings label_data (Dict): should contain: patient_ids (list): ids of the patients, used to keep track of test and
training sets, and label data
- label (list): List of lists, where each list contains the
label status for that patient for each label
- label_name (list): Contains the different names that are stored
in the label object
- image_features (numpy array): Consists of a tuple of two lists for each patient:
(feature_values, feature_labels)
- ensemble: dictionary, optional
Contains the configuration for constructing an ensemble.
- modus: string, default ‘singlelabel’
Determine whether one-vs-all classification (or regression) for each single label is used (‘singlelabel’) or if multilabel classification is performed (‘multilabel’).
- Returns:
classifier_data (pandas dataframe)
- WORC.classification.crossval.random_split_cross_validation(image_features, feature_labels, classes, patient_ids, n_iterations, param_grid, config, modus, test_size, start=0, save_data=None, tempsave=False, tempfolder=None, fixedsplits=None, fixed_seed=False, use_fastr=None, fastr_plugin=None, do_test_RS_Ensemble=False)[source]¶
Cross-validation in which data is randomly split in each iteration.
Due to options of doing single-label and multi-label classification, stratified splitting, and regression, we use a manual loop instead of the default scikit-learn object.
- WORC.classification.crossval.test_RS_Ensemble(estimator_input, X_train, Y_train, X_test, Y_test, feature_labels, output_json)[source]¶
Test performance for different random search and ensemble sizes.
This function is written for conducting a specific experiment from the WORC paper to test how the performance varies with varying random search and ensemble sizes. We do not recommend usage in general of this part.
estimators
Module¶
- class WORC.classification.estimators.RankedSVM(cost=1, lambda_tol=1e-06, norm_tol=0.0001, max_iter=500, svm='Poly', gamma=0.05, coefficient=0.05, degree=3)[source]¶
Bases:
sklearn.base.BaseEstimator
,sklearn.base.ClassifierMixin
An example classifier which implements a 1-NN algorithm.
- demo_paramstr, optional
A parameter used for demonstation of how to pass and store paramters.
- X_array, shape = [n_samples, n_features]
The input passed during
fit()
- y_array, shape = [n_samples]
The labels passed during
fit()
- __init__(cost=1, lambda_tol=1e-06, norm_tol=0.0001, max_iter=500, svm='Poly', gamma=0.05, coefficient=0.05, degree=3)[source]¶
Initialize self. See help(type(self)) for accurate signature.
- __module__ = 'WORC.classification.estimators'¶
- fit(X, y)[source]¶
A reference implementation of a fitting function for a classifier.
- Xarray-like, shape = [n_samples, n_features]
The training input samples.
- yarray-like, shape = [n_samples]
The target values. An array of int.
- selfobject
Returns self.
fitandscore
Module¶
- WORC.classification.fitandscore.delete_cc_para(para)[source]¶
Delete all parameters that are involved in classifier construction.
- WORC.classification.fitandscore.delete_nonestimator_parameters(parameters)[source]¶
Delete non-estimator parameters.
Delete all parameters in a parameter dictionary that are not used for the actual estimator.
- WORC.classification.fitandscore.fit_and_score(X, y, scoring, train, test, parameters, fit_params=None, return_train_score=True, return_n_test_samples=True, return_times=True, return_parameters=False, return_estimator=False, error_score='raise', verbose=True, return_all=True, refit_workflows=False)[source]¶
Fit an estimator to a dataset and score the performance.
The following methods can currently be applied as preprocessing before fitting, in this order: 0. Apply OneHotEncoder 1. Apply feature imputation 2. Select features based on feature type group (e.g. shape, histogram). 3. Scale features with e.g. z-scoring. 4. Apply feature selection based on variance of feature among patients. 5. Univariate statistical testing (e.g. t-test, Wilcoxon). 6. Use Relief feature selection. 7. Select features based on a fit with a LASSO model. 8. Select features using PCA. 9. Resampling 10. If a SingleLabel classifier is used for a MultiLabel problem,
a OneVsRestClassifier is employed around it.
All of the steps are optional.
- estimator: sklearn estimator, mandatory
Unfitted estimator which will be fit.
- X: array, mandatory
Array containingfor each object (rows) the feature values (1st Column) and the associated feature label (2nd Column).
- y: list(?), mandatory
List containing the labels of the objects.
- scorer: sklearn scorer, mandatory
Function used as optimization criterion for the hyperparamater optimization.
- train: list, mandatory
Indices of the objects to be used as training set.
- test: list, mandatory
Indices of the objects to be used as testing set.
- parameters: dictionary, mandatory
Contains the settings used for the above preprocessing functions and the fitting. TODO: Create a default object and show the fields.
- fit_params:dictionary, default None
Parameters supplied to the estimator for fitting. See the SKlearn site for the parameters of the estimators.
- return_train_score: boolean, default True
Save the training score to the final SearchCV object.
- return_n_test_samples: boolean, default True
Save the number of times each sample was used in the test set to the final SearchCV object.
- return_times: boolean, default True
Save the time spend for each fit to the final SearchCV object.
- return_parameters: boolean, default True
Return the parameters used in the final fit to the final SearchCV object.
- return_estimatorbool, default=False
Whether to return the fitted estimator.
- error_score: numeric or “raise” by default
Value to assign to the score if an error occurs in estimator fitting. If set to “raise”, the error is raised. If a numeric value is given, FitFailedWarning is raised. This parameter does not affect the refit step, which will always raise the error.
- verbose: boolean, default=True
If True, print intermediate progress to command line. Warnings are always printed.
- return_all: boolean, default=True
If False, only the ret object containing the performance will be returned. If True, the ret object plus all fitted objects will be returned.
Depending on the return_all input parameter, either only ret or all objects below are returned.
- ret: list
Contains optionally the train_scores and the test_scores, fit_time, score_time, parameters_est and parameters_all.
- GroupSel: WORC GroupSel Object
Either None if the groupwise feature selection is not used, or the fitted object.
- VarSel: WORC VarSel Object
Either None if the variance threshold feature selection is not used, or the fitted object.
- SelectModel: WORC SelectModel Object
Either None if the feature selection based on a fittd model is not used, or the fitted object.
- feature_labels: list
Labels of the features. Only one list is returned, not one per feature object, as we assume all samples have the same feature names.
- scaler: scaler object
Either None if feature scaling is not used, or the fitted object.
- encoder: WORC Encoder Object
Either None if feature OneHotEncoding is not used, or the fitted object.
- imputer: WORC Imputater Object
Either None if feature imputation is not used, or the fitted object.
- pca: WORC PCA Object
Either None if PCA based feature selection is not used, or the fitted object.
- StatisticalSel: WORC StatisticalSel Object
Either None if the statistical test feature selection is not used, or the fitted object.
- ReliefSel: WORC ReliefSel Object
Either None if the RELIEF feature selection is not used, or the fitted object.
- Sampler: WORC ObjectSampler Object
Either None if no resampling is used, or an ObjectSampler object
metrics
Module¶
- WORC.classification.metrics.ICC(M, ICCtype='inter')[source]¶
- Input:
M is matrix of observations. Rows: patients, columns: observers. type: ICC type, currently “inter” or “intra”.
- WORC.classification.metrics.ICC_anova(Y, ICCtype='inter', more=False)[source]¶
Adopted from Nipype with a slight alteration to distinguish inter and intra. the data Y are entered as a ‘table’ ie subjects are in rows and repeated measures in columns One Sample Repeated measure ANOVA Y = XB + E with X = [FaTor / Subjects]
- WORC.classification.metrics.check_multimetric_scoring(estimator, scoring=None)[source]¶
Wrapper around sklearn function to enable more scoring options.
Check the scoring parameter in cases when multiple metrics are allowed
- estimatorsklearn estimator instance
The estimator for which the scoring will be applied.
- scoringstring, callable, list/tuple, dict or None, default: None
A single string (see scoring_parameter) or a callable (see scoring) to evaluate the predictions on the test set. For evaluating multiple metrics, either give a list of (unique) strings or a dict with names as keys and callables as values. NOTE that when using custom scorers, each scorer should return a single value. Metric functions returning a list/array of values can be wrapped into multiple scorers that return one value each. See multimetric_grid_search for an example. If None the estimator’s score method is used. The return value in that case will be
{'score': <default_scorer>}
. If the estimator’s score method is not available, aTypeError
is raised.
- scorers_dictdict
A dict mapping each scorer name to its validated scorer.
- is_multimetricbool
True if scorer is a list/tuple or dict of callables False if scorer is None/str/callable
- WORC.classification.metrics.check_scoring(estimator, scoring=None, allow_none=False)[source]¶
Surrogate for sklearn’s check_scoring to enable use of some other scoring metrics.
- WORC.classification.metrics.f1_weighted_predictproba(y_truth, y_score)[source]¶
Calculate f1-score, but based on predict_proba instead of predict.
Probabilities are thresholded at 0.5.
- WORC.classification.metrics.performance_multilabel(y_truth, y_prediction, y_score=None, beta=1)[source]¶
Multiclass performance metrics.
y_truth and y_prediction should both be lists with the multiclass label of each object, e.g.
y_truth = [0, 0, 0, 0, 0, 0, 2, 2, 1, 1, 2] ### Groundtruth y_prediction = [0, 0, 0, 0, 0, 0, 1, 2, 1, 2, 2] ### Predicted labels y_score = [[0.3, 0.3, 0.4], [0.2, 0.6, 0.2], … ] # Normalized score per patient for all labels (three in this example)
Calculation of accuracy accorading to formula suggested in CAD Dementia Grand Challege http://caddementia.grand-challenge.org and the TADPOLE challenge https://tadpole.grand-challenge.org/Performance_Metrics/ Calculation of Multi Class AUC according to classpy: https://bitbucket.org/bigr_erasmusmc/classpy/src/master/classpy/multi_class_auc.py
parameter_optimization
Module¶
- WORC.classification.parameter_optimization.random_search_parameters(features, labels, N_iter, test_size, param_grid, scoring_method, n_splits=5, n_jobspercore=200, use_fastr=False, n_cores=1, fastr_plugin=None, memory='2G', maxlen=100, ranking_score='test_score', random_seed=None, refit_workflows=False)[source]¶
Train a classifier and simultaneously optimizes hyperparameters using a randomized search.
- Arguments:
features: numpy array containing the training features. labels: list containing the object labels to be trained on. N_iter: integer listing the number of iterations to be used in the
hyperparameter optimization.
- test_size: float listing the test size percentage used in the cross
validation.
classifier: sklearn classifier to be tested param_grid: dictionary containing all possible hyperparameters and their
values or distrubitions.
- scoring_method: string defining scoring method used in optimization,
e.g. f1_weighted for a SVM.
- n_jobsperscore: integer listing the number of jobs that are ran on a
single core when using the fastr randomized search.
- use_fastr: Boolean determining of either fastr or joblib should be used
for the opimization.
- fastr_plugin: determines which plugin is used for fastr executions.
When None, uses the default plugin from the fastr config.
- Returns:
random_search: sklearn randomsearch object containing the results.
regressors
Module¶
trainclassifier
Module¶
- WORC.classification.trainclassifier.add_parameters_to_grid(param_grid, config)[source]¶
Add non-classifier parameters from config to param grid.
- WORC.classification.trainclassifier.trainclassifier(feat_train, patientinfo_train, config, output_hdf, feat_test=None, patientinfo_test=None, fixedsplits=None, verbose=True)[source]¶
Train a classifier using machine learning from features.
By default, if no split in training and test is supplied, a cross validation will be performed.
- feat_train: string, mandatory
contains the paths to all .hdf5 feature files used. modalityname1=file1,file2,file3,… modalityname2=file1,… Thus, modalities names are always between a space and a equal sign, files are split by commas. We assume that the lists of files for each modality has the same length. Files on the same position on each list should belong to the same patient.
- patientinfo: string, mandatory
Contains the path referring to a .txt file containing the patient label(s) and value(s) to be used for learning. See the Github Wiki for the format.
- config: string, mandatory
path referring to a .ini file containing the parameters used for feature extraction. See the Github Wiki for the possible fields and their description.
- output_hdf: string, mandatory
path refering to a .hdf5 file to which the final classifier and it’s properties will be written to.
- feat_test: string, optional
When this argument is supplied, the machine learning will not be trained using a cross validation, but rather using a fixed training and text split. This field should contain paths of the test set feature files, similar to the feat_train argument.
- patientinfo_test: string, optional
When feat_test is supplied, you can supply optionally a patient label file through which the performance will be evaluated.
- fixedsplits: string, optional
By default, random split cross validation is used to train and evaluate the machine learning methods. Optionally, you can provide a .xlsx file containing fixed splits to be used. See the Github Wiki for the format.
- verbose: boolean, default True
print final feature values and labels to command line or not.