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

ValueError: You are trying to load a weight file containing 4 layers into a model with 0 layers.
已经训练好模型,并保存为Simcnn.h5文件,模型重新编译并调用的时候报错。
出错代码:

 def model_pre(self):
        if os.path.exists("ckpt/Simcnn/checkpoint/Simcnn.h5"):
            Simcnn.model.load_weights("ckpt/Simcnn/checkpoint/Simcnn.h5")
            res=Simcnn.model.predict(x=self.x_test)
            print(np.argmax(res,axis=1))

原因:
猜测应该是模型结构没有加载成功。
网上看的大概有两种解决方案:1.keras降级 2.使用json
没有实测,不知道效果怎么样,自己摸索了一下其他的办法
解决方案:

 def model_pre(self):
        if os.path.exists("ckpt/Simcnn/checkpoint/Simcnn.h5"):
        	Simcnn.model.fit(x=self.x_train, y=self.y_train, batch_size=50, epochs=0, verbose=1)
            Simcnn.model.load_weights("ckpt/Simcnn/checkpoint/Simcnn.h5")
            res=Simcnn.model.predict(x=self.x_test)
            print(np.argmax(res,axis=1))

在load_weights之前“预训练”一下,设置epochs=0并不会真正训练。成功运行。
环境:Python3.7,使用tensorflow1.13.1自带的keras,tensorflow.python.keras.__ version__==‘2.2.4-tf’

猜你喜欢

转载自blog.csdn.net/qq_41870658/article/details/108869172