使用 Apache MXNet(孵化中)进行推断 ResNet 50Model - 深度学习 AMI
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅中国的 Amazon Web Services 服务入门

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

使用 Apache MXNet(孵化中)进行推断 ResNet 50Model

如何使用预训练的 Apache MXNet(孵化中)模型和 Symbol API 在 MXNet 上进行图像推断

    • (Python 3 的选项)-激活 Python 3 Apache MXNet(孵化)环境:

      $ source activate mxnet_p36
    • (Python 2 的选项)-激活 Python 2 Apache MXNet(孵化)环境:

      $ source activate mxnet_p27
  1. 其余步骤假定您使用的是 mxnet_p36 环境。

  2. 使用您的首选文本编辑器来创建具有以下内容的脚本。此脚本将下载 ResNet-50 个模型文件(resnet-50-0000.params 和 resnet-50-symbol.json)和标签列表(synset.txt),下载猫图像以从预训练模型中获得预测结果,然后在标签列表的结果中查找,返回预测结果。

    import mxnet as mx import numpy as np path='http://data.mxnet.io/models/imagenet/' [mx.test_utils.download(path+'resnet/50-layers/resnet-50-0000.params'), mx.test_utils.download(path+'resnet/50-layers/resnet-50-symbol.json'), mx.test_utils.download(path+'synset.txt')] ctx = mx.cpu() with open('synset.txt', 'r') as f: labels = [l.rstrip() for l in f] sym, args, aux = mx.model.load_checkpoint('resnet-50', 0) fname = mx.test_utils.download('https://github.com/dmlc/web-data/blob/master/mxnet/doc/tutorials/python/predict_image/cat.jpg?raw=true') img = mx.image.imread(fname) # convert into format (batch, RGB, width, height) img = mx.image.imresize(img, 224, 224) # resize img = img.transpose((2, 0, 1)) # Channel first img = img.expand_dims(axis=0) # batchify img = img.astype(dtype='float32') args['data'] = img softmax = mx.nd.random_normal(shape=(1,)) args['softmax_label'] = softmax exe = sym.bind(ctx=ctx, args=args, aux_states=aux, grad_req='null') exe.forward() prob = exe.outputs[0].asnumpy() # print the top-5 prob = np.squeeze(prob) a = np.argsort(prob)[::-1] for i in a[0:5]: print('probability=%f, class=%s' %(prob[i], labels[i]))
  3. 然后运行脚本,您应看到一个如下所示的结果:

    probability=0.418679, class=n02119789 kit fox, Vulpes macrotis probability=0.293495, class=n02119022 red fox, Vulpes vulpes probability=0.029321, class=n02120505 grey fox, gray fox, Urocyon cinereoargenteus probability=0.026230, class=n02124075 Egyptian cat probability=0.022557, class=n02085620 Chihuahua