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

时间:2019-01-23 11:31:08

标签: python tensorflow keras tensorflow.js

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

我现在希望能够部署此模型,以便可以通过TensorFlow.js使用它,但是我很难使ResNet50正常工作。我能够将我从头创建的NN毫无问题地传输到TensorFlow.js,但是使用预先训练的网络传输NN并不是那么简单。

这是我要适应的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中使用?

1 个答案:

答案 0 :(得分:1)

Resnet是如此庞大,以至于它尚未被导入浏览器中,我怀疑是否有一天会导入。至少它不是最新版本的tensorflowJs(版本0.14

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

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

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

2-除了考虑使用mobilenet或{{1}}(可以在浏览器中用作特征提取器)以外,不要在浏览器中使用Resnet。您可以在official repo

上查看如何使用它们
相关问题