tf2.0 ValueError:You are trying to load a weight file containing 2 layers into a model with 0 layers

    技术2022-07-29  81

    tensorflow2.0版本,通过继承 tf.keras.Model 类自定义网络结构,当加载之前训练过的模型参数时报错 ValueError:You are trying to load a weight file containing 2 layers into a model with 0 layers。

    网上有说改成 model.load_weights('model_name.h5',by_name=True) 试了下还是报错。

    后来在github的一些demo里发现,在加载权重前将模型运行一遍将模型初始化就可以了。

    model = MyModel() # 实例化 model(tf.ones(shape=INPUT_SHAPE)) # 随便用个输入跑一下,初始化模型 model.load_weights('model_name.h5') # 加载权重

    最后吐糟一下 tensorflow2.0 坑有点多

    Processed: 0.009, SQL: 9