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

2024-06-24 12:04:42 发布

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

我是深入学习的新手,尝试使用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'))

有人知道怎么解决这个问题吗?提前谢谢


Tags: fromimportselfaddinputmodelvaluelayers