更改文件名后张量流模型未加载

问题描述 投票:0回答:1

当我更改文件名时,出现这个奇怪的错误,模型无法正确加载。 训练模型时的文件名是 044.weights.h5,当我使用

加载该模型时
weak_learner = weighted_unet_model()
weak_learner.load_weights(weight_path)

效果很好。但是,当复制模型并使用新名称粘贴时,尽管除了指向新位置的文件路径之外一切都相同,但它不起作用。

md值也相同

% md5 ~/Downloads/044.weights.h5

MD5 (~/Downloads/044.weights.h5) = 01be4b0bcb4f08ab471dbfcfd6edc842
% md5 ~/Desktop/model_checkpoints_hexa.h5 
MD5 (~/Desktop/model_checkpoints_hexa.h5) = 01be4b0bcb4f08ab471dbfcfd6edc842

一个可能的原因是模型是在 ubuntu 系统上训练的,而我使用的是 macOS 张量流版本。但这应该意味着如果名称没有更改,加载模型时会发生错误,但这里不是这种情况

我的 mac 中的tensorflow版本是 张量流2.16.1 张量流-MacOS 2.16.1

执行代码时出现的错误是:

ValueError: Layer count mismatch when loading weights from file. Model expected 37 layers, found 0 saved layers.

tensorflow keras
1个回答
0
投票

通过在新路径中加载和保存模型并使用该路径解决了这个问题

from tensorflow.keras.models import load_model
from models.model_arch import weighted_unet_model

def save_model_with_new_weights(original_weight_path, new_model_path):
    # Initialize the model
    weak_learner = weighted_unet_model()
    
    # Load the weights from the original path
    weak_learner.load_weights(original_weight_path)
    
    # Save the model with weights to the new path
    weak_learner.save(new_model_path, save_format='h5')
    print(f"Model saved with weights at {new_model_path}")

# Example usage
original_weight_path = '~/Downloads/044.weights.h5'
new_model_path = '~/Desktop/model_checkpoints_hexa.h5'
save_model_with_new_weights(original_weight_path, new_model_path)
© www.soinside.com 2019 - 2024. All rights reserved.