使用RandomizedSearchCV(scikitlearn)>优化隐藏层和神经元的数量,没有不必要的训练?

2024-04-19 06:49:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我想优化隐藏层的数量和每个隐藏层中的单元数量。 为此,我使用了sklearn的RandomizedSearchCV:

    from tensorflow.keras.wrappers.scikit_learn import KerasRegressor
    from sklearn.model_selection import RandomizedSearchCV
    from tensorflow import keras
    models = keras.models
    layers = keras.layers

    def tuneModel(n_layer, n1_units, n2_units):
        model = models.Sequential()

        # input layer + first hidden layer
        model.add(layers.Dense(n1_units, input_dim=100, activation="relu"))       
        
        # second hidden layer
        if n_layer == 2:
            model.add(layers.Dense(n2_units, activation="relu"))   
    
        # output layer
        model.add(layers.Dense(2))                                                  
        
        model.compile(loss="mse", optimizer=opt)
        return model
    
    model = KerasRegressor(build_fn=tuneModel, verbose=0)
    
    param_grid = dict(n_layer=[1,2],
                      n1_units=[16, 32, 64, 128],                  
                      n2_units=[16, 32, 64, 128],
                      batch_size=[64],
                      epochs=[100]
                      )

    grid = RandomizedSearchCV(estimator=model,
                              param_distributions=param_grid, 
                              scoring="neg_mean_squared_error",
                              cv=5,
                              n_iter=8
                              )
    
    grid_result = grid.fit(x,y)

这是一个显示我的问题的强有力的缩编例子。 它运行良好,但会发生不必要的培训。例如,如果n_层=1和n1_单元=16,则有四种组合训练相同的网络:

n_层=1,n1_单元=16,n2_单元=16

n_层=1,n1_单元=16,n2_单元=32

n_层=1,n1_单元=16,n2_单元=64

n_层=1,n1_单元=16,n2_单元=128

因为参数n2_units不用于一层网络

是否有可能以另一种方式构建网络,而这不会发生

我希望我的解释可以理解:)


Tags: fromimportaddlayermodelmodelslayersgrid
1条回答
网友
1楼 · 发布于 2024-04-19 06:49:41

我会将层的大小作为元组传递,而不是单独的参数。例如

def tuneModel(layer_sizes): 
    model = models.Sequential()
    model.add(keras.Input(shape=(100,)))

    for layer_size in layer_sizes:
        model.add(layers.Dense(layer_size, activation="relu"))

    model.add(layers.Dense(2))

    model.compile(loss="mse", optimizer=opt)
    return model

sizes = [16, 32, 64, 128]
shapes = (
    list(itertools.product(sizes, repeat=1))
    + list(itertools.product(sizes, repeat=2))
)

param_grid = dict(
    layer_sizes=shapes,
    batch_size=[64],
    epochs=[100]
)

相关问题 更多 >