核心 TensorFlow
库提供了将在 Python
中创建的模型转换为保存到描述图形和权重的 JSON
文件的能力在浏览器环境中执行。
在示例中,您需要在浏览器中加载整个 TensorFlow
库,这非常繁重。此库也不可使用 tree shaking。
我的问题是:如何将 TensorFlow JS
中的必要元素加载到客户端/浏览器中以减小捆绑应用程序的整体大小?
编辑:我们正在努力减少捆绑库的超大尺寸。
最佳答案
Tensorflow.js API 结合了四个包:
- tfjs-core : 数学函数和后端支持等功能
- tfjs-layers : 支持层创建模型(依赖于
tfjs-core
) - tfjs-data : 数据处理(依赖于
tfjs-core
) - tfjs-converter : 支持将模型转换为 Tensorflow.js
根据您确切需要执行的任务,仅使用一些包可能就足够了。也就是说,请记住 tfjs-layers
和 tfjs-data
需要导入 tfjs-core
。
代码示例
以下几行仅导入 Core 和 Layers API:
import * as tfc from '@tensorflow/tfjs-core';
import * as tfl from '@tensorflow/tfjs-layers';
// Examples how to use the APIs
const vectr = tfc.tensor(/* .. */);
const model = tfl.sequential();
const dense = tfl.layers.dense(/* .. */);
请注意,像 tf.matMul
这样的函数是通过调用 tfc.matMul
使用的,但是图层 API 的一些函数(如 tf.layers.dense
)是通过调用 tfl.layers.dense
使用的而其他的(如 tf.sequential
)则通过调用 tfl.sequential
使用。
优化
为了让您了解潜在的优化,让我们看一下数字:
--------------------------------------
| Package | Size | Relative |
|----------------|--------|----------|
| tfjs | 856 | 100% |
| tfjs-core | 506 | 59% |
| tfjs-layers | 228 | 27% |
| tfjs-data | 52 | 6% |
| tfjs-converter | 80 | 9% |
--------------------------------------
版本 1.2.7,以 KB 为单位的大小(缩小后的 JS 文件),与 tfjs 相比的相对值
直接使用 tfjs-core
和 tfjs-layers
,可以将大小缩小 122 KB 或 14%。如果你需要更多,你总是可以尝试自己重建存储库,删除任何不需要的功能。当然,这种方法意味着大量的手动工作。
摇树
正如您自己已经注意到的,目前不支持 tree shaking,但您可能希望关注 tfjs github 存储库中关于该主题的 support of tree-shaking 的讨论。
关于javascript - 将 python TensorFlow Layers 模型加载到 JavaScript 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57540443/