简单来说,交叉验证和网格搜索有什么区别?网格搜索如何工作?我应该首先进行交叉验证然后进行网格搜索吗?
使用确定最佳参数后pipeline和GridSearchCV,我怎么pickle/ joblib后来这个过程中重新使用?当它是单个分类器时,我看到如何做到这一点......
from sklearn.externals import joblib
joblib.dump(clf, 'filename.pkl')
Run Code Online (Sandbox Code Playgroud)
但是,如何pipeline在执行和完成后用最佳参数保存整体gridsearch?
我试过了:
joblib.dump(grid, 'output.pkl') - 但是转储了每次网格搜索尝试(许多文件)joblib.dump(pipeline, 'output.pkl') - 但我不认为它包含最好的参数X_train = df['Keyword']
y_train = df['Ad Group']
pipeline = Pipeline([
('tfidf', TfidfVectorizer()),
('sgd', SGDClassifier())
])
parameters = {'tfidf__ngram_range': [(1, 1), (1, 2)],
'tfidf__use_idf': (True, False),
'tfidf__max_df': [0.25, 0.5, 0.75, 1.0],
'tfidf__max_features': [10, 50, 100, 250, 500, 1000, None],
'tfidf__stop_words': ('english', None),
'tfidf__smooth_idf': (True, False),
'tfidf__norm': ('l1', 'l2', None),
}
grid = …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用DecisionTreeClassifier("DTC")作为base_estimator来调整AdaBoost分类器("ABT").我想调都 ABT同时DTC参数,但我不知道如何做到这一点-管道不应该工作,因为我不是"管" DTC的输出ABT.我们的想法是在GridSearchCV估算器中迭代ABT和DTC的超参数.
如何正确指定调整参数?
我尝试了以下操作,在下面生成了一个错误.
[IN]
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import AdaBoostClassifier
from sklearn.grid_search import GridSearchCV
param_grid = {dtc__criterion : ["gini", "entropy"],
dtc__splitter : ["best", "random"],
abc__n_estimators: [none, 1, 2]
}
DTC = DecisionTreeClassifier(random_state = 11, max_features = "auto", class_weight = "auto",max_depth = None)
ABC = AdaBoostClassifier(base_estimator = DTC)
# run grid search
grid_search_ABC = GridSearchCV(ABC, param_grid=param_grid, scoring = 'roc_auc')
[OUT]
ValueError: Invalid parameter dtc for estimator AdaBoostClassifier(algorithm='SAMME.R',
base_estimator=DecisionTreeClassifier(class_weight='auto', criterion='gini', max_depth=None,
max_features='auto', max_leaf_nodes=None, min_samples_leaf=1,
min_samples_split=2, min_weight_fraction_leaf=0.0,
random_state=11, …Run Code Online (Sandbox Code Playgroud) 我正在使用Python 2.7和sklearn 0.16 从O'Reilly的书" 使用Python 进行机器学习简介 "中实现一个示例.
我正在使用的代码:
pipe = make_pipeline(TfidfVectorizer(), LogisticRegression())
param_grid = {"logisticregression_C": [0.001, 0.01, 0.1, 1, 10, 100], "tfidfvectorizer_ngram_range": [(1,1), (1,2), (1,3)]}
grid = GridSearchCV(pipe, param_grid, cv=5)
grid.fit(X_train, y_train)
print("Best cross-validation score: {:.2f}".format(grid.best_score_))
Run Code Online (Sandbox Code Playgroud)
返回的错误归结为:
ValueError: Invalid parameter logisticregression_C for estimator Pipeline
Run Code Online (Sandbox Code Playgroud)
这是与从v.0.16使用Make_pipeline相关的错误吗?导致此错误的原因是什么?
我正在寻找一种从sklearn中的GridSearchCV图形grid_scores_的方法.在这个例子中,我试图网格搜索SVR算法的最佳gamma和C参数.我的代码如下:
C_range = 10.0 ** np.arange(-4, 4)
gamma_range = 10.0 ** np.arange(-4, 4)
param_grid = dict(gamma=gamma_range.tolist(), C=C_range.tolist())
grid = GridSearchCV(SVR(kernel='rbf', gamma=0.1),param_grid, cv=5)
grid.fit(X_train,y_train)
print(grid.grid_scores_)
Run Code Online (Sandbox Code Playgroud)
运行代码并打印网格分数后,我得到以下结果:
[mean: -3.28593, std: 1.69134, params: {'gamma': 0.0001, 'C': 0.0001}, mean: -3.29370, std: 1.69346, params: {'gamma': 0.001, 'C': 0.0001}, mean: -3.28933, std: 1.69104, params: {'gamma': 0.01, 'C': 0.0001}, mean: -3.28925, std: 1.69106, params: {'gamma': 0.1, 'C': 0.0001}, mean: -3.28925, std: 1.69106, params: {'gamma': 1.0, 'C': 0.0001}, mean: -3.28925, std: 1.69106, params: {'gamma': 10.0, 'C': 0.0001},etc]
Run Code Online (Sandbox Code Playgroud)
我想根据gamma和C参数可视化所有分数(平均值).我想要获得的图表应如下所示: …
我正在使用scickit-learn来调整模型超参数.我正在使用管道将预处理链接到估算器.我的问题的简单版本看起来像这样:
import numpy as np
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
grid = GridSearchCV(make_pipeline(StandardScaler(), LogisticRegression()),
param_grid={'logisticregression__C': [0.1, 10.]},
cv=2,
refit=False)
_ = grid.fit(X=np.random.rand(10, 3),
y=np.random.randint(2, size=(10,)))
Run Code Online (Sandbox Code Playgroud)
在我的情况下,预处理(在玩具示例中将是StandardScale())是耗时的,并且我没有调整它的任何参数.
因此,当我执行该示例时,StandardScaler执行12次.2拟合/预测*2 cv*3参数.但是每次为参数C的不同值执行StandardScaler时,它都返回相同的输出,因此计算它一次就更有效率,然后只运行管道的估算器部分.
我可以在预处理(没有调整超参数)和估算器之间手动拆分管道.但是要将预处理应用于数据,我应该只提供训练集.所以,我必须手动实现拆分,而根本不使用GridSearchCV.
是否有一种简单/标准的方法可以避免在使用GridSearchCV时重复预处理?
在scikit中有一个绝对有用的类GridSearchCV - 学习网格搜索和交叉验证,但我不想做交叉验证.我想在没有交叉验证的情况下进行网格搜索,并使用整个数据进行训练.更具体地说,我需要在网格搜索期间使用"oob得分"评估RandomForestClassifier制作的模型.有简单的方法吗?或者我应该自己上课?
要点是
我希望通过Keras和sklean实现早期停止GridSearchCV.
下面的工作代码示例是使用Keras在Python中如何使用网格搜索超参数进行深度学习模型修改的.可以从这里下载数据集.
修改添加了Keras EarlyStopping回调类以防止过度拟合.为了使其有效,它需要monitor='val_acc'用于监控验证准确性的论据.要val_acc使其可用,KerasClassifier需要validation_split=0.1生成验证准确性,否则EarlyStopping提高RuntimeWarning: Early stopping requires val_acc available!.注意FIXME:代码注释!
请注意,我们可以更换val_acc的val_loss!
问题:如何使用GridSearchCVk-fold算法生成的交叉验证数据集,而不是浪费10%的训练数据用于早期停止验证集?
# Use scikit-learn to grid search the learning rate and momentum
import numpy
from sklearn.model_selection import GridSearchCV
from keras.models import Sequential
from keras.layers import Dense
from keras.wrappers.scikit_learn import KerasClassifier
from keras.optimizers import SGD
# Function to create model, required for KerasClassifier …Run Code Online (Sandbox Code Playgroud) machine-learning scikit-learn cross-validation keras grid-search
我目前正在研究一个问题,该问题比较了同一数据集上三种不同的机器学习算法性能.我将数据集划分为70/30个训练/测试集,然后使用GridSearchCV和网格搜索每个算法的最佳参数X_train, y_train.
第一个问题,我想在训练集上进行网格搜索还是假设在整个数据集上?
第二个问题,我知道GridSearchCV在其实现中使用了K-fold,这是否意味着如果我X_train, y_train在GridSearchCV中比较的所有三种算法都使用了相同的交叉验证?
任何答案都将不胜感激,谢谢.
python machine-learning scikit-learn cross-validation grid-search
我正在运行多个嵌套循环来进行超参数网格搜索.每个嵌套循环遍历超级参数值列表,并且在最内层循环内部,每次使用生成器构建和评估Keras顺序模型.(我没有做任何训练,我只是随机初始化,然后多次评估模型,然后检索平均损失).
我的问题是,在这个过程中,Keras似乎填满了我的GPU内存,所以我最终得到了一个OOM错误.
在评估模型后,是否有人知道如何解决这个问题并释放GPU内存?
在评估之后我根本不再需要模型,我可以在内循环的下一次传递中构建一个新模型之前完全抛弃它.
我正在使用Tensorflow后端.
这是代码,尽管其中大部分与一般问题无关.该模型构建在第四个循环内,
for fsize in fsizes:
Run Code Online (Sandbox Code Playgroud)
我想有关如何构建模型的细节并不重要,但无论如何都是这样的:
model_losses = []
model_names = []
for activation in activations:
for i in range(len(layer_structures)):
for width in layer_widths[i]:
for fsize in fsizes:
model_name = "test_{}_struc-{}_width-{}_fsize-{}".format(activation,i,np.array_str(np.array(width)),fsize)
model_names.append(model_name)
print("Testing new model: ", model_name)
#Structure for this network
structure = layer_structures[i]
row, col, ch = 80, 160, 3 # Input image format
model = Sequential()
model.add(Lambda(lambda x: x/127.5 - 1.,
input_shape=(row, col, ch),
output_shape=(row, col, ch)))
for j in range(len(structure)):
if structure[j] …Run Code Online (Sandbox Code Playgroud) grid-search ×10
python ×8
scikit-learn ×8
keras ×2
pipeline ×2
adaboost ×1
definition ×1
difference ×1
numpy ×1