![](/img/trans.png)
[英]Keras try save and load model error You are trying to load a weight file containing 16 layers into a model with 0 layers
[英]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 上創建了一個問題:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.