You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何加载Keras保存的.h5权重文件?解决TypeError参数缺失问题

解决Keras加载权重时的TypeError问题

错误原因

你直接调用了Model类的load_weights()方法,但这个方法是模型实例的方法,必须先创建和训练阶段结构完全一致的模型对象,再通过对象调用该方法,而非用类本身调用。

正确操作步骤

  1. 重建与训练时完全一致的模型结构
    比如你训练时定义的模型结构如下(示例):

    from tensorflow.keras import layers, Model
    
    def build_classification_model():
        inputs = layers.Input(shape=(224, 224, 3))  # 和训练时的输入形状一致
        x = layers.Conv2D(32, (3, 3), activation='relu')(inputs)
        x = layers.MaxPooling2D(pool_size=(2, 2))(x)
        x = layers.Flatten()(x)
        x = layers.Dense(64, activation='relu')(x)
        outputs = layers.Dense(10, activation='softmax')(x)  # 分类数和训练时一致
        return Model(inputs=inputs, outputs=outputs)
    

    预测阶段先创建模型实例:

    model = build_classification_model()
    
  2. 通过模型实例加载权重
    用创建好的模型对象调用load_weights(),传入权重文件路径:

    model.load_weights('file_name.h5')
    
  3. 执行单张图像预测
    对单张图像做预处理(和训练时的预处理逻辑一致,比如归一化、resize等)后,调用模型的predict()方法即可:

    # 示例:预处理单张图像
    import numpy as np
    from PIL import Image
    
    img = Image.open('test_image.jpg').resize((224, 224))
    img_array = np.array(img) / 255.0  # 和训练时的归一化一致
    img_array = np.expand_dims(img_array, axis=0)  # 增加batch维度
    
    # 预测
    predictions = model.predict(img_array)
    

关键注意事项

  • 模型结构必须和训练阶段完全匹配,包括输入形状、每层的参数(卷积核数量、全连接层神经元数等),否则权重无法正确加载
  • 若训练时使用了自定义层,需确保预测代码中定义了相同的自定义层,或在加载时通过custom_objects参数指定

Keras官方核心说明(翻译)

load_weights()是Keras模型实例的方法,而非模型类的方法。它用于将已保存的权重加载到结构完全匹配的模型实例中。保存权重使用model.save_weights(filepath),加载时需先构建相同结构的模型,再调用实例的load_weights(filepath)方法。

内容的提问来源于stack exchange,提问作者Stop War

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 23:52:34