深度学习 AMI
开发人员指南
AWS 文档中描述的 AWS 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅中国的 AWS 服务入门

将 Apache MXNet for Inference 与 ResNet 50 模型结合使用

如何将预训练的 MXNet 模型与 Symbol API for Image Inference 和 MXNet 结合使用

    • (适用于 Python 3 的选项)- 激活 Python 3 MXNet 环境:

      $ source activate mxnet_p36
    • (适用于 Python 2 的选项)- 激活 Python 2 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