使用神经网络在多个 class class化问题中进行网格搜索

Grid Search in Multi class classification problems using Neural networks

我正在尝试对神经网络中的多个 class 问题进行网格搜索。 我无法获得最佳参数,内核继续编译。 我的代码有问题吗?请帮忙

import keras

from keras.models import Sequential
from keras.layers import Dense

# defining the baseline model:

def neural(output_dim=10,init_mode='glorot_uniform'):
    model = Sequential()
    model.add(Dense(output_dim=output_dim,
                    input_dim=2,
                    activation='relu',
                    kernel_initializer= init_mode))
    model.add(Dense(output_dim=output_dim,
                    activation='relu',
                    kernel_initializer= init_mode))
    model.add(Dense(output_dim=3,activation='softmax'))

    # Compile model
    model.compile(loss='sparse_categorical_crossentropy', 
                  optimizer='adam', 
                  metrics=['accuracy'])
    return model

from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import KFold
from sklearn.model_selection import GridSearchCV
estimator = KerasClassifier(build_fn=neural, 
                            epochs=5, 
                            batch_size=5, 
                            verbose=0)

# define the grid search parameters
batch_size = [10, 20, 40, 60, 80, 100]
epochs = [10, 50, 100]
init_mode = ['uniform', 'lecun_uniform', 'normal', 'zero', 
             'glorot_normal', 'glorot_uniform', 'he_normal', 'he_uniform']
output_dim = [10, 15, 20, 25, 30,40]

param_grid = dict(batch_size=batch_size, 
                  epochs=epochs,
                  output_dim=output_dim,
                  init_mode=init_mode)

grid = GridSearchCV(estimator=estimator, 
                    scoring= 'accuracy',
                    param_grid=param_grid, 
                    n_jobs=-1,cv=5)

grid_result = grid.fit(X_train, Y_train)

# summarize results

print("Best: %f using %s" % (grid_result.best_score_, 
                             grid_result.best_params_))
means = grid_result.cv_results_['mean_test_score']
stds = grid_result.cv_results_['std_test_score']
params = grid_result.cv_results_['params']
for mean, stdev, param in zip(means, stds, params):
    print("%f (%f) with: %r" % (mean, stdev, param))

您的代码没有错误。

您当前的参数网格有 864 种可能的不同参数组合。

('batch_size' 中的 6 个值 × 'epochs' 中的 3 个值 × 'init_mode' 中的 8 个值 × 'output_dim' 中的 6 个值) = 864

GridSearchCV 将迭代所有这些可能性,并且您的估算器将被克隆多次。由于您设置了 cv=5,因此再次重复 5 次。

因此您的模型将被克隆(根据可能性进行编译和设置参数)总共 864 x 5 = 4320 次。

所以你一直在输出中看到模型被编译了那么多次。

要检查 GridSearchCV 是否正常工作,请使用其 verbose 参数。

grid = GridSearchCV(estimator=estimator, 
                    scoring= 'accuracy',
                    param_grid=param_grid, 
                    n_jobs=1,cv=5, verbose=3)

这将打印当前正在尝试的可能参数、cv 迭代、适应它所花费的时间、当前精度等。