2021年11月27日記事を修正しました。
はじめに
現時点でMXNet 2.0(ベータ)ではGluonCVが使えません。どうしてもGluonCVの学習済みモデルが使いたい時はいったんMXNet 1.xでモデルをdownloadしてexportしておく必要があります。その手順を示します。手順
MXNet 1.xでモデルをdownloadしてexport
ここではGluonCVが必要です。from gluoncv import model_zoo from gluoncv.utils import export_block net = model_zoo.get_model('ResNet152_v2', pretrained=True, root='models') net.hybridize() export_block('resnet152', net, preprocess=None, layout='CHW') with open('class_names.txt', 'w') as f: f.writelines('\n'.join(net.classes))
MXNet 2.0(ベータ)でモデルを読み込んで使用する
ここではGluonCVは必要ありません。from mxnet import np, npx, gluon, image from mxnet.gluon.data.vision import transforms device = npx.gpu() if npx.num_gpus() > 0 else npx.cpu() with open('class_names.txt', 'r') as f: classes = [x.strip() for x in f.readlines()] url = 'https://upload.wikimedia.org/wikipedia/commons/thumb/b/b5/Golden_Retriever_medium-to-light-coat.jpg/365px-Golden_Retriever_medium-to-light-coat.jpg' img = gluon.utils.download(url) x = image.imread(img) x = image.resize_short(x, 256) x, _ = image.center_crop(x, (224,224)) net = gluon.SymbolBlock.imports("resnet152-symbol.json",['data'], "resnet152-0000.params") net.reset_device(device) transformer = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))]) prob = npx.softmax(net(np.expand_dims(transformer(x), axis=0).to_device(device))) idx = npx.topk(prob, k=5)[0] for i in idx: print('With prob = %.5f, it contains %s' % ( prob[0, int(i)], classes[int(i)]))
結果
With prob = 0.99987, it contains golden retriever With prob = 0.00006, it contains Irish setter With prob = 0.00003, it contains Labrador retriever With prob = 0.00002, it contains tennis ball With prob = 0.00001, it contains flat-coated retriever
99.99%の確率でゴールデンレトリバーだと判定しています。
環境
GPUなし
Ubuntu 20.04LTS on WSL2 Python 3.8.10
certifi==2021.10.8 charset-normalizer==2.0.7 graphviz==0.8.4 idna==3.3 mxnet==2.0.0b20211105 numpy==1.21.4 pkg_resources==0.0.0 requests==2.26.0 urllib3==1.26.7
以下の方法でその時点で最新のベータ版がインストールされます。
pip install mxnet --pre -f https://dist.mxnet.io/python/cpu
GPUあり
Ubuntu 20.04LTS on WSL2 Python 3.8.10
certifi==2021.10.8 charset-normalizer==2.0.7 graphviz==0.8.4 idna==3.3 mxnet-cu112==2.0.0b20211105 numpy==1.21.4 pkg_resources==0.0.0 requests==2.26.0 urllib3==1.26.7
以下の方法でその時点で最新のベータ版がインストールされます。
pip install mxnet-cu112 --pre -f https://dist.mxnet.io/python/cu112
つづき
物体検出モデルを使用する場合も書きました。touch-sp.hatenablog.com