【问题标题】:SciKit-learn grid search own scoring object syntaxSciKit-learn 网格搜索自带评分对象语法
【发布时间】:2017-03-27 03:29:57
【问题描述】:

我想在使用 Keras 构建的卷积网络中搜索超参数。为此,我使用了来自 SciKit-learn 的 KerasClassifier 和 GridSearchCV,以符合此处MachineLearningMastery 给出的良好介绍。 通常 SciKit-learn 在 'accuracy' 上进行优化,但是我的网络运行图像分割优化 Jaccard 索引。因此,我需要使用 make_scorer 为网格搜索定义自己的评分对象,如make_scorerdefining your scoring strategy 所述。下面的代码部分显示了我的实现,但在model.compile(optimizer=optimizer, loss=eval_loss, metrics=(['eval_func']) 中出现错误,我不知道在指标中指定什么。默认值为'accuracy',但我假设在我的情况下这将是'eval_func'(在不进行网格搜索时有效)或'score',但在这种情况下这些都不起作用。

什么是正确的语法?

def eval_func(y_true, y_pred):
    '''Evaluation function dice or jaccard, set with global var JACCARD=True'''
    if JACCARD:
        return jaccard_index(y_true, y_pred)
    else:
        return dice_coef(y_true, y_pred)


def get_unet(batch_size=32, decay=0, dropout_rate=0.5, weight_constraint=0):
    '''Create u-net model'''
    dim = 32    

    inputs = Input((3, image_cols, image_rows)) # modified to take 3 color channel input
    conv1 = Convolution2D(dim, 3, 3, activation='relu', border_mode='same', W_constraint=weight_constraint)(inputs)
    conv1 = Convolution2D(dim, 3, 3, activation='relu', border_mode='same', W_constraint=weight_constraint)(conv1)
    pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)
    pool1 = Dropout(dropout_rate)(pool1) # dropout added to all layers

    ... more layers ...

    conv10 = Convolution2D(1, 1, 1, activation='sigmoid')(conv9)

    model = Model(input=inputs, output=conv10)

    optimizer = Adam(lr=LR, decay=decay)   
    model.compile(optimizer=optimizer, loss=eval_loss, metrics=(['eval_func'])

    return model

def run_grid_search():
    '''Optimize model parameters with grid search'''

    ... loading data ...

    model = KerasClassifier(build_fn=get_unet, verbose=1, nb_epoch=NUM_EPOCH, shuffle=True)
    # define grid search parameters
    batch_size = [16, 32, 48]
    decay = [0, 0.002, 0.004]
    param_grid = dict(batch_size=batch_size, decay=decay)

    # create scoring object
    score = make_scorer(eval_func, greater_is_better=True)

    grid = GridSearchCV(estimator=model, param_grid=param_grid, scoring=score, n_jobs=1, verbose=1)
    grid_result = grid.fit(X_aug, Y_aug) 

这是我在使用“eval_func”和“score”时遇到的错误的最后一部分:

文件“C:\程序 Files\Anaconda2\lib\site-packages\keras\metrics.py",第 216 行,在获取 return get_from_module(identifier, globals(), 'metric') File "C:\Program Files\Anaconda2\lib\site-packages\keras\utils\generic_utils.py",行 16、在get_from_module中 str(identifier)) 异常:无效度量:eval_func

【问题讨论】:

    标签: python scikit-learn keras


    【解决方案1】:

    你应该在传递给编译时取消引用它。只有当它们是 Keras API 的一部分时,Keras 才会识别引号中的指标。见Keras.io/metrics

    这就是问题所在:

    model.compile(optimizer=optimizer, loss=eval_loss, metrics=(['eval_func']) 
    

    您应该将其修复为:

    model.compile(optimizer=optimizer, loss=eval_loss, metrics=([eval_func])
    

    希望对你有帮助!

    【讨论】:

    【解决方案2】:

    默认情况下,scikit-learn 在估计器中使用 score 函数,如果它存在的话。所以你可以在KerasClassifier中覆盖the score function

    class MyEstimator(KerasClassifier):
        def __init__(self, **kwargs):
            super(MyEstimator, self).__init__(**kwargs)
    
        def score(self, X, y):
            y_pred = self.predict(X)
            return eval_func(y, y_pred)
    

    【讨论】:

      猜你喜欢
      • 2016-07-18
      • 2016-04-09
      • 2016-08-30
      • 2016-04-04
      • 2014-08-09
      • 2017-12-29
      • 2017-10-26
      • 2015-04-02
      • 2018-09-22
      相关资源
      最近更新 更多