TensorFlow.js - 使用预训练的 ResNet50 网络

TensorFlow.js - Using pretrained ResNet50 network

我在 Python 中通过 Keras API 使用 TensorFlow 创建了一个神经网络,它利用 ResNet50 预训练网络能够对 133 种不同品种的狗进行分类。

我现在希望能够部署此模型,以便可以通过 TensorFlow.js 使用它,但是我在让 ResNet50 工作时遇到了困难。我能够毫无问题地将我从头创建的 NN 转移到 TensorFlow.js,但是使用预训练网络转移一个神经网络并不那么简单。

这是我要修改的 Python 代码:

from keras.applications.resnet50 import ResNet50
ResNet50_model = ResNet50(weights="imagenet") # download ImageNet challenge weights

def extractResNet50(tensor): # tensor shape is (1, 224, 224, 3)
    return ResNet50(weights='imagenet', include_top=False, pooling="avg").predict(preprocess_input(tensor))

def dogBreed(img_path):
    tensor = convertToTensor(img_path) # I can do this in TF.js already with no issue

    resnetTensor = extractResNet50(tensor) # tensor returned in shape (1, 2048)
    resnetTensor = np.expand_dims(resnetTensor, axis=0) # repeat this line 2 more times to get shape (1, 1, 1, 1, 2048)

    # code below I can convert to TF.js without issue
    prediction = model.predict(resnetTensor[0])

除了 dogBreed() 的代码行 1 和 4 之外,我如何将上面的所有内容转换为在 TensorFlow.js 中使用?

Resnet 是一个很大的网络,它还没有被导入浏览器,我怀疑它是否有一天会被导入。至少它不是最新版本的 tensorflowJs (version 0.14)

另一方面,你可以做的是保存你的 Python keras 模型,然后在 Js 上导入冻结模型进行预测。

更新: 您正在使用 resnet50 作为模型的特征提取器。在这种情况下,您将保存的冻结模型需要包含 Resnet50 以及您的模型拓扑和权重。

1- 与其在 python 中有两个独立的架构,不如直接使用 tensorflow 而不是 keras 创建一个网络。然后冻结的模型将包含 Resnet。这在浏览器中可能无法正常工作,因为 Resnet 的大小很大(我自己没有测试过)

2- 考虑使用可在浏览器中用作特征提取器的 coco-ssdmobilenet,而不是在浏览器中使用 Resnet。您可以在 official repo

上查看如何使用它们