模型转化之----H5转化tflite

H5转化tflite

 

 

注意事项:

1.H5文件必须为整个模型(包含权重,模型结构,配置信息),若是权值h5文件,会加载不出模型

模型训练时,ModelCheckpoint设置参数save_weights_only=False;

  • save_weights_only : 如果为 True,则仅保存模型的权重 ( model.save_weights(filepath)),否则保存完整模型 ( model.save(filepath))

 

参考链接:https://blog.csdn.net/leviopku/article/details/86612293

https://blog.csdn.net/weixin_41770169/article/details/85697281

http://www.cppcns.com/jiaoben/python/314093.html

https://blog.csdn.net/u011529752/article/details/113921568?spm=1001.2014.3001.5501

  

转换步骤:

  

 

报错1:ValueError: Unknown activation function:relu6

原因:新版本的keras把relu6改掉了,找不到该方法

解决方法:

自己定义一个relu6;

  

 

报错2:TypeError: Unexpected keyword argument passed to optimizer: learning_rate

原因:由于在新版本的keras中(指大于等于2.3.0版本),将原来的 lr 这一参数重命名为 leraning_rate,因此将 leraning_rate 重新改为 lr 即可解决报错问题

解决方法:

在模型训练时需根据keras版本定义学习率:

  

解决方法2:

若上述方法不能解决,则升级tensorflow版本至2.0;

并修改使用tf1.0版本的API:

converter = tf.compat.v1.lite.TFLiteConverter.from_keras_model_file(model_file=filepath);

  

H5模型可视化:

 

 

 

报错1:ValueError: Unknown activation function:relu6

原因:新版本的keras把relu6改掉了,找不到方法

解决方法:

重新定义relu6,修改如下:

  

 

报错2:TypeError: Unexpected keyword argument passed to optimizer: learning_rate

类型错误:意外的关键字参数传递给优化器:learning_rate

原因:

Keras版本不匹配,学习率命名 keras2.2.4使用lr,keras2.3.1使用learning_rate

解决方法:

升级keras:pip install --upgrade keras==2.3.1

 

报错3:OSError: `pydot` failed to call GraphViz.Please install GraphViz (https://www.graphviz.org/) and ensure that its executables are in the $PATH.

原因:

解决方法:(仍待解决)

 pip install pydot

pip install pydotplus

brew install graphviz

  

Ps:

关于Adam:

 

  

 

 

Keras保存模型:

参考链接:https://blog.csdn.net/leviopku/article/details/86612293

1.保存整个模型:model.save(filepath)将Keras模型和权重保存在一个HDF5文件中,该文件将包含:

  • 模型的结构
  • 模型的权重
  • 训练配置(损失函数,优化器,准确率等)
  • 优化器的状态,以便于从上次训练中断的地方

再一次使用时可以model.load_model(filepath)载入模型;

 

2.保存模型结构:model.to_jason()将模型序列化保存为json文件,里面记录了网络的整体结构, 各个层的参数设置等信息. 将json字符串保存到文件.

 

 

 

3.保存模型权重:经过调参网络的输出精度比较满意后,可以将训练好的网络权重参数保存下来,可通过下面的代码利用HDF5进行保存:

model.save_weights(‘model_weights.h5’)

使用时加载模型: 

model.load_weights(‘model_weights.h5’)

 

如果需要加载权重到不同的网络结构(有些层一样)中,例如fine-tune或transfer-learning,可以通过层名字来加载模型: 

model.load_weights('my_model_weights.h5', by_name=True)

因此建模时最好给每个层定义名字。

 

 

原文地址:https://www.cnblogs.com/xiaowa/p/15397774.html