尝试获取调谐器时引发ValueError(“形状%s和%s不兼容”%(自身,其他))错误,get_best_models()[0].summary()使用keras-tuner

relj7zay  于 2022-11-13  发布在  其他
关注(0)|答案(1)|浏览(178)

我正在尝试使用keras-tuner优化1D CNN模型的超参数。在尝试获得最佳参数时,一切看起来都很完美。但当我尝试打印tuner.get_best_models()[0].summary()时,它给我以下错误:
raise ValueError(“图形%s和%s不兼容”%(自身,其他))ValueError:形状(78400,10)和(235680,10)不兼容

def build_model(hp):  # random search passes this hyperparameter() object
    nSNP = X_train.shape[1]
    kernel_size = 3  # stride between convolutions

    model = keras.models.Sequential()

    model.add(Conv1D(hp.Int('input_units',
                            min_value=32,
                            max_value=256,
                            step=32), kernel_size, input_shape=(nSNP, 1)))

    model.add(Activation('relu'))
    model.add(MaxPooling1D(pool_size=2))

    for i in range(hp.Int('n_layers', 1, 4)):  # adding variation of layers.
        model.add(Conv1D(hp.Int(f'conv_{i}_units',
                                min_value=32,
                                max_value=256,
                                step=32), kernel_size))
        model.add(Activation('relu'))

    model.add(Flatten())
    model.add(Dense(10, activation='linear'))
    model.add(Dense(1))
    # model.add(Activation(hp.Choice('Activation', values=['relu', 'sigmoid', 'linear'])))

    # Tune the learning rate for the optimizer
    # Choose an optimal value from 0.01, 0.001, or 0.0001
    hp_learning_rate = hp.Choice('learning_rate', values=[1e-2, 1e-3, 1e-4, 1e-5,
                                                          1e-6, 1e-7])
    # hp_optimizer = hp.Choice('optimizer', values=['SGD', 'Adam'])
    adm = keras.optimizers.Adam(learning_rate=hp_learning_rate)
    model.compile(optimizer=adm, loss='mse')

    return model

tuner = keras_tuner.Hyperband(build_model,
                             objective='val_loss',
                             max_epochs=10,
                             factor=3)
stop_early = tensorflow.keras.callbacks.EarlyStopping(monitor='val_loss', patience=10)
    tuner.search(x=X2_train,
                 y=y_train,
                 verbose=2,     
                 epochs=50,
                 batch_size=64,
                 validation_data=(X2_valid, y_valid),
                 callbacks=[stop_early])
    
    # Get the optimal hyperparameters
    best_hps = tuner.get_best_hyperparameters(num_trials=1)[0]
    
    print(f"""
    The hyper-parameter search is complete.
    The optimal number of units in the first densely-connected
    layer is {best_hps.get('input_units')} and the optimal learning rate for the optimizer
    is {best_hps.get('learning_rate')}.
    """)
    
    print(tuner.get_best_hyperparameters()[0].values)
    tuner.get_best_models()[0].summary()

输入形状,训练数据形状如下图:

X shape (195, 4915)
Y shape (195, 3)
X_train.shape (156, 4915) 
y_train.shape (156,)
X_valid.shape (39, 4915) 
y_valid.shape (39,)

tuner.get_best_models()[0].summary()应该打印以下模型摘要:

我怎样才能解决这个错误呢?如果有人帮助我解决这个问题,我将不胜感激。

50few1ms

50few1ms1#

我不知道你是否已经解决了这个问题,
1.确保您重置Keras调谐器,因为它记住了详细的日志和检查点的每一个试验通过传递下面的参数,当您运行调谐器。

overwrite = True

1.模型需要以下格式的三维输入:[n_samples,variables,features],其中features = 1。您的X_train图形应该看起来像(156,4915,1),而X_test图形应该看起来像(39,4915,1)。若要重新调整数据的形状,请用途:

X_train = np.array(X_train).reshape(X_train.shape[0], X_train.shape[1], 1)
X_test = np.array(X_test).reshape(X_test.shape[0], X_test.shape[1], 1)

希望这对你有帮助。

相关问题