Kerastuner ValueError:形状(320,)和(1,)不兼容

时间:2020-06-30 03:33:40

标签: python tensorflow machine-learning keras deep-learning

我是深度学习的新手,并尝试使用kerastuner调整超参数。这是我的代码:

from tensorflow import keras
from tensorflow.keras import layers
from kerastuner.tuners import RandomSearch

from kerastuner import HyperModel


class MyHyperModel(HyperModel):

    def __init__(self, input_shape):
        self.input_shape = input_shape

    def build(self, hp):
        model = keras.Sequential()
        model.add(layers.Dense(units=hp.Int('units',
                                        min_value=10,
                                        max_value=120,
                                        step=10),
                           activation='relu',
                           input_shape=self.input_shape))
     
     
        model.add(layers.Dense(units=hp.Int('units',min_value=10,max_value=20,step=2),
                            activation='relu'))
        model.add(layers.Dense(1, activation='linear'))
        model.compile(
            optimizer=keras.optimizers.Adam(
            hp.Choice('learning_rate',
                      values=[1e-2, 1e-3, 1e-4])),
        loss='mse',
        metrics=['mse'])
        return model

input_shape = (X_train.shape[1],)
hypermodel = MyHyperModel(input_shape)

tuner = RandomSearch(
    hypermodel,
    objective='mse',
    max_trials=10,
    )

tuner.search(X_train, y_train,
         epochs=50,
         validation_data=(X_test, y_test),verbose=0)

当我尝试使用检索最佳模型时

tuner.get_best_models(num_models=1)[0]

我遇到以下错误

ValueError: Shapes (320,) and (1,) are incompatible

删除该隐藏层时没有此错误

model.add(layers.Dense(units=hp.Int('units',min_value=10,max_value=20,step=2),
                            activation='relu'))

有人知道如何解决此问题吗?预先感谢。

0 个答案:

没有答案