python预测工程打包遇到的一些问题

1.版本匹配问题

我们的服务器版本是centOS7,所以相对应的一些其他的依赖包版本如下:

版本
python环境 3.6
tensorflow 1.5.0
keras 2.1.6
h5py 2.10.0
sklearn 0.24.2
numpy 1.19.5
flask 2.0.1
pip 21.2.4

版本不匹配会报一些问题,比如:

1)

import tensorflow.python as tf
AttributeError: module 'tensorflow' has no attribute 'python'

另外上面这个问题发生后,我们尽量不要用tensorflow.python点的这种方式来引用包,比如要用backend,就写成如下两行:

from tensorflow import keras
from keras import backend

2)

Traceback (most recent call last):
  File "webapi.py", line 40, in <module>
  File "keras/models.py", line 768, in load_weights
  File "keras/engine/topology.py", line 3339, in load_weights_from_hdf5_group
AttributeError: 'str' object has no attribute 'decode'
[17766] Failed to execute script 'HFwebapi' due to unhandled exception!

这是keras生成的h5模型,在调用load模型时,发生的报错。
solution:
这是h5py模块的版本不匹配,改为2.10.0即可解决(先卸载当前的版本,我的是3.1.0,然后再安装)。

2.打包spec修改

因为我需要把配置文件夹、生成的模型文件、日志文件夹生成到打包后的文件夹中,所以,需要修改spec文件。

a = Analysis(['webapi.py'],
             pathex=['/home/Downloads/20211101'],
             binaries=[('./conf','conf'),('./saved_models','saved_models'),('./Logs','Logs'),
		],
             datas=[],
             hiddenimports=[],
             hookspath=[],
             hooksconfig={},
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher,
             noarchive=False)

如上面所示,要把指定的文件夹生成到指定的目录中去,在binaries中添加即可。
改完spec以后,每次的打包需要记得由

pyinstaller -D webapi.py

改为

pyinstaller -D webapi.spec

3.加载模型遇到的问题

File "/apps/webapi/tensorflow/python/framework/ops.py", line 3402, in _as_graph_element_locked
    
ValueError: Tensor Tensor("dense_9/BiasAdd:0", shape=(?, 1), dtype=float32) is not an element of this graph.
  File "/apps/keras/models.py", line 273, in load_model
    
  File "/apps/keras/engine/topology.py", line 3393, in load_weights_from_hdf5_group
    
  File "/apps/keras/backend/tensorflow_backend.py", line 2377, in batch_set_value
    
  File "/apps/tensorflow/python/client/session.py", line 895, in run
    
  File "/apps/tensorflow/python/client/session.py", line 1073, in _run
    
TypeError: Cannot interpret feed_dict key as Tensor: Tensor Tensor("Placeholder:0", shape=(240, 400), dtype=float32) is not an element of this graph.

参考
https://www.jianshu.com/p/c84ae0527a3f
https://www.cnblogs.com/yanjj/p/8242595.html
这个问题是在调用h5模型时产生的。
solution
在初始化加载模型之后,就随便生成一个向量让 model 执行一次 predict 函数,之后再使用就不会有问题了。
load_model后,加一句:

model.predict(np.zeros((1,50,29)))

如上修改后,再打包运行会发现接口可以成功调用一次,第二次就又失败了。
这个问题,下面的blog描述了解决方法:
https://blog.csdn.net/selfimpro_001/article/details/99693273
session是tensorflow中常见的会话。
clear_session: destroys the current TF graph and creates a new one. Useful to avoid clutter from old models/layers.
TF graph函数,可以通过tensorboard用图形化界面展示出来流程结构,可以整合一段代码为一个整体存在于一个图中。
如果不添加clear_session(),每次加载模型,graph上的node就会越来越多,最终导致时间、内存问题。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>