tensorflow專案打包
- 1.版本匹配問題
- 1)
- 2)
- 2.打包spec修改
- 3.加載模型遇到的問題
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.
參考:
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就會越來越多,最終導致時間、記憶體問題,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/353243.html
標籤:AI
上一篇:RuntimeError: module compiled against API version 0xc but this version of numpy is 0xb
