QT5封装keras tensorflow(三,封装训练好的网络)

5 篇文章 0 订阅
4 篇文章 0 订阅

此处坑较多

发布exe需要pyinstaller 

1首先安装pip3 install pyinstaller

将安装后的script路径写入环境变量PATH,否则命令提示行不识别

2.pyinstaller打包命令pyinstaller -F main.py(时间较久)

由于tensorflow 与keras调用,会出现各种错误。

由于打包过程中或者打包后运行exe会出现ModuleNotFoundError: No module named *错误

使用hook,建立文件件hooks,并在其中配置hook-tensorflow.py

使用pyinstaller -F --additional-hooks-dir=hooks main.py(具体参考pyinstaller 打包 keras tensorflow pyqt 的 打包步骤(踩坑日记 )_“神”地摊小哥的博客-CSDN博客)

但是在运行exe时不断出现错误需要配置*.spec,打包文件同名的spec文件,(例如我找不到keras.engine.base_layer_v1,我就在*.spec中的hiddenimports加入keras.engine.base_layer_v1.)却啥补啥。

然后pyinstaller -F  main.spec 打包

网上说pyh5和tensorflow安装顺序问题,我试了没啥用(玄虚调试)。打包起来有1.5G,稍微有点大,后续挖个坑,网络训练好后,其实读入网络结构和权重很轻量级。后续写一个读入网络权重函数,摆脱tensorflow(太大了)

后文贴出我的配置文件

我将自己配置的hook-tensorflow.py贴出

from PyInstaller.utils.hooks import collect_data_files, collect_submodules

#下面用于将以下模块下所有的子模块全部加入
hiddenimports = collect_submodules('tensorflow_core.core.framework')
hiddenimports += collect_submodules('tensorflow_core.core')
hiddenimports += collect_submodules('tensorflow_core')

hiddenimports += collect_submodules('tensorflow.compiler.tf2tensorrt')
hiddenimports += collect_submodules('tensorflow.python.keras.engine.base_layer_v1')
hiddenimports += collect_submodules('tensorflow_core.lite.experimental.microfrontend.python.ops')
hiddenimports=['pkg_resources.py2_warn',
			   'tensorflow',
			   'tensorflow_core.python',
			   'tensorflow_core.python.platform',
			   'tensorflow_core.python.platform.tf_logging',
			   'tensorflow_core.python.platform.self_check',
             	'tensorflow_core.python.platform.build_info',
			   'tensorflow_core.python.pywrap_tensorflow',
             	'tensorflow_core.python.pywrap_tensorflow_internal',
			   'tensorflow_core.python.util',
			   'tensorflow_core.python.util.deprecation',
			   'tensorflow_core.python.util.tf_export',
			   'tensorflow_core.python.util.tf_decorator',
			   'tensorflow_core.python.util.tf_stack',
			   'tensorflow_core.python.util.tf_inspect',
			   'tensorflow_core.python.util.*',
			   'tensorflow_core.python.util.decorator_utils',
			   'tensorflow_core.python.util.ANY.*',
			   'tensorflow_core.python.util.is_in_graph_mode',
			   'tensorflow_core.python.util.tf_contextlib',
			   'tensorflow_core.core.*',
			   'tensorflow_core.core.framework.*',
			   "cython",
			   "sklearn",
			   "sklearn.ensemble",
			   "sklearn.neighbors.typedefs",
			   "sklearn.neighbors.quad_tree",
			   "sklearn.tree._utils",
			   "sklearn.utils._cython_blas"
			   ]

特别是出现如下错误

我的是main.spec

# -*- mode: python ; coding: utf-8 -*-
import os
import importlib

block_cipher = None


a = Analysis(['main.py'],
             pathex=['E:\\weather2'],
             binaries=[],
			 datas=[(os.path.join(os.path.dirname(importlib.import_module('tensorflow').__file__),
			 "lite/experimental/microfrontend/python/ops/_audio_microfrontend_op.so"),
			 "tensorflow/lite/experimental/microfrontend/python/ops/")],
			 hiddenimports=['pkg_resources.py2_warn',
			 'tensorflow',
			 'tensorflow_core.python',
			 'tensorflow_core.python.platform',
			 'tensorflow_core.python.platform.tf_logging',
			 'tensorflow_core.python.platform.self_check',
             'tensorflow_core.python.platform.build_info',
			 'tensorflow_core.python.pywrap_tensorflow',
             'tensorflow_core.python.pywrap_tensorflow_internal',
			 'tensorflow_core.python.util',
			 'tensorflow_core.python.util.deprecation',
			 'tensorflow_core.python.util.tf_export',
			 'tensorflow_core.python.util.tf_decorator',
			 'tensorflow_core.python.util.tf_stack',
			 'tensorflow_core.python.util.tf_inspect',
			 'tensorflow_core.python.util.*',
			 'tensorflow_core.python.util.decorator_utils',
			 'tensorflow_core.python.util.ANY.*',
			 'tensorflow_core.python.util.is_in_graph_mode',
			 'tensorflow_core.python.util.tf_contextlib',
			 'tensorflow_core.core.*',
			 'tensorflow_core.core.framework.*',
			 "cython",
			 "sklearn",
			 "sklearn.ensemble",
			 "sklearn.neighbors.typedefs",
			 "sklearn.neighbors.quad_tree",
			 "sklearn.tree._utils",
			 "sklearn.utils._cython_blas",
			 "keras.engine.base_layer_v1"],
             hookspath=[],
             hooksconfig={},
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher,
             noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)

exe = EXE(pyz,
          a.scripts, 
          [],
          exclude_binaries=True,
          name='main',
          debug=False,
          bootloader_ignore_signals=False,
          strip=False,
          upx=True,
          console=True,
          disable_windowed_traceback=False,
          target_arch=None,
          codesign_identity=None,
          entitlements_file=None )
coll = COLLECT(exe,
               a.binaries,
               a.zipfiles,
               a.datas, 
               strip=False,
               upx=True,
               upx_exclude=[],
               name='main')

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python中的Keras是一个高级神经网络API,可以在多个深度学习框架上运行。将神经网络以类的形式封装可以使代码更易于管理和重用,下面是一个简单的例子: ```python from keras.models import Sequential from keras.layers import Dense class NeuralNetwork: def __init__(self, input_dim, hidden_dim, output_dim): self.model = Sequential() self.model.add(Dense(hidden_dim, input_dim=input_dim, activation='relu')) self.model.add(Dense(output_dim, activation='softmax')) self.model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) def train(self, X_train, y_train, epochs, batch_size): self.model.fit(X_train, y_train, epochs=epochs, batch_size=batch_size) def predict(self, X_test): return self.model.predict(X_test) # 使用封装好的神经网络类 input_dim = 100 hidden_dim = 50 output_dim = 10 nn = NeuralNetwork(input_dim, hidden_dim, output_dim) X_train = ... y_train = ... nn.train(X_train, y_train, epochs=10, batch_size=32) X_test = ... predictions = nn.predict(X_test) ``` 在上面的例子中,我们首先导入了Keras的Sequential模型和Dense层。然后创建了一个名为NeuralNetwork的类,它的初始化方法中定义了神经网络的结构,并使用compile方法编译模型。训练和预测方法分别用于训练模型和进行预测。最后,我们实例化了这个类,并使用封装好的方法进行训练和预测。这样可以让我们更方便地管理和重用神经网络模型,提高代码的可维护性和可重用性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值