TensorFlow训练模型时,基本都是在Python环境下完成。生成环境中通常会使用其他语言开发应用程序,来完成对训练好的模型的调用。这时,就需要用到tensorflow的动态库文件。Tensorflow的官方并没有提供编译好的动态库文件,只是给出了如何进行编译的方法指导。实际编译过程中,会遇到很多问题,作者在参考其他编译教程,结合自己的实战经验,总结撰写本教程,希望能为需要的同仁提供些许帮助。
主要参考:
https://www.tensorflow.org/install/source_windows官网配置指南
Installing Bazel on Windows - Bazel main
Windows 下 tensorflow2.3 c++ 编译 - 知乎
1. Windows 编译环境配置
安装以下构建工具以配置 Windows 编译环境。
1.1. 安装 Python 和 TensorFlow 软件包依赖项
1.1.1. 安装Python
安装适用于 Windows 的 Python 3.6.x 64 位版本(以上的版本)。选择 pip 作为可选功能,并将其添加到 %PATH%
环境变量中。
注意:python的安装路径不能有空格,否则在bazel build时会报如下错误:
python安装在没有空格路径下(比如: C:\Python\Python38)并将安装路径配置到系统环境变量path中。
1.1.2. 安装Tensorflow pip软件依赖包
安装 TensorFlow pip 软件包依赖项:
pip3 install six numpy wheel
pip3 install keras_applications==1.0.6 --no-deps
pip3 install keras_preprocessing==1.0.5 --no-deps
上图说明six,numpy,wheel已经安装过了。可通过pip uninstall先卸载已经安装的软件,并按照要求重新安装指定版本软件。
pip3 install
six~=1.15.0 numpy~=1.19.2 wheel~=0.35
pip3 install
keras_applications~=1.0.8 --no-deps
pip3 install
keras_preprocessing~=1.1.2 --no-deps
说明:通过pip3 install keras_applications安装的版本最新只有1.0.8。
这些依赖项就列在 setup.py 文件tensorflow/setup.py at master · tensorflow/tensorflow · GitHub
)的 REQUIRED_PACKAGES 下。
本教程针对TensorFlow2.5版本进行编译,请参考:
tensorflow/setup.py at r2.5 · tensorflow/tensorflow · GitHub
REQUIRED_PACKAGES = [
# NOTE:As numpy has releases that break semver guaranteesand several other
# deps depend on numpy without an upper bound, we must install numpy before
# everything else.
'numpy ~= 1.19.2',
# Install other dependencies
'absl-py ~= 0.10',
'astunparse ~= 1.6.3',
'flatbuffers ~= 1.12.0',
'google_pasta ~= 0.2',
'h5py ~= 3.1.0',
'keras_preprocessing ~= 1.1.2',
'opt_einsum ~= 3.3.0',
'protobuf >= 3.9.2',
'six ~= 1.15.0',
'termcolor ~= 1.1.0',
'typing_extensions ~= 3.7.4',
'wheel ~= 0.35',
'wrapt ~= 1.12.1',
# These packages need to be pinned exactly as newer versions are
# incompatible with the rest of the ecosystem
'gast == 0.4.0',
# TensorFlow ecosystem packages that TF exposes API for
# These need to be in sync with the existing TF version
# They are updated during the release process
# When updating these, please also update the nightly versions below
'tensorboard ~= 2.5',
'tensorflow-estimator >= 2.5.0 , < 2.6.0',
# TODO(scottzhu) : OSS keras hasn't been formally released yet.
# Use keras - nightly at the moment.
'keras-nightly ~= 2.5.0.dev',
]
1.1.3. 【补充知识】版本号说明
版本号分为major,minor,patch。分别对应第一,二,三位。
1.2.0
major.minor.patch
~的意思是:
如果有minor,则patch可以变,minor不能变。
如果没有minor,则minor,patch可变,major不能变。
例如:
~1.2.0 ===> 1.2.0 <= x < 1.3.0
~1.3 ===> 1.3.0 <= x < 1.4.0
~2 ===> 2.0.0 <= x < 3.0.0
^ 表示左边第一位非0的版本号不变,其他可变。
例子:
major
major非0 ^1.2.2 ===> 1.2.2 <= x < 2.0.0
minor非0 ^0.1.2 ===> 0.1.2 <= x < 0.