首页 > 解决方案 > 在浏览器中训练后在 tensorflow.js 中合并和保存模型

问题描述

我正在关注 tensorflow.js教程,其中我正在加载 mobilenet 作为主干

<html>
  <head>
    <!-- Load the latest version of TensorFlow.js -->
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/mobilenet"></script>
  </head>

在js中它被称为net

 net = await mobilenet.load();

然后教程通过添加“K-Nearest Neighbors Classifier”-Layer 继续

<script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/knn-classifier"></script>

然后通过调用它classifier

const classifier = knnClassifier.create();

然后将样本添加到分类器之后,为了进行预测,必须推断整个管道

// Get the activation from mobilenet.
const activation = net.infer(img, 'conv_preds');
// Then feed the activation to the custom output layer
const result = await classifier.predictClass(activation);

现在我想将整个模型 ( net+ classifier) 下载为 .hdf 文件或类似文件。我该怎么做呢?我还需要合并这两个吗?

我知道model.savepython tensorflow 和 keras 中的功能,但我不知道如何在 tensorflow.js 中最好地做到这一点

更新 - 目前我正在尝试一些类似的东西

  // merging the model and then downloading it
  const merge_models = async (backbone, outputlayer) => {
      console.log('Downloading your model..');
    const model = tf.sequential();
    model.add(backbone);
    model.add(outputlayer);
    
    // download
    await model.save('downloads://my-model');
    console.log('..is completed.');
  };

但我在添加功能中遇到错误

TypeError: Cannot read properties of undefined (reading 'length')

标签: javascripthtmltensorflowmachine-learningtensorflow.js

解决方案


推荐阅读