簡體   English   中英

Tensorflow 2 -Keras SAVE/LOAD 模型錯誤(DenseFeatures 和 DistributionLambda 層)

[英]Tensorflow 2 -Keras SAVE/LOAD model error (DenseFeatures and DistributionLambda layers)

我有一個 Tensorflow 2.x 模型,它使用 TF 預處理層 (tf.keras.layers.DenseFeatures) 和來自 TF 概率 (DistributionLambda) 的分布層:

def regression_deep1_proba2(preprocessing_layer, feature_layer_inputs, model_name='test_model'):


    model = tf.keras.Sequential([
        preprocessing_layer,
        tf.keras.layers.Dense(100, activation='relu', name='hidden_1'),
        tf.keras.layers.Dense(50, activation='relu', name='hidden_2'),
        tf.keras.layers.Dense(1 + 1, name='output'),
        tfp.layers.DistributionLambda(
            lambda t: tfd.LogNormal(loc=t[..., :1], scale=tf.math.softplus(0.05 * t[..., 1:]))
        ),
    ])

    # ____________________ COMPILE WITH  ____________________________________________
    optimizer = tf.keras.optimizers.Adam()
    negloglik = lambda y, p_y: -p_y.log_prob(y)

    metrics = [
        tf.keras.metrics.MeanAbsolutePercentageError()
        ]

    model.compile(
        loss=negloglik,
        optimizer=optimizer,
        metrics=metrics
    )

    # ____________________ CALLBACKS DEFINITION ___________________________________________
    tbCallBack = tf.keras.callbacks.TensorBoard(
        log_dir=f'./logs_regression/{model_name}',
        update_freq='batch',
        histogram_freq=1,
        embeddings_freq=1,
        write_graph=True,
        write_images=True
    )

    # Create a callback that saves the model's weights every 5 epochs
    cp_callback = tf.keras.callbacks.ModelCheckpoint(
        filepath=f'./weights.{model_name}.hdf5',
        verbose=1,
        save_weights_only=True,
        save_best_onlt=True,
        monitor='MeanSquaredError'
    )
    early_stop = tf.keras.callbacks.EarlyStopping(
        monitor='MeanSquaredError',
        patience=2
    )
    callbacks_list = [tbCallBack, cp_callback, early_stop]

    return model, callbacks_list

對於這個模型的回歸問題,我可以得到一些不錯的結果,但是當我保存它以供進一步使用時,我無法再加載它(我已經嘗試了所有在線教程和解決方案,但沒有任何效果)!!

根據我如何保存 tahat 模型,我會收到不同類型的錯誤,但總的來說,我有:

使用時:

tf.keras.models.save_model(model, 'model_name.h5')

new_model = tf.keras.models.load_model('model_name.h5')

我得到:

ValueError: ('We expected a dictionary here. Instead we got: ', <tf.Tensor 'Placeholder:0' shape=(None,) dtype=float32>)

我不知道我做錯了什么 - 任何幫助將不勝感激?

對於 Tensorflow 概率模型,目前僅加載權重有效。 回調也只是保存權重。 因此加載模型首先定義模型架構,然后加載權重。

  model = tf.keras.Sequential([
        preprocessing_layer,
        tf.keras.layers.Dense(100, activation='relu', name='hidden_1'),
        tf.keras.layers.Dense(50, activation='relu', name='hidden_2'),
        tf.keras.layers.Dense(1 + 1, name='output'),
        tfp.layers.DistributionLambda(
            lambda t: tfd.LogNormal(loc=t[..., :1], scale=tf.math.softplus(0.05 * t[..., 1:]))
        ),
    ])

model.load_weights(model_path)
#Predict using Model (Currently model.predict() will not work given distribution Lamba output layer)
model(new_data)

不記得我在哪里偶然發現的,但在我的案例中,解決方案是在模型名稱中保存沒有“.h5”擴展名的模型

tf.keras.models.save_model(model, "model_name")
new_model = tf.keras.models.load_model("model_name")

我在 Tensorflow 概率問題 github 上創建了一個問題:

https://github.com/tensorflow/probability/issues/755

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM