I am trying to optimze hyperparamter for 1D CNN model using keras-tuner. Everything looks perfect while trying to get the best parameter. But when I try to print tuner.get_best_models()[0].summary(), it gives me the following error:
raise ValueError("Shapes %s and %s are incompatible" % (self, other)) ValueError: Shapes (78400, 10) and (235680, 10) are incompatible
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()
The input shape, training data shape is below:
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() supposed to print the following model summary:
How can I solve this error? If anyone helps me to solve this problem, it is appreciated.