本文整理汇总了Python中sklearn.model_selection.ParameterGrid方法的典型用法代码示例。如果您正苦于以下问题:Python model_selection.ParameterGrid方法的具体用法?Python model_selection.ParameterGrid怎么用?Python model_selection.ParameterGrid使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sklearn.model_selection
的用法示例。
在下文中一共展示了model_selection.ParameterGrid方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_regression
# 需要导入模块: from sklearn import model_selection [as 别名]
# 或者: from sklearn.model_selection import ParameterGrid [as 别名]
def test_regression():
# Check regression for various parameter settings.
rng = check_random_state(0)
X_train, X_test, y_train, y_test = train_test_split(boston.data[:50],
boston.target[:50],
random_state=rng)
grid = ParameterGrid({"max_samples": [0.5, 1.0],
"max_features": [0.5, 1.0],
"bootstrap": [True, False],
"bootstrap_features": [True, False]})
for base_estimator in [None,
DummyRegressor(),
DecisionTreeRegressor(),
KNeighborsRegressor(),
SVR(gamma='scale')]:
for params in grid:
BaggingRegressor(base_estimator=base_estimator,
random_state=rng,
**params).fit(X_train, y_train).predict(X_test)
示例2: get_parameters
# 需要导入模块: from sklearn import model_selection [as 别名]
# 或者: from sklearn.model_selection import ParameterGrid [as 别名]
def get_parameters(sizes, stars, noises, comb_number, repeats, seed):
"""Create a list of dictionaries with all the combinations of the given
parameters.
"""
grid = ParameterGrid({
"size": sizes, "stars": stars, "noise": noises})
grid = list(grid) * comb_number
# set the random state for run in parallel
random = np.random.RandomState(seed)
images_seeds = random.randint(1_000_000, size=len(grid))
for idx, g in enumerate(grid):
g["idx"] = idx
g["seed"] = seed
g["images_seed"] = images_seeds[idx]
g["repeats"] = repeats
return grid
示例3: test_iforest_sparse
# 需要导入模块: from sklearn import model_selection [as 别名]
# 或者: from sklearn.model_selection import ParameterGrid [as 别名]
def test_iforest_sparse():
"""Check IForest for various parameter settings on sparse input."""
rng = check_random_state(0)
X_train, X_test, y_train, y_test = train_test_split(boston.data[:50],
boston.target[:50],
random_state=rng)
grid = ParameterGrid({"max_samples": [0.5, 1.0],
"bootstrap": [True, False]})
for sparse_format in [csc_matrix, csr_matrix]:
X_train_sparse = sparse_format(X_train)
X_test_sparse = sparse_format(X_test)
for params in grid:
# Trained on sparse format
sparse_classifier = IsolationForest(
n_estimators=10, random_state=1, **params).fit(X_train_sparse)
sparse_results = sparse_classifier.predict(X_test_sparse)
# Trained on dense format
dense_classifier = IsolationForest(
n_estimators=10, random_state=1, **params).fit(X_train)
dense_results = dense_classifier.predict(X_test)
assert_array_equal(sparse_results, dense_results)
示例4: test_classification
# 需要导入模块: from sklearn import model_selection [as 别名]
# 或者: from sklearn.model_selection import ParameterGrid [as 别名]
def test_classification():
# Check classification for various parameter settings.
rng = check_random_state(0)
X_train, X_test, y_train, y_test = train_test_split(iris.data,
iris.target,
random_state=rng)
grid = ParameterGrid({"max_samples": [0.5, 1.0],
"max_features": [1, 2, 4],
"bootstrap": [True, False],
"bootstrap_features": [True, False]})
for base_estimator in [None,
DummyClassifier(),
Perceptron(tol=1e-3),
DecisionTreeClassifier(),
KNeighborsClassifier(),
SVC(gamma="scale")]:
for params in grid:
BaggingClassifier(base_estimator=base_estimator,
random_state=rng,
**params).fit(X_train, y_train).predict(X_test)
示例5: fitModels
# 需要导入模块: from sklearn import model_selection [as 别名]
# 或者: from sklearn.model_selection import ParameterGrid [as 别名]
def fitModels(model, paramGrid, X, y, n_jobs=-1, verbose=10):
"""
Parallelizes fitting all models using all combinations of parameters in paramGrid on provided data.
:param model: The instantiated model you wish to pass, e.g. LogisticRegression()
:param paramGrid: The ParameterGrid object created from sklearn.model_selection
:param X: The independent variable data
:param y: The response variable data
:param n_jobs: Number of cores to use in parallelization (defaults to -1: all cores)
:param verbose: The level of verbosity of reporting updates on parallel process
Default is 10 (send an update at the completion of each job)
:return: Returns a list of fitted models
Example usage:
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import ParameterGrid
model = LogisticRegression()
grid = {
'C': [1e-4, 1e-3], # regularization
'penalty': ['l1','l2'], # penalty type
'n_jobs': [-1] # parallelize within each fit over all cores
}
paramGrid = ParameterGrid(grid)
myModels = fitModels(model, paramGrid, X_train, y_train)
"""
return Parallel(n_jobs=n_jobs, verbose=verbose)(delayed(fitOne)(model, X, y, params) for params in paramGrid)
示例6: _model_param_grid
# 需要导入模块: from sklearn import model_selection [as 别名]
# 或者: from sklearn.model_selection import ParameterGrid [as 别名]
def _model_param_grid(params_config):
for name, config in params_config.items():
try:
Model = yamlconf.import_module(config['class'])
except Exception:
logger.warn("Could not load model {0}"
.format(config['class']))
logger.warn("Exception:\n" + traceback.format_exc())
continue
if not hasattr(Model, "train"):
logger.warn("Model {0} does not have a train() method."
.format(config['class']))
continue
param_grid = ParameterGrid(config['params'])
yield name, Model, param_grid
示例7: test_gscv_fit
# 需要导入模块: from sklearn import model_selection [as 别名]
# 或者: from sklearn.model_selection import ParameterGrid [as 别名]
def test_gscv_fit(forecaster, param_dict, cv, scoring):
param_grid = ParameterGrid(param_dict)
y = load_airline()
gscv = ForecastingGridSearchCV(forecaster, param_grid=param_dict, cv=cv,
scoring=scoring)
gscv.fit(y)
# check scores
gscv_scores = gscv.cv_results_[f"mean_test_{scoring.name}"]
expected_scores = compute_expected_gscv_scores(forecaster, cv, param_grid,
y, scoring)
np.testing.assert_array_equal(gscv_scores, expected_scores)
# check best parameters
assert gscv.best_params_ == param_grid[gscv_scores.argmin()]
# check best forecaster is the one with best parameters
assert {key: value for key, value in
gscv.best_forecaster_.get_params().items() if
key in gscv.best_params_.keys()} == gscv.best_params_
示例8: test_apply_backtesting
# 需要导入模块: from sklearn import model_selection [as 别名]
# 或者: from sklearn.model_selection import ParameterGrid [as 别名]
def test_apply_backtesting():
"""Test backtesting function."""
# Input data
bettor = Bettor(classifier=DummyClassifier(), targets=['D', 'H'])
param_grid = {'classifier__strategy': ['uniform', 'stratified']}
risk_factors = [0.0, 0.2, 0.4]
random_state = 0
X = np.random.random((100, 2))
scores = np.repeat([1, 0], 50), np.repeat([0, 1], 50), np.repeat([1, 0], 50), np.repeat([0, 1], 50)
odds = np.repeat([2.0, 2.0], 100).reshape(-1, 2)
cv = TimeSeriesSplit(2, 0.3)
n_runs = 3
n_jobs = -1
# Output
results = apply_backtesting(bettor, param_grid, risk_factors, X, scores, odds, cv, random_state, n_runs, n_jobs)
assert list(results.columns) == ['parameters', 'risk_factor', 'coverage', 'mean_yield', 'std_yield', 'std_mean_yield']
assert len(results) == len(risk_factors) * len(ParameterGrid(param_grid))
示例9: _prepare_components_grid
# 需要导入模块: from sklearn import model_selection [as 别名]
# 或者: from sklearn.model_selection import ParameterGrid [as 别名]
def _prepare_components_grid(self, seasonal_harmonics=None):
"""Provides a grid of all allowed model component combinations.
Parameters
----------
seasonal_harmonics: array-like or None
When provided all component combinations shall contain those harmonics
"""
allowed_combinations = []
use_box_cox = self.use_box_cox
base_combination = {
'use_box_cox': self.__prepare_component_boolean_combinations(use_box_cox),
'box_cox_bounds': [self.box_cox_bounds],
'use_arma_errors': [self.use_arma_errors],
'seasonal_periods': [self.seasonal_periods],
}
if seasonal_harmonics is not None:
base_combination['seasonal_harmonics'] = [seasonal_harmonics]
if self.use_trend is not True: # False or None
allowed_combinations.append({
**base_combination,
**{
'use_trend': [False],
'use_damped_trend': [False], # Damped trend must be False when trend is False
}
})
if self.use_trend is not False: # True or None
allowed_combinations.append({
**base_combination,
**{
'use_trend': [True],
'use_damped_trend': self.__prepare_component_boolean_combinations(self.use_damped_trend),
}
})
return ParameterGrid(allowed_combinations)
示例10: fit
# 需要导入模块: from sklearn import model_selection [as 别名]
# 或者: from sklearn.model_selection import ParameterGrid [as 别名]
def fit(self, X, y=None, groups=None):
"""Run fit with all sets of parameters.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Training vector, where n_samples is the number of samples and
n_features is the number of features.
y : array-like, shape = [n_samples] or [n_samples, n_output], optional
Target relative to X for classification or regression;
None for unsupervised learning.
groups : array-like, with shape (n_samples,), optional
Group labels for the samples used while splitting the dataset into
train/test set.
"""
return self._fit(X, y, groups, ParameterGrid(self.param_grid))
示例11: test_classification
# 需要导入模块: from sklearn import model_selection [as 别名]
# 或者: from sklearn.model_selection import ParameterGrid [as 别名]
def test_classification():
# Check classification for various parameter settings.
rng = check_random_state(0)
X_train, X_test, y_train, y_test = train_test_split(iris.data,
iris.target,
random_state=rng)
grid = ParameterGrid({"max_samples": [0.5, 1.0],
"max_features": [1, 2, 4],
"bootstrap": [True, False],
"bootstrap_features": [True, False]})
for base_estimator in [None,
DummyClassifier(),
Perceptron(tol=1e-3),
DecisionTreeClassifier(),
KNeighborsClassifier(),
SVC()]:
for params in grid:
BaggingClassifier(base_estimator=base_estimator,
random_state=rng,
**params).fit(X_train, y_train).predict(X_test)
示例12: test_regression
# 需要导入模块: from sklearn import model_selection [as 别名]
# 或者: from sklearn.model_selection import ParameterGrid [as 别名]
def test_regression():
# Check regression for various parameter settings.
rng = check_random_state(0)
X_train, X_test, y_train, y_test = train_test_split(boston.data[:50],
boston.target[:50],
random_state=rng)
grid = ParameterGrid({"max_samples": [0.5, 1.0],
"max_features": [0.5, 1.0],
"bootstrap": [True, False],
"bootstrap_features": [True, False]})
for base_estimator in [None,
DummyRegressor(),
DecisionTreeRegressor(),
KNeighborsRegressor(),
SVR()]:
for params in grid:
BaggingRegressor(base_estimator=base_estimator,
random_state=rng,
**params).fit(X_train, y_train).predict(X_test)
示例13: get_parameters
# 需要导入模块: from sklearn import model_selection [as 别名]
# 或者: from sklearn.model_selection import ParameterGrid [as 别名]
def get_parameters(min_size, max_size, step_size, stars,
noise, seed, comb_number, repeats):
"""Create a list of dictionaries with all the combinations of the given
parameters.
"""
sample_size = int((max_size - min_size) / step_size)
sizes = np.linspace(min_size, max_size, sample_size, dtype=int)
grid = ParameterGrid({
"size": sizes, "stars": [stars],
"noise": [noise], "repeats": [repeats]})
grid = list(grid) * comb_number
# set the random state for run in parallel
random = np.random.RandomState(seed)
images_seeds = random.randint(1_000_000, size=len(grid))
for idx, g in enumerate(grid):
g["idx"] = idx
g["seed"] = seed
g["min_size"] = min_size
g["max_size"] = max_size
g["step_size"] = step_size
g["images_seed"] = images_seeds[idx]
return grid
示例14: fit
# 需要导入模块: from sklearn import model_selection [as 别名]
# 或者: from sklearn.model_selection import ParameterGrid [as 别名]
def fit(self, X, y=None):
"""Run fit with all sets of parameters.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Training vector, where n_samples is the number of samples and
n_features is the number of features.
y : array-like, shape = [n_samples] or [n_samples, n_output], optional
Target relative to X for classification or regression;
None for unsupervised learning.
"""
return self._fit(X, y, ParameterGrid(self.param_grid))
示例15: fit
# 需要导入模块: from sklearn import model_selection [as 别名]
# 或者: from sklearn.model_selection import ParameterGrid [as 别名]
def fit(self, frame):
"""Fit the grid search.
Parameters
----------
frame : H2OFrame, shape=(n_samples, n_features)
The training frame on which to fit.
"""
return self._fit(frame, ParameterGrid(self.param_grid))